10b57cec5SDimitry Andric //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file defines vectorizer utilities.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
140b57cec5SDimitry Andric #include "llvm/ADT/EquivalenceClasses.h"
15cb14a3feSDimitry Andric #include "llvm/ADT/SmallVector.h"
160b57cec5SDimitry Andric #include "llvm/Analysis/DemandedBits.h"
170b57cec5SDimitry Andric #include "llvm/Analysis/LoopInfo.h"
180b57cec5SDimitry Andric #include "llvm/Analysis/LoopIterator.h"
190b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolution.h"
200b57cec5SDimitry Andric #include "llvm/Analysis/ScalarEvolutionExpressions.h"
210b57cec5SDimitry Andric #include "llvm/Analysis/TargetTransformInfo.h"
220b57cec5SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
230b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
24cb14a3feSDimitry Andric #include "llvm/IR/DerivedTypes.h"
250b57cec5SDimitry Andric #include "llvm/IR/IRBuilder.h"
260b57cec5SDimitry Andric #include "llvm/IR/PatternMatch.h"
270b57cec5SDimitry Andric #include "llvm/IR/Value.h"
28480093f4SDimitry Andric #include "llvm/Support/CommandLine.h"
290b57cec5SDimitry Andric 
300b57cec5SDimitry Andric #define DEBUG_TYPE "vectorutils"
310b57cec5SDimitry Andric 
320b57cec5SDimitry Andric using namespace llvm;
330b57cec5SDimitry Andric using namespace llvm::PatternMatch;
340b57cec5SDimitry Andric 
350b57cec5SDimitry Andric /// Maximum factor for an interleaved memory access.
360b57cec5SDimitry Andric static cl::opt<unsigned> MaxInterleaveGroupFactor(
370b57cec5SDimitry Andric     "max-interleave-group-factor", cl::Hidden,
380b57cec5SDimitry Andric     cl::desc("Maximum factor for an interleaved access group (default = 8)"),
390b57cec5SDimitry Andric     cl::init(8));
400b57cec5SDimitry Andric 
410b57cec5SDimitry Andric /// Return true if all of the intrinsic's arguments and return type are scalars
420b57cec5SDimitry Andric /// for the scalar form of the intrinsic, and vectors for the vector form of the
430b57cec5SDimitry Andric /// intrinsic (except operands that are marked as always being scalar by
4481ad6265SDimitry Andric /// isVectorIntrinsicWithScalarOpAtArg).
isTriviallyVectorizable(Intrinsic::ID ID)450b57cec5SDimitry Andric bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
460b57cec5SDimitry Andric   switch (ID) {
47e8d8bef9SDimitry Andric   case Intrinsic::abs:   // Begin integer bit-manipulation.
48e8d8bef9SDimitry Andric   case Intrinsic::bswap:
490b57cec5SDimitry Andric   case Intrinsic::bitreverse:
500b57cec5SDimitry Andric   case Intrinsic::ctpop:
510b57cec5SDimitry Andric   case Intrinsic::ctlz:
520b57cec5SDimitry Andric   case Intrinsic::cttz:
530b57cec5SDimitry Andric   case Intrinsic::fshl:
540b57cec5SDimitry Andric   case Intrinsic::fshr:
55e8d8bef9SDimitry Andric   case Intrinsic::smax:
56e8d8bef9SDimitry Andric   case Intrinsic::smin:
57e8d8bef9SDimitry Andric   case Intrinsic::umax:
58e8d8bef9SDimitry Andric   case Intrinsic::umin:
590b57cec5SDimitry Andric   case Intrinsic::sadd_sat:
600b57cec5SDimitry Andric   case Intrinsic::ssub_sat:
610b57cec5SDimitry Andric   case Intrinsic::uadd_sat:
620b57cec5SDimitry Andric   case Intrinsic::usub_sat:
630b57cec5SDimitry Andric   case Intrinsic::smul_fix:
640b57cec5SDimitry Andric   case Intrinsic::smul_fix_sat:
650b57cec5SDimitry Andric   case Intrinsic::umul_fix:
668bcb0991SDimitry Andric   case Intrinsic::umul_fix_sat:
670b57cec5SDimitry Andric   case Intrinsic::sqrt: // Begin floating-point.
680b57cec5SDimitry Andric   case Intrinsic::sin:
690b57cec5SDimitry Andric   case Intrinsic::cos:
700b57cec5SDimitry Andric   case Intrinsic::exp:
710b57cec5SDimitry Andric   case Intrinsic::exp2:
720b57cec5SDimitry Andric   case Intrinsic::log:
730b57cec5SDimitry Andric   case Intrinsic::log10:
740b57cec5SDimitry Andric   case Intrinsic::log2:
750b57cec5SDimitry Andric   case Intrinsic::fabs:
760b57cec5SDimitry Andric   case Intrinsic::minnum:
770b57cec5SDimitry Andric   case Intrinsic::maxnum:
780b57cec5SDimitry Andric   case Intrinsic::minimum:
790b57cec5SDimitry Andric   case Intrinsic::maximum:
800b57cec5SDimitry Andric   case Intrinsic::copysign:
810b57cec5SDimitry Andric   case Intrinsic::floor:
820b57cec5SDimitry Andric   case Intrinsic::ceil:
830b57cec5SDimitry Andric   case Intrinsic::trunc:
840b57cec5SDimitry Andric   case Intrinsic::rint:
850b57cec5SDimitry Andric   case Intrinsic::nearbyint:
860b57cec5SDimitry Andric   case Intrinsic::round:
875ffd83dbSDimitry Andric   case Intrinsic::roundeven:
880b57cec5SDimitry Andric   case Intrinsic::pow:
890b57cec5SDimitry Andric   case Intrinsic::fma:
900b57cec5SDimitry Andric   case Intrinsic::fmuladd:
9106c3fb27SDimitry Andric   case Intrinsic::is_fpclass:
920b57cec5SDimitry Andric   case Intrinsic::powi:
930b57cec5SDimitry Andric   case Intrinsic::canonicalize:
9481ad6265SDimitry Andric   case Intrinsic::fptosi_sat:
9581ad6265SDimitry Andric   case Intrinsic::fptoui_sat:
965f757f3fSDimitry Andric   case Intrinsic::lrint:
975f757f3fSDimitry Andric   case Intrinsic::llrint:
980b57cec5SDimitry Andric     return true;
990b57cec5SDimitry Andric   default:
1000b57cec5SDimitry Andric     return false;
1010b57cec5SDimitry Andric   }
1020b57cec5SDimitry Andric }
1030b57cec5SDimitry Andric 
1040b57cec5SDimitry Andric /// Identifies if the vector form of the intrinsic has a scalar operand.
isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID,unsigned ScalarOpdIdx)10581ad6265SDimitry Andric bool llvm::isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID,
1060b57cec5SDimitry Andric                                               unsigned ScalarOpdIdx) {
1070b57cec5SDimitry Andric   switch (ID) {
108e8d8bef9SDimitry Andric   case Intrinsic::abs:
1090b57cec5SDimitry Andric   case Intrinsic::ctlz:
1100b57cec5SDimitry Andric   case Intrinsic::cttz:
11106c3fb27SDimitry Andric   case Intrinsic::is_fpclass:
1120b57cec5SDimitry Andric   case Intrinsic::powi:
1130b57cec5SDimitry Andric     return (ScalarOpdIdx == 1);
1140b57cec5SDimitry Andric   case Intrinsic::smul_fix:
1150b57cec5SDimitry Andric   case Intrinsic::smul_fix_sat:
1160b57cec5SDimitry Andric   case Intrinsic::umul_fix:
1178bcb0991SDimitry Andric   case Intrinsic::umul_fix_sat:
1180b57cec5SDimitry Andric     return (ScalarOpdIdx == 2);
1190b57cec5SDimitry Andric   default:
1200b57cec5SDimitry Andric     return false;
1210b57cec5SDimitry Andric   }
1220b57cec5SDimitry Andric }
1230b57cec5SDimitry Andric 
isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID,int OpdIdx)12481ad6265SDimitry Andric bool llvm::isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID,
12506c3fb27SDimitry Andric                                                   int OpdIdx) {
126647cbc5dSDimitry Andric   assert(ID != Intrinsic::not_intrinsic && "Not an intrinsic!");
127647cbc5dSDimitry Andric 
128fe6060f1SDimitry Andric   switch (ID) {
12981ad6265SDimitry Andric   case Intrinsic::fptosi_sat:
13081ad6265SDimitry Andric   case Intrinsic::fptoui_sat:
1315f757f3fSDimitry Andric   case Intrinsic::lrint:
1325f757f3fSDimitry Andric   case Intrinsic::llrint:
13306c3fb27SDimitry Andric     return OpdIdx == -1 || OpdIdx == 0;
13406c3fb27SDimitry Andric   case Intrinsic::is_fpclass:
13581ad6265SDimitry Andric     return OpdIdx == 0;
136fe6060f1SDimitry Andric   case Intrinsic::powi:
13706c3fb27SDimitry Andric     return OpdIdx == -1 || OpdIdx == 1;
138fe6060f1SDimitry Andric   default:
13906c3fb27SDimitry Andric     return OpdIdx == -1;
140fe6060f1SDimitry Andric   }
141fe6060f1SDimitry Andric }
142fe6060f1SDimitry Andric 
1430b57cec5SDimitry Andric /// Returns intrinsic ID for call.
1440b57cec5SDimitry Andric /// For the input call instruction it finds mapping intrinsic and returns
1450b57cec5SDimitry Andric /// its ID, in case it does not found it return not_intrinsic.
getVectorIntrinsicIDForCall(const CallInst * CI,const TargetLibraryInfo * TLI)1460b57cec5SDimitry Andric Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI,
1470b57cec5SDimitry Andric                                                 const TargetLibraryInfo *TLI) {
1485ffd83dbSDimitry Andric   Intrinsic::ID ID = getIntrinsicForCallSite(*CI, TLI);
1490b57cec5SDimitry Andric   if (ID == Intrinsic::not_intrinsic)
1500b57cec5SDimitry Andric     return Intrinsic::not_intrinsic;
1510b57cec5SDimitry Andric 
1520b57cec5SDimitry Andric   if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
1530b57cec5SDimitry Andric       ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
154e8d8bef9SDimitry Andric       ID == Intrinsic::experimental_noalias_scope_decl ||
155e8d8bef9SDimitry Andric       ID == Intrinsic::sideeffect || ID == Intrinsic::pseudoprobe)
1560b57cec5SDimitry Andric     return ID;
1570b57cec5SDimitry Andric   return Intrinsic::not_intrinsic;
1580b57cec5SDimitry Andric }
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric /// Given a vector and an element number, see if the scalar value is
1610b57cec5SDimitry Andric /// already around as a register, for example if it were inserted then extracted
1620b57cec5SDimitry Andric /// from the vector.
findScalarElement(Value * V,unsigned EltNo)1630b57cec5SDimitry Andric Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
1640b57cec5SDimitry Andric   assert(V->getType()->isVectorTy() && "Not looking at a vector?");
1650b57cec5SDimitry Andric   VectorType *VTy = cast<VectorType>(V->getType());
1665ffd83dbSDimitry Andric   // For fixed-length vector, return undef for out of range access.
1675ffd83dbSDimitry Andric   if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
1685ffd83dbSDimitry Andric     unsigned Width = FVTy->getNumElements();
1695ffd83dbSDimitry Andric     if (EltNo >= Width)
1705ffd83dbSDimitry Andric       return UndefValue::get(FVTy->getElementType());
1715ffd83dbSDimitry Andric   }
1720b57cec5SDimitry Andric 
1730b57cec5SDimitry Andric   if (Constant *C = dyn_cast<Constant>(V))
1740b57cec5SDimitry Andric     return C->getAggregateElement(EltNo);
1750b57cec5SDimitry Andric 
1760b57cec5SDimitry Andric   if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
1770b57cec5SDimitry Andric     // If this is an insert to a variable element, we don't know what it is.
1780b57cec5SDimitry Andric     if (!isa<ConstantInt>(III->getOperand(2)))
1790b57cec5SDimitry Andric       return nullptr;
1800b57cec5SDimitry Andric     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
1810b57cec5SDimitry Andric 
1820b57cec5SDimitry Andric     // If this is an insert to the element we are looking for, return the
1830b57cec5SDimitry Andric     // inserted value.
1840b57cec5SDimitry Andric     if (EltNo == IIElt)
1850b57cec5SDimitry Andric       return III->getOperand(1);
1860b57cec5SDimitry Andric 
187e8d8bef9SDimitry Andric     // Guard against infinite loop on malformed, unreachable IR.
188e8d8bef9SDimitry Andric     if (III == III->getOperand(0))
189e8d8bef9SDimitry Andric       return nullptr;
190e8d8bef9SDimitry Andric 
1910b57cec5SDimitry Andric     // Otherwise, the insertelement doesn't modify the value, recurse on its
1920b57cec5SDimitry Andric     // vector input.
1930b57cec5SDimitry Andric     return findScalarElement(III->getOperand(0), EltNo);
1940b57cec5SDimitry Andric   }
1950b57cec5SDimitry Andric 
1965ffd83dbSDimitry Andric   ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V);
1975ffd83dbSDimitry Andric   // Restrict the following transformation to fixed-length vector.
1985ffd83dbSDimitry Andric   if (SVI && isa<FixedVectorType>(SVI->getType())) {
1995ffd83dbSDimitry Andric     unsigned LHSWidth =
2005ffd83dbSDimitry Andric         cast<FixedVectorType>(SVI->getOperand(0)->getType())->getNumElements();
2010b57cec5SDimitry Andric     int InEl = SVI->getMaskValue(EltNo);
2020b57cec5SDimitry Andric     if (InEl < 0)
2030b57cec5SDimitry Andric       return UndefValue::get(VTy->getElementType());
2040b57cec5SDimitry Andric     if (InEl < (int)LHSWidth)
2050b57cec5SDimitry Andric       return findScalarElement(SVI->getOperand(0), InEl);
2060b57cec5SDimitry Andric     return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
2070b57cec5SDimitry Andric   }
2080b57cec5SDimitry Andric 
2090b57cec5SDimitry Andric   // Extract a value from a vector add operation with a constant zero.
2100b57cec5SDimitry Andric   // TODO: Use getBinOpIdentity() to generalize this.
2110b57cec5SDimitry Andric   Value *Val; Constant *C;
2120b57cec5SDimitry Andric   if (match(V, m_Add(m_Value(Val), m_Constant(C))))
2130b57cec5SDimitry Andric     if (Constant *Elt = C->getAggregateElement(EltNo))
2140b57cec5SDimitry Andric       if (Elt->isNullValue())
2150b57cec5SDimitry Andric         return findScalarElement(Val, EltNo);
2160b57cec5SDimitry Andric 
217349cc55cSDimitry Andric   // If the vector is a splat then we can trivially find the scalar element.
218349cc55cSDimitry Andric   if (isa<ScalableVectorType>(VTy))
219349cc55cSDimitry Andric     if (Value *Splat = getSplatValue(V))
220349cc55cSDimitry Andric       if (EltNo < VTy->getElementCount().getKnownMinValue())
221349cc55cSDimitry Andric         return Splat;
222349cc55cSDimitry Andric 
2230b57cec5SDimitry Andric   // Otherwise, we don't know.
2240b57cec5SDimitry Andric   return nullptr;
2250b57cec5SDimitry Andric }
2260b57cec5SDimitry Andric 
getSplatIndex(ArrayRef<int> Mask)2275ffd83dbSDimitry Andric int llvm::getSplatIndex(ArrayRef<int> Mask) {
2285ffd83dbSDimitry Andric   int SplatIndex = -1;
2295ffd83dbSDimitry Andric   for (int M : Mask) {
2305ffd83dbSDimitry Andric     // Ignore invalid (undefined) mask elements.
2315ffd83dbSDimitry Andric     if (M < 0)
2325ffd83dbSDimitry Andric       continue;
2335ffd83dbSDimitry Andric 
2345ffd83dbSDimitry Andric     // There can be only 1 non-negative mask element value if this is a splat.
2355ffd83dbSDimitry Andric     if (SplatIndex != -1 && SplatIndex != M)
2365ffd83dbSDimitry Andric       return -1;
2375ffd83dbSDimitry Andric 
2385ffd83dbSDimitry Andric     // Initialize the splat index to the 1st non-negative mask element.
2395ffd83dbSDimitry Andric     SplatIndex = M;
2405ffd83dbSDimitry Andric   }
2415ffd83dbSDimitry Andric   assert((SplatIndex == -1 || SplatIndex >= 0) && "Negative index?");
2425ffd83dbSDimitry Andric   return SplatIndex;
2435ffd83dbSDimitry Andric }
2445ffd83dbSDimitry Andric 
2450b57cec5SDimitry Andric /// Get splat value if the input is a splat vector or return nullptr.
2460b57cec5SDimitry Andric /// This function is not fully general. It checks only 2 cases:
2470b57cec5SDimitry Andric /// the input value is (1) a splat constant vector or (2) a sequence
2480b57cec5SDimitry Andric /// of instructions that broadcasts a scalar at element 0.
getSplatValue(const Value * V)249e8d8bef9SDimitry Andric Value *llvm::getSplatValue(const Value *V) {
2500b57cec5SDimitry Andric   if (isa<VectorType>(V->getType()))
2510b57cec5SDimitry Andric     if (auto *C = dyn_cast<Constant>(V))
2520b57cec5SDimitry Andric       return C->getSplatValue();
2530b57cec5SDimitry Andric 
2540b57cec5SDimitry Andric   // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...>
2550b57cec5SDimitry Andric   Value *Splat;
2565ffd83dbSDimitry Andric   if (match(V,
2575ffd83dbSDimitry Andric             m_Shuffle(m_InsertElt(m_Value(), m_Value(Splat), m_ZeroInt()),
2585ffd83dbSDimitry Andric                       m_Value(), m_ZeroMask())))
2590b57cec5SDimitry Andric     return Splat;
2600b57cec5SDimitry Andric 
2610b57cec5SDimitry Andric   return nullptr;
2620b57cec5SDimitry Andric }
2630b57cec5SDimitry Andric 
isSplatValue(const Value * V,int Index,unsigned Depth)2645ffd83dbSDimitry Andric bool llvm::isSplatValue(const Value *V, int Index, unsigned Depth) {
265e8d8bef9SDimitry Andric   assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric   if (isa<VectorType>(V->getType())) {
2680b57cec5SDimitry Andric     if (isa<UndefValue>(V))
2690b57cec5SDimitry Andric       return true;
2705ffd83dbSDimitry Andric     // FIXME: We can allow undefs, but if Index was specified, we may want to
2715ffd83dbSDimitry Andric     //        check that the constant is defined at that index.
2720b57cec5SDimitry Andric     if (auto *C = dyn_cast<Constant>(V))
2730b57cec5SDimitry Andric       return C->getSplatValue() != nullptr;
2740b57cec5SDimitry Andric   }
2750b57cec5SDimitry Andric 
2765ffd83dbSDimitry Andric   if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V)) {
2775ffd83dbSDimitry Andric     // FIXME: We can safely allow undefs here. If Index was specified, we will
2785ffd83dbSDimitry Andric     //        check that the mask elt is defined at the required index.
279bdd1243dSDimitry Andric     if (!all_equal(Shuf->getShuffleMask()))
2805ffd83dbSDimitry Andric       return false;
2815ffd83dbSDimitry Andric 
2825ffd83dbSDimitry Andric     // Match any index.
2835ffd83dbSDimitry Andric     if (Index == -1)
2845ffd83dbSDimitry Andric       return true;
2855ffd83dbSDimitry Andric 
2865ffd83dbSDimitry Andric     // Match a specific element. The mask should be defined at and match the
2875ffd83dbSDimitry Andric     // specified index.
2885ffd83dbSDimitry Andric     return Shuf->getMaskValue(Index) == Index;
2895ffd83dbSDimitry Andric   }
2900b57cec5SDimitry Andric 
2910b57cec5SDimitry Andric   // The remaining tests are all recursive, so bail out if we hit the limit.
292e8d8bef9SDimitry Andric   if (Depth++ == MaxAnalysisRecursionDepth)
2930b57cec5SDimitry Andric     return false;
2940b57cec5SDimitry Andric 
2950b57cec5SDimitry Andric   // If both operands of a binop are splats, the result is a splat.
2960b57cec5SDimitry Andric   Value *X, *Y, *Z;
2970b57cec5SDimitry Andric   if (match(V, m_BinOp(m_Value(X), m_Value(Y))))
2985ffd83dbSDimitry Andric     return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth);
2990b57cec5SDimitry Andric 
3000b57cec5SDimitry Andric   // If all operands of a select are splats, the result is a splat.
3010b57cec5SDimitry Andric   if (match(V, m_Select(m_Value(X), m_Value(Y), m_Value(Z))))
3025ffd83dbSDimitry Andric     return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth) &&
3035ffd83dbSDimitry Andric            isSplatValue(Z, Index, Depth);
3040b57cec5SDimitry Andric 
3050b57cec5SDimitry Andric   // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops).
3060b57cec5SDimitry Andric 
3070b57cec5SDimitry Andric   return false;
3080b57cec5SDimitry Andric }
3090b57cec5SDimitry Andric 
getShuffleDemandedElts(int SrcWidth,ArrayRef<int> Mask,const APInt & DemandedElts,APInt & DemandedLHS,APInt & DemandedRHS,bool AllowUndefElts)310bdd1243dSDimitry Andric bool llvm::getShuffleDemandedElts(int SrcWidth, ArrayRef<int> Mask,
311bdd1243dSDimitry Andric                                   const APInt &DemandedElts, APInt &DemandedLHS,
312bdd1243dSDimitry Andric                                   APInt &DemandedRHS, bool AllowUndefElts) {
313bdd1243dSDimitry Andric   DemandedLHS = DemandedRHS = APInt::getZero(SrcWidth);
314bdd1243dSDimitry Andric 
315bdd1243dSDimitry Andric   // Early out if we don't demand any elements.
316bdd1243dSDimitry Andric   if (DemandedElts.isZero())
317bdd1243dSDimitry Andric     return true;
318bdd1243dSDimitry Andric 
319bdd1243dSDimitry Andric   // Simple case of a shuffle with zeroinitializer.
320bdd1243dSDimitry Andric   if (all_of(Mask, [](int Elt) { return Elt == 0; })) {
321bdd1243dSDimitry Andric     DemandedLHS.setBit(0);
322bdd1243dSDimitry Andric     return true;
323bdd1243dSDimitry Andric   }
324bdd1243dSDimitry Andric 
325bdd1243dSDimitry Andric   for (unsigned I = 0, E = Mask.size(); I != E; ++I) {
326bdd1243dSDimitry Andric     int M = Mask[I];
327bdd1243dSDimitry Andric     assert((-1 <= M) && (M < (SrcWidth * 2)) &&
328bdd1243dSDimitry Andric            "Invalid shuffle mask constant");
329bdd1243dSDimitry Andric 
330bdd1243dSDimitry Andric     if (!DemandedElts[I] || (AllowUndefElts && (M < 0)))
331bdd1243dSDimitry Andric       continue;
332bdd1243dSDimitry Andric 
333bdd1243dSDimitry Andric     // For undef elements, we don't know anything about the common state of
334bdd1243dSDimitry Andric     // the shuffle result.
335bdd1243dSDimitry Andric     if (M < 0)
336bdd1243dSDimitry Andric       return false;
337bdd1243dSDimitry Andric 
338bdd1243dSDimitry Andric     if (M < SrcWidth)
339bdd1243dSDimitry Andric       DemandedLHS.setBit(M);
340bdd1243dSDimitry Andric     else
341bdd1243dSDimitry Andric       DemandedRHS.setBit(M - SrcWidth);
342bdd1243dSDimitry Andric   }
343bdd1243dSDimitry Andric 
344bdd1243dSDimitry Andric   return true;
345bdd1243dSDimitry Andric }
346bdd1243dSDimitry Andric 
narrowShuffleMaskElts(int Scale,ArrayRef<int> Mask,SmallVectorImpl<int> & ScaledMask)3475ffd83dbSDimitry Andric void llvm::narrowShuffleMaskElts(int Scale, ArrayRef<int> Mask,
3485ffd83dbSDimitry Andric                                  SmallVectorImpl<int> &ScaledMask) {
3495ffd83dbSDimitry Andric   assert(Scale > 0 && "Unexpected scaling factor");
3505ffd83dbSDimitry Andric 
3515ffd83dbSDimitry Andric   // Fast-path: if no scaling, then it is just a copy.
3525ffd83dbSDimitry Andric   if (Scale == 1) {
3535ffd83dbSDimitry Andric     ScaledMask.assign(Mask.begin(), Mask.end());
3545ffd83dbSDimitry Andric     return;
3555ffd83dbSDimitry Andric   }
3565ffd83dbSDimitry Andric 
3575ffd83dbSDimitry Andric   ScaledMask.clear();
3585ffd83dbSDimitry Andric   for (int MaskElt : Mask) {
3595ffd83dbSDimitry Andric     if (MaskElt >= 0) {
360e8d8bef9SDimitry Andric       assert(((uint64_t)Scale * MaskElt + (Scale - 1)) <= INT32_MAX &&
3615ffd83dbSDimitry Andric              "Overflowed 32-bits");
3625ffd83dbSDimitry Andric     }
3635ffd83dbSDimitry Andric     for (int SliceElt = 0; SliceElt != Scale; ++SliceElt)
3645ffd83dbSDimitry Andric       ScaledMask.push_back(MaskElt < 0 ? MaskElt : Scale * MaskElt + SliceElt);
3655ffd83dbSDimitry Andric   }
3665ffd83dbSDimitry Andric }
3675ffd83dbSDimitry Andric 
widenShuffleMaskElts(int Scale,ArrayRef<int> Mask,SmallVectorImpl<int> & ScaledMask)3685ffd83dbSDimitry Andric bool llvm::widenShuffleMaskElts(int Scale, ArrayRef<int> Mask,
3695ffd83dbSDimitry Andric                                 SmallVectorImpl<int> &ScaledMask) {
3705ffd83dbSDimitry Andric   assert(Scale > 0 && "Unexpected scaling factor");
3715ffd83dbSDimitry Andric 
3725ffd83dbSDimitry Andric   // Fast-path: if no scaling, then it is just a copy.
3735ffd83dbSDimitry Andric   if (Scale == 1) {
3745ffd83dbSDimitry Andric     ScaledMask.assign(Mask.begin(), Mask.end());
3755ffd83dbSDimitry Andric     return true;
3765ffd83dbSDimitry Andric   }
3775ffd83dbSDimitry Andric 
3785ffd83dbSDimitry Andric   // We must map the original elements down evenly to a type with less elements.
3795ffd83dbSDimitry Andric   int NumElts = Mask.size();
3805ffd83dbSDimitry Andric   if (NumElts % Scale != 0)
3815ffd83dbSDimitry Andric     return false;
3825ffd83dbSDimitry Andric 
3835ffd83dbSDimitry Andric   ScaledMask.clear();
3845ffd83dbSDimitry Andric   ScaledMask.reserve(NumElts / Scale);
3855ffd83dbSDimitry Andric 
3865ffd83dbSDimitry Andric   // Step through the input mask by splitting into Scale-sized slices.
3875ffd83dbSDimitry Andric   do {
3885ffd83dbSDimitry Andric     ArrayRef<int> MaskSlice = Mask.take_front(Scale);
3895ffd83dbSDimitry Andric     assert((int)MaskSlice.size() == Scale && "Expected Scale-sized slice.");
3905ffd83dbSDimitry Andric 
3915ffd83dbSDimitry Andric     // The first element of the slice determines how we evaluate this slice.
3925ffd83dbSDimitry Andric     int SliceFront = MaskSlice.front();
3935ffd83dbSDimitry Andric     if (SliceFront < 0) {
3945ffd83dbSDimitry Andric       // Negative values (undef or other "sentinel" values) must be equal across
3955ffd83dbSDimitry Andric       // the entire slice.
396bdd1243dSDimitry Andric       if (!all_equal(MaskSlice))
3975ffd83dbSDimitry Andric         return false;
3985ffd83dbSDimitry Andric       ScaledMask.push_back(SliceFront);
3995ffd83dbSDimitry Andric     } else {
4005ffd83dbSDimitry Andric       // A positive mask element must be cleanly divisible.
4015ffd83dbSDimitry Andric       if (SliceFront % Scale != 0)
4025ffd83dbSDimitry Andric         return false;
4035ffd83dbSDimitry Andric       // Elements of the slice must be consecutive.
4045ffd83dbSDimitry Andric       for (int i = 1; i < Scale; ++i)
4055ffd83dbSDimitry Andric         if (MaskSlice[i] != SliceFront + i)
4065ffd83dbSDimitry Andric           return false;
4075ffd83dbSDimitry Andric       ScaledMask.push_back(SliceFront / Scale);
4085ffd83dbSDimitry Andric     }
4095ffd83dbSDimitry Andric     Mask = Mask.drop_front(Scale);
4105ffd83dbSDimitry Andric   } while (!Mask.empty());
4115ffd83dbSDimitry Andric 
4125ffd83dbSDimitry Andric   assert((int)ScaledMask.size() * Scale == NumElts && "Unexpected scaled mask");
4135ffd83dbSDimitry Andric 
4145ffd83dbSDimitry Andric   // All elements of the original mask can be scaled down to map to the elements
4155ffd83dbSDimitry Andric   // of a mask with wider elements.
4165ffd83dbSDimitry Andric   return true;
4175ffd83dbSDimitry Andric }
4185ffd83dbSDimitry Andric 
getShuffleMaskWithWidestElts(ArrayRef<int> Mask,SmallVectorImpl<int> & ScaledMask)419bdd1243dSDimitry Andric void llvm::getShuffleMaskWithWidestElts(ArrayRef<int> Mask,
420bdd1243dSDimitry Andric                                         SmallVectorImpl<int> &ScaledMask) {
421bdd1243dSDimitry Andric   std::array<SmallVector<int, 16>, 2> TmpMasks;
422bdd1243dSDimitry Andric   SmallVectorImpl<int> *Output = &TmpMasks[0], *Tmp = &TmpMasks[1];
423bdd1243dSDimitry Andric   ArrayRef<int> InputMask = Mask;
424bdd1243dSDimitry Andric   for (unsigned Scale = 2; Scale <= InputMask.size(); ++Scale) {
425bdd1243dSDimitry Andric     while (widenShuffleMaskElts(Scale, InputMask, *Output)) {
426bdd1243dSDimitry Andric       InputMask = *Output;
427bdd1243dSDimitry Andric       std::swap(Output, Tmp);
428bdd1243dSDimitry Andric     }
429bdd1243dSDimitry Andric   }
430bdd1243dSDimitry Andric   ScaledMask.assign(InputMask.begin(), InputMask.end());
431bdd1243dSDimitry Andric }
432bdd1243dSDimitry Andric 
processShuffleMasks(ArrayRef<int> Mask,unsigned NumOfSrcRegs,unsigned NumOfDestRegs,unsigned NumOfUsedRegs,function_ref<void ()> NoInputAction,function_ref<void (ArrayRef<int>,unsigned,unsigned)> SingleInputAction,function_ref<void (ArrayRef<int>,unsigned,unsigned)> ManyInputsAction)43381ad6265SDimitry Andric void llvm::processShuffleMasks(
43481ad6265SDimitry Andric     ArrayRef<int> Mask, unsigned NumOfSrcRegs, unsigned NumOfDestRegs,
43581ad6265SDimitry Andric     unsigned NumOfUsedRegs, function_ref<void()> NoInputAction,
43681ad6265SDimitry Andric     function_ref<void(ArrayRef<int>, unsigned, unsigned)> SingleInputAction,
43781ad6265SDimitry Andric     function_ref<void(ArrayRef<int>, unsigned, unsigned)> ManyInputsAction) {
43881ad6265SDimitry Andric   SmallVector<SmallVector<SmallVector<int>>> Res(NumOfDestRegs);
43981ad6265SDimitry Andric   // Try to perform better estimation of the permutation.
44081ad6265SDimitry Andric   // 1. Split the source/destination vectors into real registers.
44181ad6265SDimitry Andric   // 2. Do the mask analysis to identify which real registers are
44281ad6265SDimitry Andric   // permuted.
44381ad6265SDimitry Andric   int Sz = Mask.size();
44481ad6265SDimitry Andric   unsigned SzDest = Sz / NumOfDestRegs;
44581ad6265SDimitry Andric   unsigned SzSrc = Sz / NumOfSrcRegs;
44681ad6265SDimitry Andric   for (unsigned I = 0; I < NumOfDestRegs; ++I) {
44781ad6265SDimitry Andric     auto &RegMasks = Res[I];
44881ad6265SDimitry Andric     RegMasks.assign(NumOfSrcRegs, {});
44981ad6265SDimitry Andric     // Check that the values in dest registers are in the one src
45081ad6265SDimitry Andric     // register.
45181ad6265SDimitry Andric     for (unsigned K = 0; K < SzDest; ++K) {
45281ad6265SDimitry Andric       int Idx = I * SzDest + K;
45381ad6265SDimitry Andric       if (Idx == Sz)
45481ad6265SDimitry Andric         break;
45506c3fb27SDimitry Andric       if (Mask[Idx] >= Sz || Mask[Idx] == PoisonMaskElem)
45681ad6265SDimitry Andric         continue;
45781ad6265SDimitry Andric       int SrcRegIdx = Mask[Idx] / SzSrc;
45881ad6265SDimitry Andric       // Add a cost of PermuteTwoSrc for each new source register permute,
45981ad6265SDimitry Andric       // if we have more than one source registers.
46081ad6265SDimitry Andric       if (RegMasks[SrcRegIdx].empty())
46106c3fb27SDimitry Andric         RegMasks[SrcRegIdx].assign(SzDest, PoisonMaskElem);
46281ad6265SDimitry Andric       RegMasks[SrcRegIdx][K] = Mask[Idx] % SzSrc;
46381ad6265SDimitry Andric     }
46481ad6265SDimitry Andric   }
46581ad6265SDimitry Andric   // Process split mask.
46681ad6265SDimitry Andric   for (unsigned I = 0; I < NumOfUsedRegs; ++I) {
46781ad6265SDimitry Andric     auto &Dest = Res[I];
46881ad6265SDimitry Andric     int NumSrcRegs =
46981ad6265SDimitry Andric         count_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
47081ad6265SDimitry Andric     switch (NumSrcRegs) {
47181ad6265SDimitry Andric     case 0:
47281ad6265SDimitry Andric       // No input vectors were used!
47381ad6265SDimitry Andric       NoInputAction();
47481ad6265SDimitry Andric       break;
47581ad6265SDimitry Andric     case 1: {
47681ad6265SDimitry Andric       // Find the only mask with at least single undef mask elem.
47781ad6265SDimitry Andric       auto *It =
47881ad6265SDimitry Andric           find_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
47981ad6265SDimitry Andric       unsigned SrcReg = std::distance(Dest.begin(), It);
48081ad6265SDimitry Andric       SingleInputAction(*It, SrcReg, I);
48181ad6265SDimitry Andric       break;
48281ad6265SDimitry Andric     }
48381ad6265SDimitry Andric     default: {
48481ad6265SDimitry Andric       // The first mask is a permutation of a single register. Since we have >2
48581ad6265SDimitry Andric       // input registers to shuffle, we merge the masks for 2 first registers
48681ad6265SDimitry Andric       // and generate a shuffle of 2 registers rather than the reordering of the
48781ad6265SDimitry Andric       // first register and then shuffle with the second register. Next,
48881ad6265SDimitry Andric       // generate the shuffles of the resulting register + the remaining
48981ad6265SDimitry Andric       // registers from the list.
49081ad6265SDimitry Andric       auto &&CombineMasks = [](MutableArrayRef<int> FirstMask,
49181ad6265SDimitry Andric                                ArrayRef<int> SecondMask) {
49281ad6265SDimitry Andric         for (int Idx = 0, VF = FirstMask.size(); Idx < VF; ++Idx) {
49306c3fb27SDimitry Andric           if (SecondMask[Idx] != PoisonMaskElem) {
49406c3fb27SDimitry Andric             assert(FirstMask[Idx] == PoisonMaskElem &&
49581ad6265SDimitry Andric                    "Expected undefined mask element.");
49681ad6265SDimitry Andric             FirstMask[Idx] = SecondMask[Idx] + VF;
49781ad6265SDimitry Andric           }
49881ad6265SDimitry Andric         }
49981ad6265SDimitry Andric       };
50081ad6265SDimitry Andric       auto &&NormalizeMask = [](MutableArrayRef<int> Mask) {
50181ad6265SDimitry Andric         for (int Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
50206c3fb27SDimitry Andric           if (Mask[Idx] != PoisonMaskElem)
50381ad6265SDimitry Andric             Mask[Idx] = Idx;
50481ad6265SDimitry Andric         }
50581ad6265SDimitry Andric       };
50681ad6265SDimitry Andric       int SecondIdx;
50781ad6265SDimitry Andric       do {
50881ad6265SDimitry Andric         int FirstIdx = -1;
50981ad6265SDimitry Andric         SecondIdx = -1;
51081ad6265SDimitry Andric         MutableArrayRef<int> FirstMask, SecondMask;
51181ad6265SDimitry Andric         for (unsigned I = 0; I < NumOfDestRegs; ++I) {
51281ad6265SDimitry Andric           SmallVectorImpl<int> &RegMask = Dest[I];
51381ad6265SDimitry Andric           if (RegMask.empty())
51481ad6265SDimitry Andric             continue;
51581ad6265SDimitry Andric 
51681ad6265SDimitry Andric           if (FirstIdx == SecondIdx) {
51781ad6265SDimitry Andric             FirstIdx = I;
51881ad6265SDimitry Andric             FirstMask = RegMask;
51981ad6265SDimitry Andric             continue;
52081ad6265SDimitry Andric           }
52181ad6265SDimitry Andric           SecondIdx = I;
52281ad6265SDimitry Andric           SecondMask = RegMask;
52381ad6265SDimitry Andric           CombineMasks(FirstMask, SecondMask);
52481ad6265SDimitry Andric           ManyInputsAction(FirstMask, FirstIdx, SecondIdx);
52581ad6265SDimitry Andric           NormalizeMask(FirstMask);
52681ad6265SDimitry Andric           RegMask.clear();
52781ad6265SDimitry Andric           SecondMask = FirstMask;
52881ad6265SDimitry Andric           SecondIdx = FirstIdx;
52981ad6265SDimitry Andric         }
53081ad6265SDimitry Andric         if (FirstIdx != SecondIdx && SecondIdx >= 0) {
53181ad6265SDimitry Andric           CombineMasks(SecondMask, FirstMask);
53281ad6265SDimitry Andric           ManyInputsAction(SecondMask, SecondIdx, FirstIdx);
53381ad6265SDimitry Andric           Dest[FirstIdx].clear();
53481ad6265SDimitry Andric           NormalizeMask(SecondMask);
53581ad6265SDimitry Andric         }
53681ad6265SDimitry Andric       } while (SecondIdx >= 0);
53781ad6265SDimitry Andric       break;
53881ad6265SDimitry Andric     }
53981ad6265SDimitry Andric     }
54081ad6265SDimitry Andric   }
54181ad6265SDimitry Andric }
54281ad6265SDimitry Andric 
5430b57cec5SDimitry Andric MapVector<Instruction *, uint64_t>
computeMinimumValueSizes(ArrayRef<BasicBlock * > Blocks,DemandedBits & DB,const TargetTransformInfo * TTI)5440b57cec5SDimitry Andric llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB,
5450b57cec5SDimitry Andric                                const TargetTransformInfo *TTI) {
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric   // DemandedBits will give us every value's live-out bits. But we want
5480b57cec5SDimitry Andric   // to ensure no extra casts would need to be inserted, so every DAG
5490b57cec5SDimitry Andric   // of connected values must have the same minimum bitwidth.
5500b57cec5SDimitry Andric   EquivalenceClasses<Value *> ECs;
5510b57cec5SDimitry Andric   SmallVector<Value *, 16> Worklist;
5520b57cec5SDimitry Andric   SmallPtrSet<Value *, 4> Roots;
5530b57cec5SDimitry Andric   SmallPtrSet<Value *, 16> Visited;
5540b57cec5SDimitry Andric   DenseMap<Value *, uint64_t> DBits;
5550b57cec5SDimitry Andric   SmallPtrSet<Instruction *, 4> InstructionSet;
5560b57cec5SDimitry Andric   MapVector<Instruction *, uint64_t> MinBWs;
5570b57cec5SDimitry Andric 
5580b57cec5SDimitry Andric   // Determine the roots. We work bottom-up, from truncs or icmps.
5590b57cec5SDimitry Andric   bool SeenExtFromIllegalType = false;
5600b57cec5SDimitry Andric   for (auto *BB : Blocks)
5610b57cec5SDimitry Andric     for (auto &I : *BB) {
5620b57cec5SDimitry Andric       InstructionSet.insert(&I);
5630b57cec5SDimitry Andric 
5640b57cec5SDimitry Andric       if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
5650b57cec5SDimitry Andric           !TTI->isTypeLegal(I.getOperand(0)->getType()))
5660b57cec5SDimitry Andric         SeenExtFromIllegalType = true;
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric       // Only deal with non-vector integers up to 64-bits wide.
5690b57cec5SDimitry Andric       if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
5700b57cec5SDimitry Andric           !I.getType()->isVectorTy() &&
5710b57cec5SDimitry Andric           I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
5720b57cec5SDimitry Andric         // Don't make work for ourselves. If we know the loaded type is legal,
5730b57cec5SDimitry Andric         // don't add it to the worklist.
5740b57cec5SDimitry Andric         if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
5750b57cec5SDimitry Andric           continue;
5760b57cec5SDimitry Andric 
5770b57cec5SDimitry Andric         Worklist.push_back(&I);
5780b57cec5SDimitry Andric         Roots.insert(&I);
5790b57cec5SDimitry Andric       }
5800b57cec5SDimitry Andric     }
5810b57cec5SDimitry Andric   // Early exit.
5820b57cec5SDimitry Andric   if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
5830b57cec5SDimitry Andric     return MinBWs;
5840b57cec5SDimitry Andric 
5850b57cec5SDimitry Andric   // Now proceed breadth-first, unioning values together.
5860b57cec5SDimitry Andric   while (!Worklist.empty()) {
5870b57cec5SDimitry Andric     Value *Val = Worklist.pop_back_val();
5880b57cec5SDimitry Andric     Value *Leader = ECs.getOrInsertLeaderValue(Val);
5890b57cec5SDimitry Andric 
59081ad6265SDimitry Andric     if (!Visited.insert(Val).second)
5910b57cec5SDimitry Andric       continue;
5920b57cec5SDimitry Andric 
5930b57cec5SDimitry Andric     // Non-instructions terminate a chain successfully.
5940b57cec5SDimitry Andric     if (!isa<Instruction>(Val))
5950b57cec5SDimitry Andric       continue;
5960b57cec5SDimitry Andric     Instruction *I = cast<Instruction>(Val);
5970b57cec5SDimitry Andric 
5980b57cec5SDimitry Andric     // If we encounter a type that is larger than 64 bits, we can't represent
5990b57cec5SDimitry Andric     // it so bail out.
6000b57cec5SDimitry Andric     if (DB.getDemandedBits(I).getBitWidth() > 64)
6010b57cec5SDimitry Andric       return MapVector<Instruction *, uint64_t>();
6020b57cec5SDimitry Andric 
6030b57cec5SDimitry Andric     uint64_t V = DB.getDemandedBits(I).getZExtValue();
6040b57cec5SDimitry Andric     DBits[Leader] |= V;
6050b57cec5SDimitry Andric     DBits[I] = V;
6060b57cec5SDimitry Andric 
6070b57cec5SDimitry Andric     // Casts, loads and instructions outside of our range terminate a chain
6080b57cec5SDimitry Andric     // successfully.
6090b57cec5SDimitry Andric     if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
6100b57cec5SDimitry Andric         !InstructionSet.count(I))
6110b57cec5SDimitry Andric       continue;
6120b57cec5SDimitry Andric 
6130b57cec5SDimitry Andric     // Unsafe casts terminate a chain unsuccessfully. We can't do anything
6140b57cec5SDimitry Andric     // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
6150b57cec5SDimitry Andric     // transform anything that relies on them.
6160b57cec5SDimitry Andric     if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
6170b57cec5SDimitry Andric         !I->getType()->isIntegerTy()) {
6180b57cec5SDimitry Andric       DBits[Leader] |= ~0ULL;
6190b57cec5SDimitry Andric       continue;
6200b57cec5SDimitry Andric     }
6210b57cec5SDimitry Andric 
6220b57cec5SDimitry Andric     // We don't modify the types of PHIs. Reductions will already have been
6230b57cec5SDimitry Andric     // truncated if possible, and inductions' sizes will have been chosen by
6240b57cec5SDimitry Andric     // indvars.
6250b57cec5SDimitry Andric     if (isa<PHINode>(I))
6260b57cec5SDimitry Andric       continue;
6270b57cec5SDimitry Andric 
6280b57cec5SDimitry Andric     if (DBits[Leader] == ~0ULL)
6290b57cec5SDimitry Andric       // All bits demanded, no point continuing.
6300b57cec5SDimitry Andric       continue;
6310b57cec5SDimitry Andric 
6320b57cec5SDimitry Andric     for (Value *O : cast<User>(I)->operands()) {
6330b57cec5SDimitry Andric       ECs.unionSets(Leader, O);
6340b57cec5SDimitry Andric       Worklist.push_back(O);
6350b57cec5SDimitry Andric     }
6360b57cec5SDimitry Andric   }
6370b57cec5SDimitry Andric 
6380b57cec5SDimitry Andric   // Now we've discovered all values, walk them to see if there are
6390b57cec5SDimitry Andric   // any users we didn't see. If there are, we can't optimize that
6400b57cec5SDimitry Andric   // chain.
6410b57cec5SDimitry Andric   for (auto &I : DBits)
6420b57cec5SDimitry Andric     for (auto *U : I.first->users())
6430b57cec5SDimitry Andric       if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
6440b57cec5SDimitry Andric         DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric   for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
6470b57cec5SDimitry Andric     uint64_t LeaderDemandedBits = 0;
648fe6060f1SDimitry Andric     for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
649fe6060f1SDimitry Andric       LeaderDemandedBits |= DBits[M];
6500b57cec5SDimitry Andric 
65106c3fb27SDimitry Andric     uint64_t MinBW = llvm::bit_width(LeaderDemandedBits);
6520b57cec5SDimitry Andric     // Round up to a power of 2
65306c3fb27SDimitry Andric     MinBW = llvm::bit_ceil(MinBW);
6540b57cec5SDimitry Andric 
6550b57cec5SDimitry Andric     // We don't modify the types of PHIs. Reductions will already have been
6560b57cec5SDimitry Andric     // truncated if possible, and inductions' sizes will have been chosen by
6570b57cec5SDimitry Andric     // indvars.
6580b57cec5SDimitry Andric     // If we are required to shrink a PHI, abandon this entire equivalence class.
6590b57cec5SDimitry Andric     bool Abort = false;
660fe6060f1SDimitry Andric     for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
661fe6060f1SDimitry Andric       if (isa<PHINode>(M) && MinBW < M->getType()->getScalarSizeInBits()) {
6620b57cec5SDimitry Andric         Abort = true;
6630b57cec5SDimitry Andric         break;
6640b57cec5SDimitry Andric       }
6650b57cec5SDimitry Andric     if (Abort)
6660b57cec5SDimitry Andric       continue;
6670b57cec5SDimitry Andric 
668fe6060f1SDimitry Andric     for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end())) {
66906c3fb27SDimitry Andric       auto *MI = dyn_cast<Instruction>(M);
67006c3fb27SDimitry Andric       if (!MI)
6710b57cec5SDimitry Andric         continue;
672fe6060f1SDimitry Andric       Type *Ty = M->getType();
673fe6060f1SDimitry Andric       if (Roots.count(M))
67406c3fb27SDimitry Andric         Ty = MI->getOperand(0)->getType();
67506c3fb27SDimitry Andric 
67606c3fb27SDimitry Andric       if (MinBW >= Ty->getScalarSizeInBits())
67706c3fb27SDimitry Andric         continue;
67806c3fb27SDimitry Andric 
67906c3fb27SDimitry Andric       // If any of M's operands demand more bits than MinBW then M cannot be
68006c3fb27SDimitry Andric       // performed safely in MinBW.
68106c3fb27SDimitry Andric       if (any_of(MI->operands(), [&DB, MinBW](Use &U) {
68206c3fb27SDimitry Andric             auto *CI = dyn_cast<ConstantInt>(U);
68306c3fb27SDimitry Andric             // For constants shift amounts, check if the shift would result in
68406c3fb27SDimitry Andric             // poison.
68506c3fb27SDimitry Andric             if (CI &&
68606c3fb27SDimitry Andric                 isa<ShlOperator, LShrOperator, AShrOperator>(U.getUser()) &&
68706c3fb27SDimitry Andric                 U.getOperandNo() == 1)
68806c3fb27SDimitry Andric               return CI->uge(MinBW);
68906c3fb27SDimitry Andric             uint64_t BW = bit_width(DB.getDemandedBits(&U).getZExtValue());
69006c3fb27SDimitry Andric             return bit_ceil(BW) > MinBW;
69106c3fb27SDimitry Andric           }))
69206c3fb27SDimitry Andric         continue;
69306c3fb27SDimitry Andric 
69406c3fb27SDimitry Andric       MinBWs[MI] = MinBW;
6950b57cec5SDimitry Andric     }
6960b57cec5SDimitry Andric   }
6970b57cec5SDimitry Andric 
6980b57cec5SDimitry Andric   return MinBWs;
6990b57cec5SDimitry Andric }
7000b57cec5SDimitry Andric 
7010b57cec5SDimitry Andric /// Add all access groups in @p AccGroups to @p List.
7020b57cec5SDimitry Andric template <typename ListT>
addToAccessGroupList(ListT & List,MDNode * AccGroups)7030b57cec5SDimitry Andric static void addToAccessGroupList(ListT &List, MDNode *AccGroups) {
7040b57cec5SDimitry Andric   // Interpret an access group as a list containing itself.
7050b57cec5SDimitry Andric   if (AccGroups->getNumOperands() == 0) {
7060b57cec5SDimitry Andric     assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group");
7070b57cec5SDimitry Andric     List.insert(AccGroups);
7080b57cec5SDimitry Andric     return;
7090b57cec5SDimitry Andric   }
7100b57cec5SDimitry Andric 
711fcaf7f86SDimitry Andric   for (const auto &AccGroupListOp : AccGroups->operands()) {
7120b57cec5SDimitry Andric     auto *Item = cast<MDNode>(AccGroupListOp.get());
7130b57cec5SDimitry Andric     assert(isValidAsAccessGroup(Item) && "List item must be an access group");
7140b57cec5SDimitry Andric     List.insert(Item);
7150b57cec5SDimitry Andric   }
7160b57cec5SDimitry Andric }
7170b57cec5SDimitry Andric 
uniteAccessGroups(MDNode * AccGroups1,MDNode * AccGroups2)7180b57cec5SDimitry Andric MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) {
7190b57cec5SDimitry Andric   if (!AccGroups1)
7200b57cec5SDimitry Andric     return AccGroups2;
7210b57cec5SDimitry Andric   if (!AccGroups2)
7220b57cec5SDimitry Andric     return AccGroups1;
7230b57cec5SDimitry Andric   if (AccGroups1 == AccGroups2)
7240b57cec5SDimitry Andric     return AccGroups1;
7250b57cec5SDimitry Andric 
7260b57cec5SDimitry Andric   SmallSetVector<Metadata *, 4> Union;
7270b57cec5SDimitry Andric   addToAccessGroupList(Union, AccGroups1);
7280b57cec5SDimitry Andric   addToAccessGroupList(Union, AccGroups2);
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric   if (Union.size() == 0)
7310b57cec5SDimitry Andric     return nullptr;
7320b57cec5SDimitry Andric   if (Union.size() == 1)
7330b57cec5SDimitry Andric     return cast<MDNode>(Union.front());
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric   LLVMContext &Ctx = AccGroups1->getContext();
7360b57cec5SDimitry Andric   return MDNode::get(Ctx, Union.getArrayRef());
7370b57cec5SDimitry Andric }
7380b57cec5SDimitry Andric 
intersectAccessGroups(const Instruction * Inst1,const Instruction * Inst2)7390b57cec5SDimitry Andric MDNode *llvm::intersectAccessGroups(const Instruction *Inst1,
7400b57cec5SDimitry Andric                                     const Instruction *Inst2) {
7410b57cec5SDimitry Andric   bool MayAccessMem1 = Inst1->mayReadOrWriteMemory();
7420b57cec5SDimitry Andric   bool MayAccessMem2 = Inst2->mayReadOrWriteMemory();
7430b57cec5SDimitry Andric 
7440b57cec5SDimitry Andric   if (!MayAccessMem1 && !MayAccessMem2)
7450b57cec5SDimitry Andric     return nullptr;
7460b57cec5SDimitry Andric   if (!MayAccessMem1)
7470b57cec5SDimitry Andric     return Inst2->getMetadata(LLVMContext::MD_access_group);
7480b57cec5SDimitry Andric   if (!MayAccessMem2)
7490b57cec5SDimitry Andric     return Inst1->getMetadata(LLVMContext::MD_access_group);
7500b57cec5SDimitry Andric 
7510b57cec5SDimitry Andric   MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group);
7520b57cec5SDimitry Andric   MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group);
7530b57cec5SDimitry Andric   if (!MD1 || !MD2)
7540b57cec5SDimitry Andric     return nullptr;
7550b57cec5SDimitry Andric   if (MD1 == MD2)
7560b57cec5SDimitry Andric     return MD1;
7570b57cec5SDimitry Andric 
7580b57cec5SDimitry Andric   // Use set for scalable 'contains' check.
7590b57cec5SDimitry Andric   SmallPtrSet<Metadata *, 4> AccGroupSet2;
7600b57cec5SDimitry Andric   addToAccessGroupList(AccGroupSet2, MD2);
7610b57cec5SDimitry Andric 
7620b57cec5SDimitry Andric   SmallVector<Metadata *, 4> Intersection;
7630b57cec5SDimitry Andric   if (MD1->getNumOperands() == 0) {
7640b57cec5SDimitry Andric     assert(isValidAsAccessGroup(MD1) && "Node must be an access group");
7650b57cec5SDimitry Andric     if (AccGroupSet2.count(MD1))
7660b57cec5SDimitry Andric       Intersection.push_back(MD1);
7670b57cec5SDimitry Andric   } else {
7680b57cec5SDimitry Andric     for (const MDOperand &Node : MD1->operands()) {
7690b57cec5SDimitry Andric       auto *Item = cast<MDNode>(Node.get());
7700b57cec5SDimitry Andric       assert(isValidAsAccessGroup(Item) && "List item must be an access group");
7710b57cec5SDimitry Andric       if (AccGroupSet2.count(Item))
7720b57cec5SDimitry Andric         Intersection.push_back(Item);
7730b57cec5SDimitry Andric     }
7740b57cec5SDimitry Andric   }
7750b57cec5SDimitry Andric 
7760b57cec5SDimitry Andric   if (Intersection.size() == 0)
7770b57cec5SDimitry Andric     return nullptr;
7780b57cec5SDimitry Andric   if (Intersection.size() == 1)
7790b57cec5SDimitry Andric     return cast<MDNode>(Intersection.front());
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric   LLVMContext &Ctx = Inst1->getContext();
7820b57cec5SDimitry Andric   return MDNode::get(Ctx, Intersection);
7830b57cec5SDimitry Andric }
7840b57cec5SDimitry Andric 
7850b57cec5SDimitry Andric /// \returns \p I after propagating metadata from \p VL.
propagateMetadata(Instruction * Inst,ArrayRef<Value * > VL)7860b57cec5SDimitry Andric Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
787fe6060f1SDimitry Andric   if (VL.empty())
788fe6060f1SDimitry Andric     return Inst;
7890b57cec5SDimitry Andric   Instruction *I0 = cast<Instruction>(VL[0]);
7900b57cec5SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
7910b57cec5SDimitry Andric   I0->getAllMetadataOtherThanDebugLoc(Metadata);
7920b57cec5SDimitry Andric 
7930b57cec5SDimitry Andric   for (auto Kind : {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
7940b57cec5SDimitry Andric                     LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
7950b57cec5SDimitry Andric                     LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load,
7960b57cec5SDimitry Andric                     LLVMContext::MD_access_group}) {
7970b57cec5SDimitry Andric     MDNode *MD = I0->getMetadata(Kind);
7980b57cec5SDimitry Andric 
7990b57cec5SDimitry Andric     for (int J = 1, E = VL.size(); MD && J != E; ++J) {
8000b57cec5SDimitry Andric       const Instruction *IJ = cast<Instruction>(VL[J]);
8010b57cec5SDimitry Andric       MDNode *IMD = IJ->getMetadata(Kind);
8020b57cec5SDimitry Andric       switch (Kind) {
8030b57cec5SDimitry Andric       case LLVMContext::MD_tbaa:
8040b57cec5SDimitry Andric         MD = MDNode::getMostGenericTBAA(MD, IMD);
8050b57cec5SDimitry Andric         break;
8060b57cec5SDimitry Andric       case LLVMContext::MD_alias_scope:
8070b57cec5SDimitry Andric         MD = MDNode::getMostGenericAliasScope(MD, IMD);
8080b57cec5SDimitry Andric         break;
8090b57cec5SDimitry Andric       case LLVMContext::MD_fpmath:
8100b57cec5SDimitry Andric         MD = MDNode::getMostGenericFPMath(MD, IMD);
8110b57cec5SDimitry Andric         break;
8120b57cec5SDimitry Andric       case LLVMContext::MD_noalias:
8130b57cec5SDimitry Andric       case LLVMContext::MD_nontemporal:
8140b57cec5SDimitry Andric       case LLVMContext::MD_invariant_load:
8150b57cec5SDimitry Andric         MD = MDNode::intersect(MD, IMD);
8160b57cec5SDimitry Andric         break;
8170b57cec5SDimitry Andric       case LLVMContext::MD_access_group:
8180b57cec5SDimitry Andric         MD = intersectAccessGroups(Inst, IJ);
8190b57cec5SDimitry Andric         break;
8200b57cec5SDimitry Andric       default:
8210b57cec5SDimitry Andric         llvm_unreachable("unhandled metadata");
8220b57cec5SDimitry Andric       }
8230b57cec5SDimitry Andric     }
8240b57cec5SDimitry Andric 
8250b57cec5SDimitry Andric     Inst->setMetadata(Kind, MD);
8260b57cec5SDimitry Andric   }
8270b57cec5SDimitry Andric 
8280b57cec5SDimitry Andric   return Inst;
8290b57cec5SDimitry Andric }
8300b57cec5SDimitry Andric 
8310b57cec5SDimitry Andric Constant *
createBitMaskForGaps(IRBuilderBase & Builder,unsigned VF,const InterleaveGroup<Instruction> & Group)8325ffd83dbSDimitry Andric llvm::createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF,
8330b57cec5SDimitry Andric                            const InterleaveGroup<Instruction> &Group) {
8340b57cec5SDimitry Andric   // All 1's means mask is not needed.
8350b57cec5SDimitry Andric   if (Group.getNumMembers() == Group.getFactor())
8360b57cec5SDimitry Andric     return nullptr;
8370b57cec5SDimitry Andric 
8380b57cec5SDimitry Andric   // TODO: support reversed access.
8390b57cec5SDimitry Andric   assert(!Group.isReverse() && "Reversed group not supported.");
8400b57cec5SDimitry Andric 
8410b57cec5SDimitry Andric   SmallVector<Constant *, 16> Mask;
8420b57cec5SDimitry Andric   for (unsigned i = 0; i < VF; i++)
8430b57cec5SDimitry Andric     for (unsigned j = 0; j < Group.getFactor(); ++j) {
8440b57cec5SDimitry Andric       unsigned HasMember = Group.getMember(j) ? 1 : 0;
8450b57cec5SDimitry Andric       Mask.push_back(Builder.getInt1(HasMember));
8460b57cec5SDimitry Andric     }
8470b57cec5SDimitry Andric 
8480b57cec5SDimitry Andric   return ConstantVector::get(Mask);
8490b57cec5SDimitry Andric }
8500b57cec5SDimitry Andric 
8515ffd83dbSDimitry Andric llvm::SmallVector<int, 16>
createReplicatedMask(unsigned ReplicationFactor,unsigned VF)8525ffd83dbSDimitry Andric llvm::createReplicatedMask(unsigned ReplicationFactor, unsigned VF) {
8535ffd83dbSDimitry Andric   SmallVector<int, 16> MaskVec;
8540b57cec5SDimitry Andric   for (unsigned i = 0; i < VF; i++)
8550b57cec5SDimitry Andric     for (unsigned j = 0; j < ReplicationFactor; j++)
8565ffd83dbSDimitry Andric       MaskVec.push_back(i);
8570b57cec5SDimitry Andric 
8585ffd83dbSDimitry Andric   return MaskVec;
8590b57cec5SDimitry Andric }
8600b57cec5SDimitry Andric 
createInterleaveMask(unsigned VF,unsigned NumVecs)8615ffd83dbSDimitry Andric llvm::SmallVector<int, 16> llvm::createInterleaveMask(unsigned VF,
8620b57cec5SDimitry Andric                                                       unsigned NumVecs) {
8635ffd83dbSDimitry Andric   SmallVector<int, 16> Mask;
8640b57cec5SDimitry Andric   for (unsigned i = 0; i < VF; i++)
8650b57cec5SDimitry Andric     for (unsigned j = 0; j < NumVecs; j++)
8665ffd83dbSDimitry Andric       Mask.push_back(j * VF + i);
8670b57cec5SDimitry Andric 
8685ffd83dbSDimitry Andric   return Mask;
8690b57cec5SDimitry Andric }
8700b57cec5SDimitry Andric 
8715ffd83dbSDimitry Andric llvm::SmallVector<int, 16>
createStrideMask(unsigned Start,unsigned Stride,unsigned VF)8725ffd83dbSDimitry Andric llvm::createStrideMask(unsigned Start, unsigned Stride, unsigned VF) {
8735ffd83dbSDimitry Andric   SmallVector<int, 16> Mask;
8740b57cec5SDimitry Andric   for (unsigned i = 0; i < VF; i++)
8755ffd83dbSDimitry Andric     Mask.push_back(Start + i * Stride);
8760b57cec5SDimitry Andric 
8775ffd83dbSDimitry Andric   return Mask;
8780b57cec5SDimitry Andric }
8790b57cec5SDimitry Andric 
createSequentialMask(unsigned Start,unsigned NumInts,unsigned NumUndefs)8805ffd83dbSDimitry Andric llvm::SmallVector<int, 16> llvm::createSequentialMask(unsigned Start,
8815ffd83dbSDimitry Andric                                                       unsigned NumInts,
8825ffd83dbSDimitry Andric                                                       unsigned NumUndefs) {
8835ffd83dbSDimitry Andric   SmallVector<int, 16> Mask;
8840b57cec5SDimitry Andric   for (unsigned i = 0; i < NumInts; i++)
8855ffd83dbSDimitry Andric     Mask.push_back(Start + i);
8860b57cec5SDimitry Andric 
8870b57cec5SDimitry Andric   for (unsigned i = 0; i < NumUndefs; i++)
8885ffd83dbSDimitry Andric     Mask.push_back(-1);
8890b57cec5SDimitry Andric 
8905ffd83dbSDimitry Andric   return Mask;
8910b57cec5SDimitry Andric }
8920b57cec5SDimitry Andric 
createUnaryMask(ArrayRef<int> Mask,unsigned NumElts)893349cc55cSDimitry Andric llvm::SmallVector<int, 16> llvm::createUnaryMask(ArrayRef<int> Mask,
894349cc55cSDimitry Andric                                                  unsigned NumElts) {
895349cc55cSDimitry Andric   // Avoid casts in the loop and make sure we have a reasonable number.
896349cc55cSDimitry Andric   int NumEltsSigned = NumElts;
897349cc55cSDimitry Andric   assert(NumEltsSigned > 0 && "Expected smaller or non-zero element count");
898349cc55cSDimitry Andric 
899349cc55cSDimitry Andric   // If the mask chooses an element from operand 1, reduce it to choose from the
900349cc55cSDimitry Andric   // corresponding element of operand 0. Undef mask elements are unchanged.
901349cc55cSDimitry Andric   SmallVector<int, 16> UnaryMask;
902349cc55cSDimitry Andric   for (int MaskElt : Mask) {
903349cc55cSDimitry Andric     assert((MaskElt < NumEltsSigned * 2) && "Expected valid shuffle mask");
904349cc55cSDimitry Andric     int UnaryElt = MaskElt >= NumEltsSigned ? MaskElt - NumEltsSigned : MaskElt;
905349cc55cSDimitry Andric     UnaryMask.push_back(UnaryElt);
906349cc55cSDimitry Andric   }
907349cc55cSDimitry Andric   return UnaryMask;
908349cc55cSDimitry Andric }
909349cc55cSDimitry Andric 
9100b57cec5SDimitry Andric /// A helper function for concatenating vectors. This function concatenates two
9110b57cec5SDimitry Andric /// vectors having the same element type. If the second vector has fewer
9120b57cec5SDimitry Andric /// elements than the first, it is padded with undefs.
concatenateTwoVectors(IRBuilderBase & Builder,Value * V1,Value * V2)9135ffd83dbSDimitry Andric static Value *concatenateTwoVectors(IRBuilderBase &Builder, Value *V1,
9140b57cec5SDimitry Andric                                     Value *V2) {
9150b57cec5SDimitry Andric   VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
9160b57cec5SDimitry Andric   VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
9170b57cec5SDimitry Andric   assert(VecTy1 && VecTy2 &&
9180b57cec5SDimitry Andric          VecTy1->getScalarType() == VecTy2->getScalarType() &&
9190b57cec5SDimitry Andric          "Expect two vectors with the same element type");
9200b57cec5SDimitry Andric 
921e8d8bef9SDimitry Andric   unsigned NumElts1 = cast<FixedVectorType>(VecTy1)->getNumElements();
922e8d8bef9SDimitry Andric   unsigned NumElts2 = cast<FixedVectorType>(VecTy2)->getNumElements();
9230b57cec5SDimitry Andric   assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
9240b57cec5SDimitry Andric 
9250b57cec5SDimitry Andric   if (NumElts1 > NumElts2) {
9260b57cec5SDimitry Andric     // Extend with UNDEFs.
9275ffd83dbSDimitry Andric     V2 = Builder.CreateShuffleVector(
928e8d8bef9SDimitry Andric         V2, createSequentialMask(0, NumElts2, NumElts1 - NumElts2));
9290b57cec5SDimitry Andric   }
9300b57cec5SDimitry Andric 
9315ffd83dbSDimitry Andric   return Builder.CreateShuffleVector(
9325ffd83dbSDimitry Andric       V1, V2, createSequentialMask(0, NumElts1 + NumElts2, 0));
9330b57cec5SDimitry Andric }
9340b57cec5SDimitry Andric 
concatenateVectors(IRBuilderBase & Builder,ArrayRef<Value * > Vecs)9355ffd83dbSDimitry Andric Value *llvm::concatenateVectors(IRBuilderBase &Builder,
9365ffd83dbSDimitry Andric                                 ArrayRef<Value *> Vecs) {
9370b57cec5SDimitry Andric   unsigned NumVecs = Vecs.size();
9380b57cec5SDimitry Andric   assert(NumVecs > 1 && "Should be at least two vectors");
9390b57cec5SDimitry Andric 
9400b57cec5SDimitry Andric   SmallVector<Value *, 8> ResList;
9410b57cec5SDimitry Andric   ResList.append(Vecs.begin(), Vecs.end());
9420b57cec5SDimitry Andric   do {
9430b57cec5SDimitry Andric     SmallVector<Value *, 8> TmpList;
9440b57cec5SDimitry Andric     for (unsigned i = 0; i < NumVecs - 1; i += 2) {
9450b57cec5SDimitry Andric       Value *V0 = ResList[i], *V1 = ResList[i + 1];
9460b57cec5SDimitry Andric       assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
9470b57cec5SDimitry Andric              "Only the last vector may have a different type");
9480b57cec5SDimitry Andric 
9490b57cec5SDimitry Andric       TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
9500b57cec5SDimitry Andric     }
9510b57cec5SDimitry Andric 
9520b57cec5SDimitry Andric     // Push the last vector if the total number of vectors is odd.
9530b57cec5SDimitry Andric     if (NumVecs % 2 != 0)
9540b57cec5SDimitry Andric       TmpList.push_back(ResList[NumVecs - 1]);
9550b57cec5SDimitry Andric 
9560b57cec5SDimitry Andric     ResList = TmpList;
9570b57cec5SDimitry Andric     NumVecs = ResList.size();
9580b57cec5SDimitry Andric   } while (NumVecs > 1);
9590b57cec5SDimitry Andric 
9600b57cec5SDimitry Andric   return ResList[0];
9610b57cec5SDimitry Andric }
9620b57cec5SDimitry Andric 
maskIsAllZeroOrUndef(Value * Mask)9630b57cec5SDimitry Andric bool llvm::maskIsAllZeroOrUndef(Value *Mask) {
964e8d8bef9SDimitry Andric   assert(isa<VectorType>(Mask->getType()) &&
965e8d8bef9SDimitry Andric          isa<IntegerType>(Mask->getType()->getScalarType()) &&
966e8d8bef9SDimitry Andric          cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
967e8d8bef9SDimitry Andric              1 &&
968e8d8bef9SDimitry Andric          "Mask must be a vector of i1");
969e8d8bef9SDimitry Andric 
9700b57cec5SDimitry Andric   auto *ConstMask = dyn_cast<Constant>(Mask);
9710b57cec5SDimitry Andric   if (!ConstMask)
9720b57cec5SDimitry Andric     return false;
9730b57cec5SDimitry Andric   if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
9740b57cec5SDimitry Andric     return true;
975e8d8bef9SDimitry Andric   if (isa<ScalableVectorType>(ConstMask->getType()))
976e8d8bef9SDimitry Andric     return false;
977e8d8bef9SDimitry Andric   for (unsigned
978e8d8bef9SDimitry Andric            I = 0,
979e8d8bef9SDimitry Andric            E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
9805ffd83dbSDimitry Andric        I != E; ++I) {
9810b57cec5SDimitry Andric     if (auto *MaskElt = ConstMask->getAggregateElement(I))
9820b57cec5SDimitry Andric       if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
9830b57cec5SDimitry Andric         continue;
9840b57cec5SDimitry Andric     return false;
9850b57cec5SDimitry Andric   }
9860b57cec5SDimitry Andric   return true;
9870b57cec5SDimitry Andric }
9880b57cec5SDimitry Andric 
maskIsAllOneOrUndef(Value * Mask)9890b57cec5SDimitry Andric bool llvm::maskIsAllOneOrUndef(Value *Mask) {
990e8d8bef9SDimitry Andric   assert(isa<VectorType>(Mask->getType()) &&
991e8d8bef9SDimitry Andric          isa<IntegerType>(Mask->getType()->getScalarType()) &&
992e8d8bef9SDimitry Andric          cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
993e8d8bef9SDimitry Andric              1 &&
994e8d8bef9SDimitry Andric          "Mask must be a vector of i1");
995e8d8bef9SDimitry Andric 
9960b57cec5SDimitry Andric   auto *ConstMask = dyn_cast<Constant>(Mask);
9970b57cec5SDimitry Andric   if (!ConstMask)
9980b57cec5SDimitry Andric     return false;
9990b57cec5SDimitry Andric   if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
10000b57cec5SDimitry Andric     return true;
1001e8d8bef9SDimitry Andric   if (isa<ScalableVectorType>(ConstMask->getType()))
1002e8d8bef9SDimitry Andric     return false;
1003e8d8bef9SDimitry Andric   for (unsigned
1004e8d8bef9SDimitry Andric            I = 0,
1005e8d8bef9SDimitry Andric            E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
10065ffd83dbSDimitry Andric        I != E; ++I) {
10070b57cec5SDimitry Andric     if (auto *MaskElt = ConstMask->getAggregateElement(I))
10080b57cec5SDimitry Andric       if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
10090b57cec5SDimitry Andric         continue;
10100b57cec5SDimitry Andric     return false;
10110b57cec5SDimitry Andric   }
10120b57cec5SDimitry Andric   return true;
10130b57cec5SDimitry Andric }
10140b57cec5SDimitry Andric 
maskContainsAllOneOrUndef(Value * Mask)1015439352acSDimitry Andric bool llvm::maskContainsAllOneOrUndef(Value *Mask) {
1016439352acSDimitry Andric   assert(isa<VectorType>(Mask->getType()) &&
1017439352acSDimitry Andric          isa<IntegerType>(Mask->getType()->getScalarType()) &&
1018439352acSDimitry Andric          cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
1019439352acSDimitry Andric              1 &&
1020439352acSDimitry Andric          "Mask must be a vector of i1");
1021439352acSDimitry Andric 
1022439352acSDimitry Andric   auto *ConstMask = dyn_cast<Constant>(Mask);
1023439352acSDimitry Andric   if (!ConstMask)
1024439352acSDimitry Andric     return false;
1025439352acSDimitry Andric   if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
1026439352acSDimitry Andric     return true;
1027439352acSDimitry Andric   if (isa<ScalableVectorType>(ConstMask->getType()))
1028439352acSDimitry Andric     return false;
1029439352acSDimitry Andric   for (unsigned
1030439352acSDimitry Andric            I = 0,
1031439352acSDimitry Andric            E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
1032439352acSDimitry Andric        I != E; ++I) {
1033439352acSDimitry Andric     if (auto *MaskElt = ConstMask->getAggregateElement(I))
1034439352acSDimitry Andric       if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
1035439352acSDimitry Andric         return true;
1036439352acSDimitry Andric   }
1037439352acSDimitry Andric   return false;
1038439352acSDimitry Andric }
1039439352acSDimitry Andric 
10400b57cec5SDimitry Andric /// TODO: This is a lot like known bits, but for
10410b57cec5SDimitry Andric /// vectors.  Is there something we can common this with?
possiblyDemandedEltsInMask(Value * Mask)10420b57cec5SDimitry Andric APInt llvm::possiblyDemandedEltsInMask(Value *Mask) {
1043e8d8bef9SDimitry Andric   assert(isa<FixedVectorType>(Mask->getType()) &&
1044e8d8bef9SDimitry Andric          isa<IntegerType>(Mask->getType()->getScalarType()) &&
1045e8d8bef9SDimitry Andric          cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
1046e8d8bef9SDimitry Andric              1 &&
1047e8d8bef9SDimitry Andric          "Mask must be a fixed width vector of i1");
10480b57cec5SDimitry Andric 
1049e8d8bef9SDimitry Andric   const unsigned VWidth =
1050e8d8bef9SDimitry Andric       cast<FixedVectorType>(Mask->getType())->getNumElements();
1051349cc55cSDimitry Andric   APInt DemandedElts = APInt::getAllOnes(VWidth);
10520b57cec5SDimitry Andric   if (auto *CV = dyn_cast<ConstantVector>(Mask))
10530b57cec5SDimitry Andric     for (unsigned i = 0; i < VWidth; i++)
10540b57cec5SDimitry Andric       if (CV->getAggregateElement(i)->isNullValue())
10550b57cec5SDimitry Andric         DemandedElts.clearBit(i);
10560b57cec5SDimitry Andric   return DemandedElts;
10570b57cec5SDimitry Andric }
10580b57cec5SDimitry Andric 
isStrided(int Stride)10590b57cec5SDimitry Andric bool InterleavedAccessInfo::isStrided(int Stride) {
10600b57cec5SDimitry Andric   unsigned Factor = std::abs(Stride);
10610b57cec5SDimitry Andric   return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
10620b57cec5SDimitry Andric }
10630b57cec5SDimitry Andric 
collectConstStrideAccesses(MapVector<Instruction *,StrideDescriptor> & AccessStrideInfo,const DenseMap<Value *,const SCEV * > & Strides)10640b57cec5SDimitry Andric void InterleavedAccessInfo::collectConstStrideAccesses(
10650b57cec5SDimitry Andric     MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
106606c3fb27SDimitry Andric     const DenseMap<Value*, const SCEV*> &Strides) {
10670b57cec5SDimitry Andric   auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
10680b57cec5SDimitry Andric 
10690b57cec5SDimitry Andric   // Since it's desired that the load/store instructions be maintained in
10700b57cec5SDimitry Andric   // "program order" for the interleaved access analysis, we have to visit the
10710b57cec5SDimitry Andric   // blocks in the loop in reverse postorder (i.e., in a topological order).
10720b57cec5SDimitry Andric   // Such an ordering will ensure that any load/store that may be executed
10730b57cec5SDimitry Andric   // before a second load/store will precede the second load/store in
10740b57cec5SDimitry Andric   // AccessStrideInfo.
10750b57cec5SDimitry Andric   LoopBlocksDFS DFS(TheLoop);
10760b57cec5SDimitry Andric   DFS.perform(LI);
10770b57cec5SDimitry Andric   for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
10780b57cec5SDimitry Andric     for (auto &I : *BB) {
10790b57cec5SDimitry Andric       Value *Ptr = getLoadStorePointerOperand(&I);
1080fe6060f1SDimitry Andric       if (!Ptr)
1081fe6060f1SDimitry Andric         continue;
1082fe6060f1SDimitry Andric       Type *ElementTy = getLoadStoreType(&I);
1083fe6060f1SDimitry Andric 
1084f3fd488fSDimitry Andric       // Currently, codegen doesn't support cases where the type size doesn't
1085f3fd488fSDimitry Andric       // match the alloc size. Skip them for now.
1086f3fd488fSDimitry Andric       uint64_t Size = DL.getTypeAllocSize(ElementTy);
1087f3fd488fSDimitry Andric       if (Size * 8 != DL.getTypeSizeInBits(ElementTy))
1088f3fd488fSDimitry Andric         continue;
1089f3fd488fSDimitry Andric 
10900b57cec5SDimitry Andric       // We don't check wrapping here because we don't know yet if Ptr will be
10910b57cec5SDimitry Andric       // part of a full group or a group with gaps. Checking wrapping for all
10920b57cec5SDimitry Andric       // pointers (even those that end up in groups with no gaps) will be overly
10930b57cec5SDimitry Andric       // conservative. For full groups, wrapping should be ok since if we would
10940b57cec5SDimitry Andric       // wrap around the address space we would do a memory access at nullptr
10950b57cec5SDimitry Andric       // even without the transformation. The wrapping checks are therefore
10960b57cec5SDimitry Andric       // deferred until after we've formed the interleaved groups.
1097bdd1243dSDimitry Andric       int64_t Stride =
1098bdd1243dSDimitry Andric         getPtrStride(PSE, ElementTy, Ptr, TheLoop, Strides,
1099bdd1243dSDimitry Andric                      /*Assume=*/true, /*ShouldCheckWrap=*/false).value_or(0);
11000b57cec5SDimitry Andric 
11010b57cec5SDimitry Andric       const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
11025ffd83dbSDimitry Andric       AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size,
11035ffd83dbSDimitry Andric                                               getLoadStoreAlignment(&I));
11040b57cec5SDimitry Andric     }
11050b57cec5SDimitry Andric }
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric // Analyze interleaved accesses and collect them into interleaved load and
11080b57cec5SDimitry Andric // store groups.
11090b57cec5SDimitry Andric //
11100b57cec5SDimitry Andric // When generating code for an interleaved load group, we effectively hoist all
11110b57cec5SDimitry Andric // loads in the group to the location of the first load in program order. When
11120b57cec5SDimitry Andric // generating code for an interleaved store group, we sink all stores to the
11130b57cec5SDimitry Andric // location of the last store. This code motion can change the order of load
11140b57cec5SDimitry Andric // and store instructions and may break dependences.
11150b57cec5SDimitry Andric //
11160b57cec5SDimitry Andric // The code generation strategy mentioned above ensures that we won't violate
11170b57cec5SDimitry Andric // any write-after-read (WAR) dependences.
11180b57cec5SDimitry Andric //
11190b57cec5SDimitry Andric // E.g., for the WAR dependence:  a = A[i];      // (1)
11200b57cec5SDimitry Andric //                                A[i] = b;      // (2)
11210b57cec5SDimitry Andric //
11220b57cec5SDimitry Andric // The store group of (2) is always inserted at or below (2), and the load
11230b57cec5SDimitry Andric // group of (1) is always inserted at or above (1). Thus, the instructions will
11240b57cec5SDimitry Andric // never be reordered. All other dependences are checked to ensure the
11250b57cec5SDimitry Andric // correctness of the instruction reordering.
11260b57cec5SDimitry Andric //
11270b57cec5SDimitry Andric // The algorithm visits all memory accesses in the loop in bottom-up program
11280b57cec5SDimitry Andric // order. Program order is established by traversing the blocks in the loop in
11290b57cec5SDimitry Andric // reverse postorder when collecting the accesses.
11300b57cec5SDimitry Andric //
11310b57cec5SDimitry Andric // We visit the memory accesses in bottom-up order because it can simplify the
11320b57cec5SDimitry Andric // construction of store groups in the presence of write-after-write (WAW)
11330b57cec5SDimitry Andric // dependences.
11340b57cec5SDimitry Andric //
11350b57cec5SDimitry Andric // E.g., for the WAW dependence:  A[i] = a;      // (1)
11360b57cec5SDimitry Andric //                                A[i] = b;      // (2)
11370b57cec5SDimitry Andric //                                A[i + 1] = c;  // (3)
11380b57cec5SDimitry Andric //
11390b57cec5SDimitry Andric // We will first create a store group with (3) and (2). (1) can't be added to
11400b57cec5SDimitry Andric // this group because it and (2) are dependent. However, (1) can be grouped
11410b57cec5SDimitry Andric // with other accesses that may precede it in program order. Note that a
11420b57cec5SDimitry Andric // bottom-up order does not imply that WAW dependences should not be checked.
analyzeInterleaving(bool EnablePredicatedInterleavedMemAccesses)11430b57cec5SDimitry Andric void InterleavedAccessInfo::analyzeInterleaving(
11440b57cec5SDimitry Andric                                  bool EnablePredicatedInterleavedMemAccesses) {
11450b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
114606c3fb27SDimitry Andric   const auto &Strides = LAI->getSymbolicStrides();
11470b57cec5SDimitry Andric 
11480b57cec5SDimitry Andric   // Holds all accesses with a constant stride.
11490b57cec5SDimitry Andric   MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
11500b57cec5SDimitry Andric   collectConstStrideAccesses(AccessStrideInfo, Strides);
11510b57cec5SDimitry Andric 
11520b57cec5SDimitry Andric   if (AccessStrideInfo.empty())
11530b57cec5SDimitry Andric     return;
11540b57cec5SDimitry Andric 
11550b57cec5SDimitry Andric   // Collect the dependences in the loop.
11560b57cec5SDimitry Andric   collectDependences();
11570b57cec5SDimitry Andric 
11580b57cec5SDimitry Andric   // Holds all interleaved store groups temporarily.
11590b57cec5SDimitry Andric   SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups;
11600b57cec5SDimitry Andric   // Holds all interleaved load groups temporarily.
11610b57cec5SDimitry Andric   SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups;
116206c3fb27SDimitry Andric   // Groups added to this set cannot have new members added.
116306c3fb27SDimitry Andric   SmallPtrSet<InterleaveGroup<Instruction> *, 4> CompletedLoadGroups;
11640b57cec5SDimitry Andric 
11650b57cec5SDimitry Andric   // Search in bottom-up program order for pairs of accesses (A and B) that can
11660b57cec5SDimitry Andric   // form interleaved load or store groups. In the algorithm below, access A
11670b57cec5SDimitry Andric   // precedes access B in program order. We initialize a group for B in the
11680b57cec5SDimitry Andric   // outer loop of the algorithm, and then in the inner loop, we attempt to
11690b57cec5SDimitry Andric   // insert each A into B's group if:
11700b57cec5SDimitry Andric   //
11710b57cec5SDimitry Andric   //  1. A and B have the same stride,
11720b57cec5SDimitry Andric   //  2. A and B have the same memory object size, and
11730b57cec5SDimitry Andric   //  3. A belongs in B's group according to its distance from B.
11740b57cec5SDimitry Andric   //
11750b57cec5SDimitry Andric   // Special care is taken to ensure group formation will not break any
11760b57cec5SDimitry Andric   // dependences.
11770b57cec5SDimitry Andric   for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
11780b57cec5SDimitry Andric        BI != E; ++BI) {
11790b57cec5SDimitry Andric     Instruction *B = BI->first;
11800b57cec5SDimitry Andric     StrideDescriptor DesB = BI->second;
11810b57cec5SDimitry Andric 
11820b57cec5SDimitry Andric     // Initialize a group for B if it has an allowable stride. Even if we don't
11830b57cec5SDimitry Andric     // create a group for B, we continue with the bottom-up algorithm to ensure
11840b57cec5SDimitry Andric     // we don't break any of B's dependences.
118506c3fb27SDimitry Andric     InterleaveGroup<Instruction> *GroupB = nullptr;
11860b57cec5SDimitry Andric     if (isStrided(DesB.Stride) &&
11870b57cec5SDimitry Andric         (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
118806c3fb27SDimitry Andric       GroupB = getInterleaveGroup(B);
118906c3fb27SDimitry Andric       if (!GroupB) {
11900b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
11910b57cec5SDimitry Andric                           << '\n');
119206c3fb27SDimitry Andric         GroupB = createInterleaveGroup(B, DesB.Stride, DesB.Alignment);
11930b57cec5SDimitry Andric         if (B->mayWriteToMemory())
119406c3fb27SDimitry Andric           StoreGroups.insert(GroupB);
11950b57cec5SDimitry Andric         else
119606c3fb27SDimitry Andric           LoadGroups.insert(GroupB);
11970b57cec5SDimitry Andric       }
11985f757f3fSDimitry Andric     }
11990b57cec5SDimitry Andric 
12000b57cec5SDimitry Andric     for (auto AI = std::next(BI); AI != E; ++AI) {
12010b57cec5SDimitry Andric       Instruction *A = AI->first;
12020b57cec5SDimitry Andric       StrideDescriptor DesA = AI->second;
12030b57cec5SDimitry Andric 
12040b57cec5SDimitry Andric       // Our code motion strategy implies that we can't have dependences
12050b57cec5SDimitry Andric       // between accesses in an interleaved group and other accesses located
12060b57cec5SDimitry Andric       // between the first and last member of the group. Note that this also
12070b57cec5SDimitry Andric       // means that a group can't have more than one member at a given offset.
12080b57cec5SDimitry Andric       // The accesses in a group can have dependences with other accesses, but
12090b57cec5SDimitry Andric       // we must ensure we don't extend the boundaries of the group such that
12100b57cec5SDimitry Andric       // we encompass those dependent accesses.
12110b57cec5SDimitry Andric       //
12120b57cec5SDimitry Andric       // For example, assume we have the sequence of accesses shown below in a
12130b57cec5SDimitry Andric       // stride-2 loop:
12140b57cec5SDimitry Andric       //
12150b57cec5SDimitry Andric       //  (1, 2) is a group | A[i]   = a;  // (1)
12160b57cec5SDimitry Andric       //                    | A[i-1] = b;  // (2) |
12170b57cec5SDimitry Andric       //                      A[i-3] = c;  // (3)
12180b57cec5SDimitry Andric       //                      A[i]   = d;  // (4) | (2, 4) is not a group
12190b57cec5SDimitry Andric       //
12200b57cec5SDimitry Andric       // Because accesses (2) and (3) are dependent, we can group (2) with (1)
12210b57cec5SDimitry Andric       // but not with (4). If we did, the dependent access (3) would be within
12220b57cec5SDimitry Andric       // the boundaries of the (2, 4) group.
12235f757f3fSDimitry Andric       auto DependentMember = [&](InterleaveGroup<Instruction> *Group,
12245f757f3fSDimitry Andric                                  StrideEntry *A) -> Instruction * {
12255f757f3fSDimitry Andric         for (uint32_t Index = 0; Index < Group->getFactor(); ++Index) {
12265f757f3fSDimitry Andric           Instruction *MemberOfGroupB = Group->getMember(Index);
12275f757f3fSDimitry Andric           if (MemberOfGroupB && !canReorderMemAccessesForInterleavedGroups(
12285f757f3fSDimitry Andric                                     A, &*AccessStrideInfo.find(MemberOfGroupB)))
12295f757f3fSDimitry Andric             return MemberOfGroupB;
12300b57cec5SDimitry Andric         }
12315f757f3fSDimitry Andric         return nullptr;
12325f757f3fSDimitry Andric       };
12335f757f3fSDimitry Andric 
12345f757f3fSDimitry Andric       auto GroupA = getInterleaveGroup(A);
12355f757f3fSDimitry Andric       // If A is a load, dependencies are tolerable, there's nothing to do here.
12365f757f3fSDimitry Andric       // If both A and B belong to the same (store) group, they are independent,
12375f757f3fSDimitry Andric       // even if dependencies have not been recorded.
12385f757f3fSDimitry Andric       // If both GroupA and GroupB are null, there's nothing to do here.
12395f757f3fSDimitry Andric       if (A->mayWriteToMemory() && GroupA != GroupB) {
12405f757f3fSDimitry Andric         Instruction *DependentInst = nullptr;
12415f757f3fSDimitry Andric         // If GroupB is a load group, we have to compare AI against all
12425f757f3fSDimitry Andric         // members of GroupB because if any load within GroupB has a dependency
12435f757f3fSDimitry Andric         // on AI, we need to mark GroupB as complete and also release the
12445f757f3fSDimitry Andric         // store GroupA (if A belongs to one). The former prevents incorrect
12455f757f3fSDimitry Andric         // hoisting of load B above store A while the latter prevents incorrect
12465f757f3fSDimitry Andric         // sinking of store A below load B.
12475f757f3fSDimitry Andric         if (GroupB && LoadGroups.contains(GroupB))
12485f757f3fSDimitry Andric           DependentInst = DependentMember(GroupB, &*AI);
12495f757f3fSDimitry Andric         else if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI))
12505f757f3fSDimitry Andric           DependentInst = B;
12515f757f3fSDimitry Andric 
12525f757f3fSDimitry Andric         if (DependentInst) {
12535f757f3fSDimitry Andric           // A has a store dependence on B (or on some load within GroupB) and
12545f757f3fSDimitry Andric           // is part of a store group. Release A's group to prevent illegal
12555f757f3fSDimitry Andric           // sinking of A below B. A will then be free to form another group
12565f757f3fSDimitry Andric           // with instructions that precede it.
12575f757f3fSDimitry Andric           if (GroupA && StoreGroups.contains(GroupA)) {
12585f757f3fSDimitry Andric             LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to "
12595f757f3fSDimitry Andric                                  "dependence between "
12605f757f3fSDimitry Andric                               << *A << " and " << *DependentInst << '\n');
12615f757f3fSDimitry Andric             StoreGroups.remove(GroupA);
12625f757f3fSDimitry Andric             releaseGroup(GroupA);
12635f757f3fSDimitry Andric           }
12645f757f3fSDimitry Andric           // If B is a load and part of an interleave group, no earlier loads
12655f757f3fSDimitry Andric           // can be added to B's interleave group, because this would mean the
12665f757f3fSDimitry Andric           // DependentInst would move across store A. Mark the interleave group
12675f757f3fSDimitry Andric           // as complete.
12685f757f3fSDimitry Andric           if (GroupB && LoadGroups.contains(GroupB)) {
126906c3fb27SDimitry Andric             LLVM_DEBUG(dbgs() << "LV: Marking interleave group for " << *B
127006c3fb27SDimitry Andric                               << " as complete.\n");
127106c3fb27SDimitry Andric             CompletedLoadGroups.insert(GroupB);
127206c3fb27SDimitry Andric           }
12735f757f3fSDimitry Andric         }
12745f757f3fSDimitry Andric       }
12755f757f3fSDimitry Andric       if (CompletedLoadGroups.contains(GroupB)) {
12765f757f3fSDimitry Andric         // Skip trying to add A to B, continue to look for other conflicting A's
12775f757f3fSDimitry Andric         // in groups to be released.
12785f757f3fSDimitry Andric         continue;
12790b57cec5SDimitry Andric       }
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric       // At this point, we've checked for illegal code motion. If either A or B
12820b57cec5SDimitry Andric       // isn't strided, there's nothing left to do.
12830b57cec5SDimitry Andric       if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
12840b57cec5SDimitry Andric         continue;
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric       // Ignore A if it's already in a group or isn't the same kind of memory
12870b57cec5SDimitry Andric       // operation as B.
12880b57cec5SDimitry Andric       // Note that mayReadFromMemory() isn't mutually exclusive to
12890b57cec5SDimitry Andric       // mayWriteToMemory in the case of atomic loads. We shouldn't see those
12900b57cec5SDimitry Andric       // here, canVectorizeMemory() should have returned false - except for the
12910b57cec5SDimitry Andric       // case we asked for optimization remarks.
12920b57cec5SDimitry Andric       if (isInterleaved(A) ||
12930b57cec5SDimitry Andric           (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
12940b57cec5SDimitry Andric           (A->mayWriteToMemory() != B->mayWriteToMemory()))
12950b57cec5SDimitry Andric         continue;
12960b57cec5SDimitry Andric 
12970b57cec5SDimitry Andric       // Check rules 1 and 2. Ignore A if its stride or size is different from
12980b57cec5SDimitry Andric       // that of B.
12990b57cec5SDimitry Andric       if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
13000b57cec5SDimitry Andric         continue;
13010b57cec5SDimitry Andric 
13020b57cec5SDimitry Andric       // Ignore A if the memory object of A and B don't belong to the same
13030b57cec5SDimitry Andric       // address space
13040b57cec5SDimitry Andric       if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
13050b57cec5SDimitry Andric         continue;
13060b57cec5SDimitry Andric 
13070b57cec5SDimitry Andric       // Calculate the distance from A to B.
13080b57cec5SDimitry Andric       const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
13090b57cec5SDimitry Andric           PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
13100b57cec5SDimitry Andric       if (!DistToB)
13110b57cec5SDimitry Andric         continue;
13120b57cec5SDimitry Andric       int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
13130b57cec5SDimitry Andric 
13140b57cec5SDimitry Andric       // Check rule 3. Ignore A if its distance to B is not a multiple of the
13150b57cec5SDimitry Andric       // size.
13160b57cec5SDimitry Andric       if (DistanceToB % static_cast<int64_t>(DesB.Size))
13170b57cec5SDimitry Andric         continue;
13180b57cec5SDimitry Andric 
13190b57cec5SDimitry Andric       // All members of a predicated interleave-group must have the same predicate,
13200b57cec5SDimitry Andric       // and currently must reside in the same BB.
13210b57cec5SDimitry Andric       BasicBlock *BlockA = A->getParent();
13220b57cec5SDimitry Andric       BasicBlock *BlockB = B->getParent();
13230b57cec5SDimitry Andric       if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
13240b57cec5SDimitry Andric           (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
13250b57cec5SDimitry Andric         continue;
13260b57cec5SDimitry Andric 
13270b57cec5SDimitry Andric       // The index of A is the index of B plus A's distance to B in multiples
13280b57cec5SDimitry Andric       // of the size.
13290b57cec5SDimitry Andric       int IndexA =
133006c3fb27SDimitry Andric           GroupB->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
13310b57cec5SDimitry Andric 
13320b57cec5SDimitry Andric       // Try to insert A into B's group.
133306c3fb27SDimitry Andric       if (GroupB->insertMember(A, IndexA, DesA.Alignment)) {
13340b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
13350b57cec5SDimitry Andric                           << "    into the interleave group with" << *B
13360b57cec5SDimitry Andric                           << '\n');
133706c3fb27SDimitry Andric         InterleaveGroupMap[A] = GroupB;
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric         // Set the first load in program order as the insert position.
13400b57cec5SDimitry Andric         if (A->mayReadFromMemory())
134106c3fb27SDimitry Andric           GroupB->setInsertPos(A);
13420b57cec5SDimitry Andric       }
13430b57cec5SDimitry Andric     } // Iteration over A accesses.
13440b57cec5SDimitry Andric   }   // Iteration over B accesses.
13450b57cec5SDimitry Andric 
1346349cc55cSDimitry Andric   auto InvalidateGroupIfMemberMayWrap = [&](InterleaveGroup<Instruction> *Group,
1347349cc55cSDimitry Andric                                             int Index,
1348349cc55cSDimitry Andric                                             std::string FirstOrLast) -> bool {
1349349cc55cSDimitry Andric     Instruction *Member = Group->getMember(Index);
1350349cc55cSDimitry Andric     assert(Member && "Group member does not exist");
1351349cc55cSDimitry Andric     Value *MemberPtr = getLoadStorePointerOperand(Member);
1352349cc55cSDimitry Andric     Type *AccessTy = getLoadStoreType(Member);
1353349cc55cSDimitry Andric     if (getPtrStride(PSE, AccessTy, MemberPtr, TheLoop, Strides,
1354bdd1243dSDimitry Andric                      /*Assume=*/false, /*ShouldCheckWrap=*/true).value_or(0))
1355349cc55cSDimitry Andric       return false;
1356349cc55cSDimitry Andric     LLVM_DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
1357349cc55cSDimitry Andric                       << FirstOrLast
1358349cc55cSDimitry Andric                       << " group member potentially pointer-wrapping.\n");
13590b57cec5SDimitry Andric     releaseGroup(Group);
1360349cc55cSDimitry Andric     return true;
1361349cc55cSDimitry Andric   };
1362349cc55cSDimitry Andric 
1363349cc55cSDimitry Andric   // Remove interleaved groups with gaps whose memory
13640b57cec5SDimitry Andric   // accesses may wrap around. We have to revisit the getPtrStride analysis,
13650b57cec5SDimitry Andric   // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
13660b57cec5SDimitry Andric   // not check wrapping (see documentation there).
13670b57cec5SDimitry Andric   // FORNOW we use Assume=false;
13680b57cec5SDimitry Andric   // TODO: Change to Assume=true but making sure we don't exceed the threshold
13690b57cec5SDimitry Andric   // of runtime SCEV assumptions checks (thereby potentially failing to
13700b57cec5SDimitry Andric   // vectorize altogether).
13710b57cec5SDimitry Andric   // Additional optional optimizations:
13720b57cec5SDimitry Andric   // TODO: If we are peeling the loop and we know that the first pointer doesn't
13730b57cec5SDimitry Andric   // wrap then we can deduce that all pointers in the group don't wrap.
13740b57cec5SDimitry Andric   // This means that we can forcefully peel the loop in order to only have to
13750b57cec5SDimitry Andric   // check the first pointer for no-wrap. When we'll change to use Assume=true
13760b57cec5SDimitry Andric   // we'll only need at most one runtime check per interleaved group.
13770b57cec5SDimitry Andric   for (auto *Group : LoadGroups) {
13780b57cec5SDimitry Andric     // Case 1: A full group. Can Skip the checks; For full groups, if the wide
13790b57cec5SDimitry Andric     // load would wrap around the address space we would do a memory access at
13800b57cec5SDimitry Andric     // nullptr even without the transformation.
13810b57cec5SDimitry Andric     if (Group->getNumMembers() == Group->getFactor())
13820b57cec5SDimitry Andric       continue;
13830b57cec5SDimitry Andric 
13840b57cec5SDimitry Andric     // Case 2: If first and last members of the group don't wrap this implies
13850b57cec5SDimitry Andric     // that all the pointers in the group don't wrap.
13860b57cec5SDimitry Andric     // So we check only group member 0 (which is always guaranteed to exist),
13870b57cec5SDimitry Andric     // and group member Factor - 1; If the latter doesn't exist we rely on
13880b57cec5SDimitry Andric     // peeling (if it is a non-reversed accsess -- see Case 3).
1389349cc55cSDimitry Andric     if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
13900b57cec5SDimitry Andric       continue;
1391349cc55cSDimitry Andric     if (Group->getMember(Group->getFactor() - 1))
1392349cc55cSDimitry Andric       InvalidateGroupIfMemberMayWrap(Group, Group->getFactor() - 1,
1393349cc55cSDimitry Andric                                      std::string("last"));
1394349cc55cSDimitry Andric     else {
13950b57cec5SDimitry Andric       // Case 3: A non-reversed interleaved load group with gaps: We need
13960b57cec5SDimitry Andric       // to execute at least one scalar epilogue iteration. This will ensure
13970b57cec5SDimitry Andric       // we don't speculatively access memory out-of-bounds. We only need
13980b57cec5SDimitry Andric       // to look for a member at index factor - 1, since every group must have
13990b57cec5SDimitry Andric       // a member at index zero.
14000b57cec5SDimitry Andric       if (Group->isReverse()) {
14010b57cec5SDimitry Andric         LLVM_DEBUG(
14020b57cec5SDimitry Andric             dbgs() << "LV: Invalidate candidate interleaved group due to "
14030b57cec5SDimitry Andric                       "a reverse access with gaps.\n");
14040b57cec5SDimitry Andric         releaseGroup(Group);
14050b57cec5SDimitry Andric         continue;
14060b57cec5SDimitry Andric       }
14070b57cec5SDimitry Andric       LLVM_DEBUG(
14080b57cec5SDimitry Andric           dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
14090b57cec5SDimitry Andric       RequiresScalarEpilogue = true;
14100b57cec5SDimitry Andric     }
14110b57cec5SDimitry Andric   }
1412349cc55cSDimitry Andric 
1413349cc55cSDimitry Andric   for (auto *Group : StoreGroups) {
1414349cc55cSDimitry Andric     // Case 1: A full group. Can Skip the checks; For full groups, if the wide
1415349cc55cSDimitry Andric     // store would wrap around the address space we would do a memory access at
1416349cc55cSDimitry Andric     // nullptr even without the transformation.
1417349cc55cSDimitry Andric     if (Group->getNumMembers() == Group->getFactor())
1418349cc55cSDimitry Andric       continue;
1419349cc55cSDimitry Andric 
1420349cc55cSDimitry Andric     // Interleave-store-group with gaps is implemented using masked wide store.
1421349cc55cSDimitry Andric     // Remove interleaved store groups with gaps if
1422349cc55cSDimitry Andric     // masked-interleaved-accesses are not enabled by the target.
1423349cc55cSDimitry Andric     if (!EnablePredicatedInterleavedMemAccesses) {
1424349cc55cSDimitry Andric       LLVM_DEBUG(
1425349cc55cSDimitry Andric           dbgs() << "LV: Invalidate candidate interleaved store group due "
1426349cc55cSDimitry Andric                     "to gaps.\n");
1427349cc55cSDimitry Andric       releaseGroup(Group);
1428349cc55cSDimitry Andric       continue;
1429349cc55cSDimitry Andric     }
1430349cc55cSDimitry Andric 
1431349cc55cSDimitry Andric     // Case 2: If first and last members of the group don't wrap this implies
1432349cc55cSDimitry Andric     // that all the pointers in the group don't wrap.
1433349cc55cSDimitry Andric     // So we check only group member 0 (which is always guaranteed to exist),
1434349cc55cSDimitry Andric     // and the last group member. Case 3 (scalar epilog) is not relevant for
1435349cc55cSDimitry Andric     // stores with gaps, which are implemented with masked-store (rather than
1436349cc55cSDimitry Andric     // speculative access, as in loads).
1437349cc55cSDimitry Andric     if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
1438349cc55cSDimitry Andric       continue;
1439349cc55cSDimitry Andric     for (int Index = Group->getFactor() - 1; Index > 0; Index--)
1440349cc55cSDimitry Andric       if (Group->getMember(Index)) {
1441349cc55cSDimitry Andric         InvalidateGroupIfMemberMayWrap(Group, Index, std::string("last"));
1442349cc55cSDimitry Andric         break;
1443349cc55cSDimitry Andric       }
1444349cc55cSDimitry Andric   }
14450b57cec5SDimitry Andric }
14460b57cec5SDimitry Andric 
invalidateGroupsRequiringScalarEpilogue()14470b57cec5SDimitry Andric void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
14480b57cec5SDimitry Andric   // If no group had triggered the requirement to create an epilogue loop,
14490b57cec5SDimitry Andric   // there is nothing to do.
14500b57cec5SDimitry Andric   if (!requiresScalarEpilogue())
14510b57cec5SDimitry Andric     return;
14520b57cec5SDimitry Andric 
14535ffd83dbSDimitry Andric   bool ReleasedGroup = false;
14545ffd83dbSDimitry Andric   // Release groups requiring scalar epilogues. Note that this also removes them
14555ffd83dbSDimitry Andric   // from InterleaveGroups.
14565ffd83dbSDimitry Andric   for (auto *Group : make_early_inc_range(InterleaveGroups)) {
14575ffd83dbSDimitry Andric     if (!Group->requiresScalarEpilogue())
14585ffd83dbSDimitry Andric       continue;
14590b57cec5SDimitry Andric     LLVM_DEBUG(
14600b57cec5SDimitry Andric         dbgs()
14610b57cec5SDimitry Andric         << "LV: Invalidate candidate interleaved group due to gaps that "
14620b57cec5SDimitry Andric            "require a scalar epilogue (not allowed under optsize) and cannot "
14630b57cec5SDimitry Andric            "be masked (not enabled). \n");
14645ffd83dbSDimitry Andric     releaseGroup(Group);
14655ffd83dbSDimitry Andric     ReleasedGroup = true;
14660b57cec5SDimitry Andric   }
14675ffd83dbSDimitry Andric   assert(ReleasedGroup && "At least one group must be invalidated, as a "
14685ffd83dbSDimitry Andric                           "scalar epilogue was required");
14695ffd83dbSDimitry Andric   (void)ReleasedGroup;
14700b57cec5SDimitry Andric   RequiresScalarEpilogue = false;
14710b57cec5SDimitry Andric }
14720b57cec5SDimitry Andric 
14730b57cec5SDimitry Andric template <typename InstT>
addMetadata(InstT * NewInst) const14740b57cec5SDimitry Andric void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
14750b57cec5SDimitry Andric   llvm_unreachable("addMetadata can only be used for Instruction");
14760b57cec5SDimitry Andric }
14770b57cec5SDimitry Andric 
14780b57cec5SDimitry Andric namespace llvm {
14790b57cec5SDimitry Andric template <>
addMetadata(Instruction * NewInst) const14800b57cec5SDimitry Andric void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const {
14810b57cec5SDimitry Andric   SmallVector<Value *, 4> VL;
14820b57cec5SDimitry Andric   std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
14830b57cec5SDimitry Andric                  [](std::pair<int, Instruction *> p) { return p.second; });
14840b57cec5SDimitry Andric   propagateMetadata(NewInst, VL);
14850b57cec5SDimitry Andric }
14867a6dacacSDimitry Andric } // namespace llvm
1487