VectorUtils.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  1. //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This file defines vectorizer utilities.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "llvm/Analysis/VectorUtils.h"
  14. #include "llvm/ADT/EquivalenceClasses.h"
  15. #include "llvm/Analysis/DemandedBits.h"
  16. #include "llvm/Analysis/LoopInfo.h"
  17. #include "llvm/Analysis/LoopIterator.h"
  18. #include "llvm/Analysis/ScalarEvolution.h"
  19. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  20. #include "llvm/Analysis/TargetTransformInfo.h"
  21. #include "llvm/Analysis/ValueTracking.h"
  22. #include "llvm/IR/Constants.h"
  23. #include "llvm/IR/GetElementPtrTypeIterator.h"
  24. #include "llvm/IR/IRBuilder.h"
  25. #include "llvm/IR/PatternMatch.h"
  26. #include "llvm/IR/Value.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.
  38. bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
  39. switch (ID) {
  40. case Intrinsic::bswap: // Begin integer bit-manipulation.
  41. case Intrinsic::bitreverse:
  42. case Intrinsic::ctpop:
  43. case Intrinsic::ctlz:
  44. case Intrinsic::cttz:
  45. case Intrinsic::fshl:
  46. case Intrinsic::fshr:
  47. case Intrinsic::sqrt: // Begin floating-point.
  48. case Intrinsic::sin:
  49. case Intrinsic::cos:
  50. case Intrinsic::exp:
  51. case Intrinsic::exp2:
  52. case Intrinsic::log:
  53. case Intrinsic::log10:
  54. case Intrinsic::log2:
  55. case Intrinsic::fabs:
  56. case Intrinsic::minnum:
  57. case Intrinsic::maxnum:
  58. case Intrinsic::minimum:
  59. case Intrinsic::maximum:
  60. case Intrinsic::copysign:
  61. case Intrinsic::floor:
  62. case Intrinsic::ceil:
  63. case Intrinsic::trunc:
  64. case Intrinsic::rint:
  65. case Intrinsic::nearbyint:
  66. case Intrinsic::round:
  67. case Intrinsic::pow:
  68. case Intrinsic::fma:
  69. case Intrinsic::fmuladd:
  70. case Intrinsic::powi:
  71. case Intrinsic::canonicalize:
  72. return true;
  73. default:
  74. return false;
  75. }
  76. }
  77. /// Identifies if the intrinsic has a scalar operand. It check for
  78. /// ctlz,cttz and powi special intrinsics whose argument is scalar.
  79. bool llvm::hasVectorInstrinsicScalarOpd(Intrinsic::ID ID,
  80. unsigned ScalarOpdIdx) {
  81. switch (ID) {
  82. case Intrinsic::ctlz:
  83. case Intrinsic::cttz:
  84. case Intrinsic::powi:
  85. return (ScalarOpdIdx == 1);
  86. default:
  87. return false;
  88. }
  89. }
  90. /// Returns intrinsic ID for call.
  91. /// For the input call instruction it finds mapping intrinsic and returns
  92. /// its ID, in case it does not found it return not_intrinsic.
  93. Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI,
  94. const TargetLibraryInfo *TLI) {
  95. Intrinsic::ID ID = getIntrinsicForCallSite(CI, TLI);
  96. if (ID == Intrinsic::not_intrinsic)
  97. return Intrinsic::not_intrinsic;
  98. if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
  99. ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
  100. ID == Intrinsic::sideeffect)
  101. return ID;
  102. return Intrinsic::not_intrinsic;
  103. }
  104. /// Find the operand of the GEP that should be checked for consecutive
  105. /// stores. This ignores trailing indices that have no effect on the final
  106. /// pointer.
  107. unsigned llvm::getGEPInductionOperand(const GetElementPtrInst *Gep) {
  108. const DataLayout &DL = Gep->getModule()->getDataLayout();
  109. unsigned LastOperand = Gep->getNumOperands() - 1;
  110. unsigned GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
  111. // Walk backwards and try to peel off zeros.
  112. while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
  113. // Find the type we're currently indexing into.
  114. gep_type_iterator GEPTI = gep_type_begin(Gep);
  115. std::advance(GEPTI, LastOperand - 2);
  116. // If it's a type with the same allocation size as the result of the GEP we
  117. // can peel off the zero index.
  118. if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize)
  119. break;
  120. --LastOperand;
  121. }
  122. return LastOperand;
  123. }
  124. /// If the argument is a GEP, then returns the operand identified by
  125. /// getGEPInductionOperand. However, if there is some other non-loop-invariant
  126. /// operand, it returns that instead.
  127. Value *llvm::stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
  128. GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  129. if (!GEP)
  130. return Ptr;
  131. unsigned InductionOperand = getGEPInductionOperand(GEP);
  132. // Check that all of the gep indices are uniform except for our induction
  133. // operand.
  134. for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
  135. if (i != InductionOperand &&
  136. !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
  137. return Ptr;
  138. return GEP->getOperand(InductionOperand);
  139. }
  140. /// If a value has only one user that is a CastInst, return it.
  141. Value *llvm::getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
  142. Value *UniqueCast = nullptr;
  143. for (User *U : Ptr->users()) {
  144. CastInst *CI = dyn_cast<CastInst>(U);
  145. if (CI && CI->getType() == Ty) {
  146. if (!UniqueCast)
  147. UniqueCast = CI;
  148. else
  149. return nullptr;
  150. }
  151. }
  152. return UniqueCast;
  153. }
  154. /// Get the stride of a pointer access in a loop. Looks for symbolic
  155. /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
  156. Value *llvm::getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
  157. auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
  158. if (!PtrTy || PtrTy->isAggregateType())
  159. return nullptr;
  160. // Try to remove a gep instruction to make the pointer (actually index at this
  161. // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
  162. // pointer, otherwise, we are analyzing the index.
  163. Value *OrigPtr = Ptr;
  164. // The size of the pointer access.
  165. int64_t PtrAccessSize = 1;
  166. Ptr = stripGetElementPtr(Ptr, SE, Lp);
  167. const SCEV *V = SE->getSCEV(Ptr);
  168. if (Ptr != OrigPtr)
  169. // Strip off casts.
  170. while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
  171. V = C->getOperand();
  172. const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
  173. if (!S)
  174. return nullptr;
  175. V = S->getStepRecurrence(*SE);
  176. if (!V)
  177. return nullptr;
  178. // Strip off the size of access multiplication if we are still analyzing the
  179. // pointer.
  180. if (OrigPtr == Ptr) {
  181. if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
  182. if (M->getOperand(0)->getSCEVType() != scConstant)
  183. return nullptr;
  184. const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
  185. // Huge step value - give up.
  186. if (APStepVal.getBitWidth() > 64)
  187. return nullptr;
  188. int64_t StepVal = APStepVal.getSExtValue();
  189. if (PtrAccessSize != StepVal)
  190. return nullptr;
  191. V = M->getOperand(1);
  192. }
  193. }
  194. // Strip off casts.
  195. Type *StripedOffRecurrenceCast = nullptr;
  196. if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
  197. StripedOffRecurrenceCast = C->getType();
  198. V = C->getOperand();
  199. }
  200. // Look for the loop invariant symbolic value.
  201. const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
  202. if (!U)
  203. return nullptr;
  204. Value *Stride = U->getValue();
  205. if (!Lp->isLoopInvariant(Stride))
  206. return nullptr;
  207. // If we have stripped off the recurrence cast we have to make sure that we
  208. // return the value that is used in this loop so that we can replace it later.
  209. if (StripedOffRecurrenceCast)
  210. Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
  211. return Stride;
  212. }
  213. /// Given a vector and an element number, see if the scalar value is
  214. /// already around as a register, for example if it were inserted then extracted
  215. /// from the vector.
  216. Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
  217. assert(V->getType()->isVectorTy() && "Not looking at a vector?");
  218. VectorType *VTy = cast<VectorType>(V->getType());
  219. unsigned Width = VTy->getNumElements();
  220. if (EltNo >= Width) // Out of range access.
  221. return UndefValue::get(VTy->getElementType());
  222. if (Constant *C = dyn_cast<Constant>(V))
  223. return C->getAggregateElement(EltNo);
  224. if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
  225. // If this is an insert to a variable element, we don't know what it is.
  226. if (!isa<ConstantInt>(III->getOperand(2)))
  227. return nullptr;
  228. unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
  229. // If this is an insert to the element we are looking for, return the
  230. // inserted value.
  231. if (EltNo == IIElt)
  232. return III->getOperand(1);
  233. // Otherwise, the insertelement doesn't modify the value, recurse on its
  234. // vector input.
  235. return findScalarElement(III->getOperand(0), EltNo);
  236. }
  237. if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
  238. unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
  239. int InEl = SVI->getMaskValue(EltNo);
  240. if (InEl < 0)
  241. return UndefValue::get(VTy->getElementType());
  242. if (InEl < (int)LHSWidth)
  243. return findScalarElement(SVI->getOperand(0), InEl);
  244. return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
  245. }
  246. // Extract a value from a vector add operation with a constant zero.
  247. // TODO: Use getBinOpIdentity() to generalize this.
  248. Value *Val; Constant *C;
  249. if (match(V, m_Add(m_Value(Val), m_Constant(C))))
  250. if (Constant *Elt = C->getAggregateElement(EltNo))
  251. if (Elt->isNullValue())
  252. return findScalarElement(Val, EltNo);
  253. // Otherwise, we don't know.
  254. return nullptr;
  255. }
  256. /// Get splat value if the input is a splat vector or return nullptr.
  257. /// This function is not fully general. It checks only 2 cases:
  258. /// the input value is (1) a splat constants vector or (2) a sequence
  259. /// of instructions that broadcast a single value into a vector.
  260. ///
  261. const llvm::Value *llvm::getSplatValue(const Value *V) {
  262. if (auto *C = dyn_cast<Constant>(V))
  263. if (isa<VectorType>(V->getType()))
  264. return C->getSplatValue();
  265. auto *ShuffleInst = dyn_cast<ShuffleVectorInst>(V);
  266. if (!ShuffleInst)
  267. return nullptr;
  268. // All-zero (or undef) shuffle mask elements.
  269. for (int MaskElt : ShuffleInst->getShuffleMask())
  270. if (MaskElt != 0 && MaskElt != -1)
  271. return nullptr;
  272. // The first shuffle source is 'insertelement' with index 0.
  273. auto *InsertEltInst =
  274. dyn_cast<InsertElementInst>(ShuffleInst->getOperand(0));
  275. if (!InsertEltInst || !isa<ConstantInt>(InsertEltInst->getOperand(2)) ||
  276. !cast<ConstantInt>(InsertEltInst->getOperand(2))->isZero())
  277. return nullptr;
  278. return InsertEltInst->getOperand(1);
  279. }
  280. MapVector<Instruction *, uint64_t>
  281. llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB,
  282. const TargetTransformInfo *TTI) {
  283. // DemandedBits will give us every value's live-out bits. But we want
  284. // to ensure no extra casts would need to be inserted, so every DAG
  285. // of connected values must have the same minimum bitwidth.
  286. EquivalenceClasses<Value *> ECs;
  287. SmallVector<Value *, 16> Worklist;
  288. SmallPtrSet<Value *, 4> Roots;
  289. SmallPtrSet<Value *, 16> Visited;
  290. DenseMap<Value *, uint64_t> DBits;
  291. SmallPtrSet<Instruction *, 4> InstructionSet;
  292. MapVector<Instruction *, uint64_t> MinBWs;
  293. // Determine the roots. We work bottom-up, from truncs or icmps.
  294. bool SeenExtFromIllegalType = false;
  295. for (auto *BB : Blocks)
  296. for (auto &I : *BB) {
  297. InstructionSet.insert(&I);
  298. if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
  299. !TTI->isTypeLegal(I.getOperand(0)->getType()))
  300. SeenExtFromIllegalType = true;
  301. // Only deal with non-vector integers up to 64-bits wide.
  302. if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
  303. !I.getType()->isVectorTy() &&
  304. I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
  305. // Don't make work for ourselves. If we know the loaded type is legal,
  306. // don't add it to the worklist.
  307. if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
  308. continue;
  309. Worklist.push_back(&I);
  310. Roots.insert(&I);
  311. }
  312. }
  313. // Early exit.
  314. if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
  315. return MinBWs;
  316. // Now proceed breadth-first, unioning values together.
  317. while (!Worklist.empty()) {
  318. Value *Val = Worklist.pop_back_val();
  319. Value *Leader = ECs.getOrInsertLeaderValue(Val);
  320. if (Visited.count(Val))
  321. continue;
  322. Visited.insert(Val);
  323. // Non-instructions terminate a chain successfully.
  324. if (!isa<Instruction>(Val))
  325. continue;
  326. Instruction *I = cast<Instruction>(Val);
  327. // If we encounter a type that is larger than 64 bits, we can't represent
  328. // it so bail out.
  329. if (DB.getDemandedBits(I).getBitWidth() > 64)
  330. return MapVector<Instruction *, uint64_t>();
  331. uint64_t V = DB.getDemandedBits(I).getZExtValue();
  332. DBits[Leader] |= V;
  333. DBits[I] = V;
  334. // Casts, loads and instructions outside of our range terminate a chain
  335. // successfully.
  336. if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
  337. !InstructionSet.count(I))
  338. continue;
  339. // Unsafe casts terminate a chain unsuccessfully. We can't do anything
  340. // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
  341. // transform anything that relies on them.
  342. if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
  343. !I->getType()->isIntegerTy()) {
  344. DBits[Leader] |= ~0ULL;
  345. continue;
  346. }
  347. // We don't modify the types of PHIs. Reductions will already have been
  348. // truncated if possible, and inductions' sizes will have been chosen by
  349. // indvars.
  350. if (isa<PHINode>(I))
  351. continue;
  352. if (DBits[Leader] == ~0ULL)
  353. // All bits demanded, no point continuing.
  354. continue;
  355. for (Value *O : cast<User>(I)->operands()) {
  356. ECs.unionSets(Leader, O);
  357. Worklist.push_back(O);
  358. }
  359. }
  360. // Now we've discovered all values, walk them to see if there are
  361. // any users we didn't see. If there are, we can't optimize that
  362. // chain.
  363. for (auto &I : DBits)
  364. for (auto *U : I.first->users())
  365. if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
  366. DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
  367. for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
  368. uint64_t LeaderDemandedBits = 0;
  369. for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
  370. LeaderDemandedBits |= DBits[*MI];
  371. uint64_t MinBW = (sizeof(LeaderDemandedBits) * 8) -
  372. llvm::countLeadingZeros(LeaderDemandedBits);
  373. // Round up to a power of 2
  374. if (!isPowerOf2_64((uint64_t)MinBW))
  375. MinBW = NextPowerOf2(MinBW);
  376. // We don't modify the types of PHIs. Reductions will already have been
  377. // truncated if possible, and inductions' sizes will have been chosen by
  378. // indvars.
  379. // If we are required to shrink a PHI, abandon this entire equivalence class.
  380. bool Abort = false;
  381. for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
  382. if (isa<PHINode>(*MI) && MinBW < (*MI)->getType()->getScalarSizeInBits()) {
  383. Abort = true;
  384. break;
  385. }
  386. if (Abort)
  387. continue;
  388. for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI) {
  389. if (!isa<Instruction>(*MI))
  390. continue;
  391. Type *Ty = (*MI)->getType();
  392. if (Roots.count(*MI))
  393. Ty = cast<Instruction>(*MI)->getOperand(0)->getType();
  394. if (MinBW < Ty->getScalarSizeInBits())
  395. MinBWs[cast<Instruction>(*MI)] = MinBW;
  396. }
  397. }
  398. return MinBWs;
  399. }
  400. /// Add all access groups in @p AccGroups to @p List.
  401. template <typename ListT>
  402. static void addToAccessGroupList(ListT &List, MDNode *AccGroups) {
  403. // Interpret an access group as a list containing itself.
  404. if (AccGroups->getNumOperands() == 0) {
  405. assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group");
  406. List.insert(AccGroups);
  407. return;
  408. }
  409. for (auto &AccGroupListOp : AccGroups->operands()) {
  410. auto *Item = cast<MDNode>(AccGroupListOp.get());
  411. assert(isValidAsAccessGroup(Item) && "List item must be an access group");
  412. List.insert(Item);
  413. }
  414. };
  415. MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) {
  416. if (!AccGroups1)
  417. return AccGroups2;
  418. if (!AccGroups2)
  419. return AccGroups1;
  420. if (AccGroups1 == AccGroups2)
  421. return AccGroups1;
  422. SmallSetVector<Metadata *, 4> Union;
  423. addToAccessGroupList(Union, AccGroups1);
  424. addToAccessGroupList(Union, AccGroups2);
  425. if (Union.size() == 0)
  426. return nullptr;
  427. if (Union.size() == 1)
  428. return cast<MDNode>(Union.front());
  429. LLVMContext &Ctx = AccGroups1->getContext();
  430. return MDNode::get(Ctx, Union.getArrayRef());
  431. }
  432. MDNode *llvm::intersectAccessGroups(const Instruction *Inst1,
  433. const Instruction *Inst2) {
  434. bool MayAccessMem1 = Inst1->mayReadOrWriteMemory();
  435. bool MayAccessMem2 = Inst2->mayReadOrWriteMemory();
  436. if (!MayAccessMem1 && !MayAccessMem2)
  437. return nullptr;
  438. if (!MayAccessMem1)
  439. return Inst2->getMetadata(LLVMContext::MD_access_group);
  440. if (!MayAccessMem2)
  441. return Inst1->getMetadata(LLVMContext::MD_access_group);
  442. MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group);
  443. MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group);
  444. if (!MD1 || !MD2)
  445. return nullptr;
  446. if (MD1 == MD2)
  447. return MD1;
  448. // Use set for scalable 'contains' check.
  449. SmallPtrSet<Metadata *, 4> AccGroupSet2;
  450. addToAccessGroupList(AccGroupSet2, MD2);
  451. SmallVector<Metadata *, 4> Intersection;
  452. if (MD1->getNumOperands() == 0) {
  453. assert(isValidAsAccessGroup(MD1) && "Node must be an access group");
  454. if (AccGroupSet2.count(MD1))
  455. Intersection.push_back(MD1);
  456. } else {
  457. for (const MDOperand &Node : MD1->operands()) {
  458. auto *Item = cast<MDNode>(Node.get());
  459. assert(isValidAsAccessGroup(Item) && "List item must be an access group");
  460. if (AccGroupSet2.count(Item))
  461. Intersection.push_back(Item);
  462. }
  463. }
  464. if (Intersection.size() == 0)
  465. return nullptr;
  466. if (Intersection.size() == 1)
  467. return cast<MDNode>(Intersection.front());
  468. LLVMContext &Ctx = Inst1->getContext();
  469. return MDNode::get(Ctx, Intersection);
  470. }
  471. /// \returns \p I after propagating metadata from \p VL.
  472. Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
  473. Instruction *I0 = cast<Instruction>(VL[0]);
  474. SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
  475. I0->getAllMetadataOtherThanDebugLoc(Metadata);
  476. for (auto Kind : {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
  477. LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
  478. LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load,
  479. LLVMContext::MD_access_group}) {
  480. MDNode *MD = I0->getMetadata(Kind);
  481. for (int J = 1, E = VL.size(); MD && J != E; ++J) {
  482. const Instruction *IJ = cast<Instruction>(VL[J]);
  483. MDNode *IMD = IJ->getMetadata(Kind);
  484. switch (Kind) {
  485. case LLVMContext::MD_tbaa:
  486. MD = MDNode::getMostGenericTBAA(MD, IMD);
  487. break;
  488. case LLVMContext::MD_alias_scope:
  489. MD = MDNode::getMostGenericAliasScope(MD, IMD);
  490. break;
  491. case LLVMContext::MD_fpmath:
  492. MD = MDNode::getMostGenericFPMath(MD, IMD);
  493. break;
  494. case LLVMContext::MD_noalias:
  495. case LLVMContext::MD_nontemporal:
  496. case LLVMContext::MD_invariant_load:
  497. MD = MDNode::intersect(MD, IMD);
  498. break;
  499. case LLVMContext::MD_access_group:
  500. MD = intersectAccessGroups(Inst, IJ);
  501. break;
  502. default:
  503. llvm_unreachable("unhandled metadata");
  504. }
  505. }
  506. Inst->setMetadata(Kind, MD);
  507. }
  508. return Inst;
  509. }
  510. Constant *
  511. llvm::createBitMaskForGaps(IRBuilder<> &Builder, unsigned VF,
  512. const InterleaveGroup<Instruction> &Group) {
  513. // All 1's means mask is not needed.
  514. if (Group.getNumMembers() == Group.getFactor())
  515. return nullptr;
  516. // TODO: support reversed access.
  517. assert(!Group.isReverse() && "Reversed group not supported.");
  518. SmallVector<Constant *, 16> Mask;
  519. for (unsigned i = 0; i < VF; i++)
  520. for (unsigned j = 0; j < Group.getFactor(); ++j) {
  521. unsigned HasMember = Group.getMember(j) ? 1 : 0;
  522. Mask.push_back(Builder.getInt1(HasMember));
  523. }
  524. return ConstantVector::get(Mask);
  525. }
  526. Constant *llvm::createReplicatedMask(IRBuilder<> &Builder,
  527. unsigned ReplicationFactor, unsigned VF) {
  528. SmallVector<Constant *, 16> MaskVec;
  529. for (unsigned i = 0; i < VF; i++)
  530. for (unsigned j = 0; j < ReplicationFactor; j++)
  531. MaskVec.push_back(Builder.getInt32(i));
  532. return ConstantVector::get(MaskVec);
  533. }
  534. Constant *llvm::createInterleaveMask(IRBuilder<> &Builder, unsigned VF,
  535. unsigned NumVecs) {
  536. SmallVector<Constant *, 16> Mask;
  537. for (unsigned i = 0; i < VF; i++)
  538. for (unsigned j = 0; j < NumVecs; j++)
  539. Mask.push_back(Builder.getInt32(j * VF + i));
  540. return ConstantVector::get(Mask);
  541. }
  542. Constant *llvm::createStrideMask(IRBuilder<> &Builder, unsigned Start,
  543. unsigned Stride, unsigned VF) {
  544. SmallVector<Constant *, 16> Mask;
  545. for (unsigned i = 0; i < VF; i++)
  546. Mask.push_back(Builder.getInt32(Start + i * Stride));
  547. return ConstantVector::get(Mask);
  548. }
  549. Constant *llvm::createSequentialMask(IRBuilder<> &Builder, unsigned Start,
  550. unsigned NumInts, unsigned NumUndefs) {
  551. SmallVector<Constant *, 16> Mask;
  552. for (unsigned i = 0; i < NumInts; i++)
  553. Mask.push_back(Builder.getInt32(Start + i));
  554. Constant *Undef = UndefValue::get(Builder.getInt32Ty());
  555. for (unsigned i = 0; i < NumUndefs; i++)
  556. Mask.push_back(Undef);
  557. return ConstantVector::get(Mask);
  558. }
  559. /// A helper function for concatenating vectors. This function concatenates two
  560. /// vectors having the same element type. If the second vector has fewer
  561. /// elements than the first, it is padded with undefs.
  562. static Value *concatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
  563. Value *V2) {
  564. VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
  565. VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
  566. assert(VecTy1 && VecTy2 &&
  567. VecTy1->getScalarType() == VecTy2->getScalarType() &&
  568. "Expect two vectors with the same element type");
  569. unsigned NumElts1 = VecTy1->getNumElements();
  570. unsigned NumElts2 = VecTy2->getNumElements();
  571. assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
  572. if (NumElts1 > NumElts2) {
  573. // Extend with UNDEFs.
  574. Constant *ExtMask =
  575. createSequentialMask(Builder, 0, NumElts2, NumElts1 - NumElts2);
  576. V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
  577. }
  578. Constant *Mask = createSequentialMask(Builder, 0, NumElts1 + NumElts2, 0);
  579. return Builder.CreateShuffleVector(V1, V2, Mask);
  580. }
  581. Value *llvm::concatenateVectors(IRBuilder<> &Builder, ArrayRef<Value *> Vecs) {
  582. unsigned NumVecs = Vecs.size();
  583. assert(NumVecs > 1 && "Should be at least two vectors");
  584. SmallVector<Value *, 8> ResList;
  585. ResList.append(Vecs.begin(), Vecs.end());
  586. do {
  587. SmallVector<Value *, 8> TmpList;
  588. for (unsigned i = 0; i < NumVecs - 1; i += 2) {
  589. Value *V0 = ResList[i], *V1 = ResList[i + 1];
  590. assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
  591. "Only the last vector may have a different type");
  592. TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
  593. }
  594. // Push the last vector if the total number of vectors is odd.
  595. if (NumVecs % 2 != 0)
  596. TmpList.push_back(ResList[NumVecs - 1]);
  597. ResList = TmpList;
  598. NumVecs = ResList.size();
  599. } while (NumVecs > 1);
  600. return ResList[0];
  601. }
  602. bool InterleavedAccessInfo::isStrided(int Stride) {
  603. unsigned Factor = std::abs(Stride);
  604. return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
  605. }
  606. void InterleavedAccessInfo::collectConstStrideAccesses(
  607. MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
  608. const ValueToValueMap &Strides) {
  609. auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
  610. // Since it's desired that the load/store instructions be maintained in
  611. // "program order" for the interleaved access analysis, we have to visit the
  612. // blocks in the loop in reverse postorder (i.e., in a topological order).
  613. // Such an ordering will ensure that any load/store that may be executed
  614. // before a second load/store will precede the second load/store in
  615. // AccessStrideInfo.
  616. LoopBlocksDFS DFS(TheLoop);
  617. DFS.perform(LI);
  618. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
  619. for (auto &I : *BB) {
  620. auto *LI = dyn_cast<LoadInst>(&I);
  621. auto *SI = dyn_cast<StoreInst>(&I);
  622. if (!LI && !SI)
  623. continue;
  624. Value *Ptr = getLoadStorePointerOperand(&I);
  625. // We don't check wrapping here because we don't know yet if Ptr will be
  626. // part of a full group or a group with gaps. Checking wrapping for all
  627. // pointers (even those that end up in groups with no gaps) will be overly
  628. // conservative. For full groups, wrapping should be ok since if we would
  629. // wrap around the address space we would do a memory access at nullptr
  630. // even without the transformation. The wrapping checks are therefore
  631. // deferred until after we've formed the interleaved groups.
  632. int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
  633. /*Assume=*/true, /*ShouldCheckWrap=*/false);
  634. const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
  635. PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
  636. uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
  637. // An alignment of 0 means target ABI alignment.
  638. unsigned Align = getLoadStoreAlignment(&I);
  639. if (!Align)
  640. Align = DL.getABITypeAlignment(PtrTy->getElementType());
  641. AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
  642. }
  643. }
  644. // Analyze interleaved accesses and collect them into interleaved load and
  645. // store groups.
  646. //
  647. // When generating code for an interleaved load group, we effectively hoist all
  648. // loads in the group to the location of the first load in program order. When
  649. // generating code for an interleaved store group, we sink all stores to the
  650. // location of the last store. This code motion can change the order of load
  651. // and store instructions and may break dependences.
  652. //
  653. // The code generation strategy mentioned above ensures that we won't violate
  654. // any write-after-read (WAR) dependences.
  655. //
  656. // E.g., for the WAR dependence: a = A[i]; // (1)
  657. // A[i] = b; // (2)
  658. //
  659. // The store group of (2) is always inserted at or below (2), and the load
  660. // group of (1) is always inserted at or above (1). Thus, the instructions will
  661. // never be reordered. All other dependences are checked to ensure the
  662. // correctness of the instruction reordering.
  663. //
  664. // The algorithm visits all memory accesses in the loop in bottom-up program
  665. // order. Program order is established by traversing the blocks in the loop in
  666. // reverse postorder when collecting the accesses.
  667. //
  668. // We visit the memory accesses in bottom-up order because it can simplify the
  669. // construction of store groups in the presence of write-after-write (WAW)
  670. // dependences.
  671. //
  672. // E.g., for the WAW dependence: A[i] = a; // (1)
  673. // A[i] = b; // (2)
  674. // A[i + 1] = c; // (3)
  675. //
  676. // We will first create a store group with (3) and (2). (1) can't be added to
  677. // this group because it and (2) are dependent. However, (1) can be grouped
  678. // with other accesses that may precede it in program order. Note that a
  679. // bottom-up order does not imply that WAW dependences should not be checked.
  680. void InterleavedAccessInfo::analyzeInterleaving(
  681. bool EnablePredicatedInterleavedMemAccesses) {
  682. LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
  683. const ValueToValueMap &Strides = LAI->getSymbolicStrides();
  684. // Holds all accesses with a constant stride.
  685. MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
  686. collectConstStrideAccesses(AccessStrideInfo, Strides);
  687. if (AccessStrideInfo.empty())
  688. return;
  689. // Collect the dependences in the loop.
  690. collectDependences();
  691. // Holds all interleaved store groups temporarily.
  692. SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups;
  693. // Holds all interleaved load groups temporarily.
  694. SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups;
  695. // Search in bottom-up program order for pairs of accesses (A and B) that can
  696. // form interleaved load or store groups. In the algorithm below, access A
  697. // precedes access B in program order. We initialize a group for B in the
  698. // outer loop of the algorithm, and then in the inner loop, we attempt to
  699. // insert each A into B's group if:
  700. //
  701. // 1. A and B have the same stride,
  702. // 2. A and B have the same memory object size, and
  703. // 3. A belongs in B's group according to its distance from B.
  704. //
  705. // Special care is taken to ensure group formation will not break any
  706. // dependences.
  707. for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
  708. BI != E; ++BI) {
  709. Instruction *B = BI->first;
  710. StrideDescriptor DesB = BI->second;
  711. // Initialize a group for B if it has an allowable stride. Even if we don't
  712. // create a group for B, we continue with the bottom-up algorithm to ensure
  713. // we don't break any of B's dependences.
  714. InterleaveGroup<Instruction> *Group = nullptr;
  715. if (isStrided(DesB.Stride) &&
  716. (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
  717. Group = getInterleaveGroup(B);
  718. if (!Group) {
  719. LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
  720. << '\n');
  721. Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
  722. }
  723. if (B->mayWriteToMemory())
  724. StoreGroups.insert(Group);
  725. else
  726. LoadGroups.insert(Group);
  727. }
  728. for (auto AI = std::next(BI); AI != E; ++AI) {
  729. Instruction *A = AI->first;
  730. StrideDescriptor DesA = AI->second;
  731. // Our code motion strategy implies that we can't have dependences
  732. // between accesses in an interleaved group and other accesses located
  733. // between the first and last member of the group. Note that this also
  734. // means that a group can't have more than one member at a given offset.
  735. // The accesses in a group can have dependences with other accesses, but
  736. // we must ensure we don't extend the boundaries of the group such that
  737. // we encompass those dependent accesses.
  738. //
  739. // For example, assume we have the sequence of accesses shown below in a
  740. // stride-2 loop:
  741. //
  742. // (1, 2) is a group | A[i] = a; // (1)
  743. // | A[i-1] = b; // (2) |
  744. // A[i-3] = c; // (3)
  745. // A[i] = d; // (4) | (2, 4) is not a group
  746. //
  747. // Because accesses (2) and (3) are dependent, we can group (2) with (1)
  748. // but not with (4). If we did, the dependent access (3) would be within
  749. // the boundaries of the (2, 4) group.
  750. if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
  751. // If a dependence exists and A is already in a group, we know that A
  752. // must be a store since A precedes B and WAR dependences are allowed.
  753. // Thus, A would be sunk below B. We release A's group to prevent this
  754. // illegal code motion. A will then be free to form another group with
  755. // instructions that precede it.
  756. if (isInterleaved(A)) {
  757. InterleaveGroup<Instruction> *StoreGroup = getInterleaveGroup(A);
  758. StoreGroups.remove(StoreGroup);
  759. releaseGroup(StoreGroup);
  760. }
  761. // If a dependence exists and A is not already in a group (or it was
  762. // and we just released it), B might be hoisted above A (if B is a
  763. // load) or another store might be sunk below A (if B is a store). In
  764. // either case, we can't add additional instructions to B's group. B
  765. // will only form a group with instructions that it precedes.
  766. break;
  767. }
  768. // At this point, we've checked for illegal code motion. If either A or B
  769. // isn't strided, there's nothing left to do.
  770. if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
  771. continue;
  772. // Ignore A if it's already in a group or isn't the same kind of memory
  773. // operation as B.
  774. // Note that mayReadFromMemory() isn't mutually exclusive to
  775. // mayWriteToMemory in the case of atomic loads. We shouldn't see those
  776. // here, canVectorizeMemory() should have returned false - except for the
  777. // case we asked for optimization remarks.
  778. if (isInterleaved(A) ||
  779. (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
  780. (A->mayWriteToMemory() != B->mayWriteToMemory()))
  781. continue;
  782. // Check rules 1 and 2. Ignore A if its stride or size is different from
  783. // that of B.
  784. if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
  785. continue;
  786. // Ignore A if the memory object of A and B don't belong to the same
  787. // address space
  788. if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
  789. continue;
  790. // Calculate the distance from A to B.
  791. const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
  792. PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
  793. if (!DistToB)
  794. continue;
  795. int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
  796. // Check rule 3. Ignore A if its distance to B is not a multiple of the
  797. // size.
  798. if (DistanceToB % static_cast<int64_t>(DesB.Size))
  799. continue;
  800. // All members of a predicated interleave-group must have the same predicate,
  801. // and currently must reside in the same BB.
  802. BasicBlock *BlockA = A->getParent();
  803. BasicBlock *BlockB = B->getParent();
  804. if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
  805. (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
  806. continue;
  807. // The index of A is the index of B plus A's distance to B in multiples
  808. // of the size.
  809. int IndexA =
  810. Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
  811. // Try to insert A into B's group.
  812. if (Group->insertMember(A, IndexA, DesA.Align)) {
  813. LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
  814. << " into the interleave group with" << *B
  815. << '\n');
  816. InterleaveGroupMap[A] = Group;
  817. // Set the first load in program order as the insert position.
  818. if (A->mayReadFromMemory())
  819. Group->setInsertPos(A);
  820. }
  821. } // Iteration over A accesses.
  822. } // Iteration over B accesses.
  823. // Remove interleaved store groups with gaps.
  824. for (auto *Group : StoreGroups)
  825. if (Group->getNumMembers() != Group->getFactor()) {
  826. LLVM_DEBUG(
  827. dbgs() << "LV: Invalidate candidate interleaved store group due "
  828. "to gaps.\n");
  829. releaseGroup(Group);
  830. }
  831. // Remove interleaved groups with gaps (currently only loads) whose memory
  832. // accesses may wrap around. We have to revisit the getPtrStride analysis,
  833. // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
  834. // not check wrapping (see documentation there).
  835. // FORNOW we use Assume=false;
  836. // TODO: Change to Assume=true but making sure we don't exceed the threshold
  837. // of runtime SCEV assumptions checks (thereby potentially failing to
  838. // vectorize altogether).
  839. // Additional optional optimizations:
  840. // TODO: If we are peeling the loop and we know that the first pointer doesn't
  841. // wrap then we can deduce that all pointers in the group don't wrap.
  842. // This means that we can forcefully peel the loop in order to only have to
  843. // check the first pointer for no-wrap. When we'll change to use Assume=true
  844. // we'll only need at most one runtime check per interleaved group.
  845. for (auto *Group : LoadGroups) {
  846. // Case 1: A full group. Can Skip the checks; For full groups, if the wide
  847. // load would wrap around the address space we would do a memory access at
  848. // nullptr even without the transformation.
  849. if (Group->getNumMembers() == Group->getFactor())
  850. continue;
  851. // Case 2: If first and last members of the group don't wrap this implies
  852. // that all the pointers in the group don't wrap.
  853. // So we check only group member 0 (which is always guaranteed to exist),
  854. // and group member Factor - 1; If the latter doesn't exist we rely on
  855. // peeling (if it is a non-reveresed accsess -- see Case 3).
  856. Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0));
  857. if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
  858. /*ShouldCheckWrap=*/true)) {
  859. LLVM_DEBUG(
  860. dbgs() << "LV: Invalidate candidate interleaved group due to "
  861. "first group member potentially pointer-wrapping.\n");
  862. releaseGroup(Group);
  863. continue;
  864. }
  865. Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
  866. if (LastMember) {
  867. Value *LastMemberPtr = getLoadStorePointerOperand(LastMember);
  868. if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
  869. /*ShouldCheckWrap=*/true)) {
  870. LLVM_DEBUG(
  871. dbgs() << "LV: Invalidate candidate interleaved group due to "
  872. "last group member potentially pointer-wrapping.\n");
  873. releaseGroup(Group);
  874. }
  875. } else {
  876. // Case 3: A non-reversed interleaved load group with gaps: We need
  877. // to execute at least one scalar epilogue iteration. This will ensure
  878. // we don't speculatively access memory out-of-bounds. We only need
  879. // to look for a member at index factor - 1, since every group must have
  880. // a member at index zero.
  881. if (Group->isReverse()) {
  882. LLVM_DEBUG(
  883. dbgs() << "LV: Invalidate candidate interleaved group due to "
  884. "a reverse access with gaps.\n");
  885. releaseGroup(Group);
  886. continue;
  887. }
  888. LLVM_DEBUG(
  889. dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
  890. RequiresScalarEpilogue = true;
  891. }
  892. }
  893. }
  894. void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
  895. // If no group had triggered the requirement to create an epilogue loop,
  896. // there is nothing to do.
  897. if (!requiresScalarEpilogue())
  898. return;
  899. // Avoid releasing a Group twice.
  900. SmallPtrSet<InterleaveGroup<Instruction> *, 4> DelSet;
  901. for (auto &I : InterleaveGroupMap) {
  902. InterleaveGroup<Instruction> *Group = I.second;
  903. if (Group->requiresScalarEpilogue())
  904. DelSet.insert(Group);
  905. }
  906. for (auto *Ptr : DelSet) {
  907. LLVM_DEBUG(
  908. dbgs()
  909. << "LV: Invalidate candidate interleaved group due to gaps that "
  910. "require a scalar epilogue (not allowed under optsize) and cannot "
  911. "be masked (not enabled). \n");
  912. releaseGroup(Ptr);
  913. }
  914. RequiresScalarEpilogue = false;
  915. }
  916. template <typename InstT>
  917. void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
  918. llvm_unreachable("addMetadata can only be used for Instruction");
  919. }
  920. namespace llvm {
  921. template <>
  922. void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const {
  923. SmallVector<Value *, 4> VL;
  924. std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
  925. [](std::pair<int, Instruction *> p) { return p.second; });
  926. propagateMetadata(NewInst, VL);
  927. }
  928. }