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