1b447ac64SDavid Blaikie //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
2b447ac64SDavid Blaikie //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6b447ac64SDavid Blaikie //
7b447ac64SDavid Blaikie //===----------------------------------------------------------------------===//
8b447ac64SDavid Blaikie //
9b447ac64SDavid Blaikie // This file defines vectorizer utilities.
10b447ac64SDavid Blaikie //
11b447ac64SDavid Blaikie //===----------------------------------------------------------------------===//
12b447ac64SDavid Blaikie
136bda14b3SChandler Carruth #include "llvm/Analysis/VectorUtils.h"
1455d633bdSJames Molloy #include "llvm/ADT/EquivalenceClasses.h"
1555d633bdSJames Molloy #include "llvm/Analysis/DemandedBits.h"
169cf58c40SHal Finkel #include "llvm/Analysis/LoopInfo.h"
171086ce23SFlorian Hahn #include "llvm/Analysis/LoopIterator.h"
189cf58c40SHal Finkel #include "llvm/Analysis/ScalarEvolution.h"
196bda14b3SChandler Carruth #include "llvm/Analysis/ScalarEvolutionExpressions.h"
2055d633bdSJames Molloy #include "llvm/Analysis/TargetTransformInfo.h"
21b4b27230SDavid Majnemer #include "llvm/Analysis/ValueTracking.h"
226bda14b3SChandler Carruth #include "llvm/IR/Constants.h"
239cf58c40SHal Finkel #include "llvm/IR/GetElementPtrTypeIterator.h"
246bda14b3SChandler Carruth #include "llvm/IR/IRBuilder.h"
259cf58c40SHal Finkel #include "llvm/IR/PatternMatch.h"
269cf58c40SHal Finkel #include "llvm/IR/Value.h"
274c1a1d3cSReid Kleckner #include "llvm/Support/CommandLine.h"
283b1d3b0dSRenato Golin
291086ce23SFlorian Hahn #define DEBUG_TYPE "vectorutils"
301086ce23SFlorian Hahn
315eaf08ffSDavid Majnemer using namespace llvm;
325eaf08ffSDavid Majnemer using namespace llvm::PatternMatch;
33b447ac64SDavid Blaikie
341086ce23SFlorian Hahn /// Maximum factor for an interleaved memory access.
351086ce23SFlorian Hahn static cl::opt<unsigned> MaxInterleaveGroupFactor(
361086ce23SFlorian Hahn "max-interleave-group-factor", cl::Hidden,
371086ce23SFlorian Hahn cl::desc("Maximum factor for an interleaved access group (default = 8)"),
381086ce23SFlorian Hahn cl::init(8));
391086ce23SFlorian Hahn
400f4f4806SSanjay Patel /// Return true if all of the intrinsic's arguments and return type are scalars
41512b1187SBjorn Pettersson /// for the scalar form of the intrinsic, and vectors for the vector form of the
42512b1187SBjorn Pettersson /// intrinsic (except operands that are marked as always being scalar by
436f81903eSDavid Green /// isVectorIntrinsicWithScalarOpAtArg).
isTriviallyVectorizable(Intrinsic::ID ID)44b447ac64SDavid Blaikie bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
45b447ac64SDavid Blaikie switch (ID) {
463efc978bSCraig Topper case Intrinsic::abs: // Begin integer bit-manipulation.
473efc978bSCraig Topper case Intrinsic::bswap:
480f4f4806SSanjay Patel case Intrinsic::bitreverse:
490f4f4806SSanjay Patel case Intrinsic::ctpop:
500f4f4806SSanjay Patel case Intrinsic::ctlz:
510f4f4806SSanjay Patel case Intrinsic::cttz:
521456fd76SSanjay Patel case Intrinsic::fshl:
531456fd76SSanjay Patel case Intrinsic::fshr:
543efc978bSCraig Topper case Intrinsic::smax:
553efc978bSCraig Topper case Intrinsic::smin:
563efc978bSCraig Topper case Intrinsic::umax:
573efc978bSCraig Topper case Intrinsic::umin:
580e08b6f0SSimon Pilgrim case Intrinsic::sadd_sat:
590e08b6f0SSimon Pilgrim case Intrinsic::ssub_sat:
600e08b6f0SSimon Pilgrim case Intrinsic::uadd_sat:
610e08b6f0SSimon Pilgrim case Intrinsic::usub_sat:
62a066f1f9SSimon Pilgrim case Intrinsic::smul_fix:
63512b1187SBjorn Pettersson case Intrinsic::smul_fix_sat:
64a066f1f9SSimon Pilgrim case Intrinsic::umul_fix:
655e331e4cSBjorn Pettersson case Intrinsic::umul_fix_sat:
660f4f4806SSanjay Patel case Intrinsic::sqrt: // Begin floating-point.
67b447ac64SDavid Blaikie case Intrinsic::sin:
68b447ac64SDavid Blaikie case Intrinsic::cos:
69b447ac64SDavid Blaikie case Intrinsic::exp:
70b447ac64SDavid Blaikie case Intrinsic::exp2:
71b447ac64SDavid Blaikie case Intrinsic::log:
72b447ac64SDavid Blaikie case Intrinsic::log10:
73b447ac64SDavid Blaikie case Intrinsic::log2:
74b447ac64SDavid Blaikie case Intrinsic::fabs:
75b447ac64SDavid Blaikie case Intrinsic::minnum:
76b447ac64SDavid Blaikie case Intrinsic::maxnum:
778a91cf1cSThomas Lively case Intrinsic::minimum:
788a91cf1cSThomas Lively case Intrinsic::maximum:
79b447ac64SDavid Blaikie case Intrinsic::copysign:
80b447ac64SDavid Blaikie case Intrinsic::floor:
81b447ac64SDavid Blaikie case Intrinsic::ceil:
82b447ac64SDavid Blaikie case Intrinsic::trunc:
83b447ac64SDavid Blaikie case Intrinsic::rint:
84b447ac64SDavid Blaikie case Intrinsic::nearbyint:
85b447ac64SDavid Blaikie case Intrinsic::round:
864d20e31fSSerge Pavlov case Intrinsic::roundeven:
87b447ac64SDavid Blaikie case Intrinsic::pow:
88b447ac64SDavid Blaikie case Intrinsic::fma:
89b447ac64SDavid Blaikie case Intrinsic::fmuladd:
90b447ac64SDavid Blaikie case Intrinsic::powi:
9180ea6dd1SMatt Arsenault case Intrinsic::canonicalize:
926f81903eSDavid Green case Intrinsic::fptosi_sat:
936f81903eSDavid Green case Intrinsic::fptoui_sat:
94b447ac64SDavid Blaikie return true;
95b447ac64SDavid Blaikie default:
96b447ac64SDavid Blaikie return false;
97b447ac64SDavid Blaikie }
98b447ac64SDavid Blaikie }
99b447ac64SDavid Blaikie
100512b1187SBjorn Pettersson /// Identifies if the vector form of the intrinsic has a scalar operand.
isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID,unsigned ScalarOpdIdx)1016f81903eSDavid Green bool llvm::isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID,
102b447ac64SDavid Blaikie unsigned ScalarOpdIdx) {
103b447ac64SDavid Blaikie switch (ID) {
1043efc978bSCraig Topper case Intrinsic::abs:
105b447ac64SDavid Blaikie case Intrinsic::ctlz:
106b447ac64SDavid Blaikie case Intrinsic::cttz:
107b447ac64SDavid Blaikie case Intrinsic::powi:
108b447ac64SDavid Blaikie return (ScalarOpdIdx == 1);
109a066f1f9SSimon Pilgrim case Intrinsic::smul_fix:
110512b1187SBjorn Pettersson case Intrinsic::smul_fix_sat:
111a066f1f9SSimon Pilgrim case Intrinsic::umul_fix:
1125e331e4cSBjorn Pettersson case Intrinsic::umul_fix_sat:
113a066f1f9SSimon Pilgrim return (ScalarOpdIdx == 2);
114b447ac64SDavid Blaikie default:
115b447ac64SDavid Blaikie return false;
116b447ac64SDavid Blaikie }
117b447ac64SDavid Blaikie }
118b447ac64SDavid Blaikie
isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID,unsigned OpdIdx)1196f81903eSDavid Green bool llvm::isVectorIntrinsicWithOverloadTypeAtArg(Intrinsic::ID ID,
1206f81903eSDavid Green unsigned OpdIdx) {
1214c7f820bSBjorn Pettersson switch (ID) {
1226f81903eSDavid Green case Intrinsic::fptosi_sat:
1236f81903eSDavid Green case Intrinsic::fptoui_sat:
1246f81903eSDavid Green return OpdIdx == 0;
1254c7f820bSBjorn Pettersson case Intrinsic::powi:
1266f81903eSDavid Green return OpdIdx == 1;
1274c7f820bSBjorn Pettersson default:
1284c7f820bSBjorn Pettersson return false;
1294c7f820bSBjorn Pettersson }
1304c7f820bSBjorn Pettersson }
1314c7f820bSBjorn Pettersson
1325f8f34e4SAdrian Prantl /// Returns intrinsic ID for call.
133b447ac64SDavid Blaikie /// For the input call instruction it finds mapping intrinsic and returns
134b447ac64SDavid Blaikie /// its ID, in case it does not found it return not_intrinsic.
getVectorIntrinsicIDForCall(const CallInst * CI,const TargetLibraryInfo * TLI)135b4b27230SDavid Majnemer Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI,
136b447ac64SDavid Blaikie const TargetLibraryInfo *TLI) {
137be04aba6SCraig Topper Intrinsic::ID ID = getIntrinsicForCallSite(*CI, TLI);
138b4b27230SDavid Majnemer if (ID == Intrinsic::not_intrinsic)
139b4b27230SDavid Majnemer return Intrinsic::not_intrinsic;
140b4b27230SDavid Majnemer
141b447ac64SDavid Blaikie if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
1422c74fe97SDan Gohman ID == Intrinsic::lifetime_end || ID == Intrinsic::assume ||
143121cac01SJeroen Dobbelaere ID == Intrinsic::experimental_noalias_scope_decl ||
144f3c44569SHongtao Yu ID == Intrinsic::sideeffect || ID == Intrinsic::pseudoprobe)
145b447ac64SDavid Blaikie return ID;
146b447ac64SDavid Blaikie return Intrinsic::not_intrinsic;
147b447ac64SDavid Blaikie }
148b447ac64SDavid Blaikie
1495f8f34e4SAdrian Prantl /// Find the operand of the GEP that should be checked for consecutive
1509cf58c40SHal Finkel /// stores. This ignores trailing indices that have no effect on the final
1519cf58c40SHal Finkel /// pointer.
getGEPInductionOperand(const GetElementPtrInst * Gep)1529cf58c40SHal Finkel unsigned llvm::getGEPInductionOperand(const GetElementPtrInst *Gep) {
1539cf58c40SHal Finkel const DataLayout &DL = Gep->getModule()->getDataLayout();
1549cf58c40SHal Finkel unsigned LastOperand = Gep->getNumOperands() - 1;
155bf60bb26SJoe Ellis TypeSize GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
1569cf58c40SHal Finkel
1579cf58c40SHal Finkel // Walk backwards and try to peel off zeros.
1585eaf08ffSDavid Majnemer while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
1599cf58c40SHal Finkel // Find the type we're currently indexing into.
1609cf58c40SHal Finkel gep_type_iterator GEPTI = gep_type_begin(Gep);
161ab85225bSPeter Collingbourne std::advance(GEPTI, LastOperand - 2);
1629cf58c40SHal Finkel
1639cf58c40SHal Finkel // If it's a type with the same allocation size as the result of the GEP we
1649cf58c40SHal Finkel // can peel off the zero index.
165ab85225bSPeter Collingbourne if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize)
1669cf58c40SHal Finkel break;
1679cf58c40SHal Finkel --LastOperand;
1689cf58c40SHal Finkel }
1699cf58c40SHal Finkel
1709cf58c40SHal Finkel return LastOperand;
1719cf58c40SHal Finkel }
1729cf58c40SHal Finkel
1735f8f34e4SAdrian Prantl /// If the argument is a GEP, then returns the operand identified by
1749cf58c40SHal Finkel /// getGEPInductionOperand. However, if there is some other non-loop-invariant
1759cf58c40SHal Finkel /// operand, it returns that instead.
stripGetElementPtr(Value * Ptr,ScalarEvolution * SE,Loop * Lp)1765eaf08ffSDavid Majnemer Value *llvm::stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
1779cf58c40SHal Finkel GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
1789cf58c40SHal Finkel if (!GEP)
1799cf58c40SHal Finkel return Ptr;
1809cf58c40SHal Finkel
1819cf58c40SHal Finkel unsigned InductionOperand = getGEPInductionOperand(GEP);
1829cf58c40SHal Finkel
1839cf58c40SHal Finkel // Check that all of the gep indices are uniform except for our induction
1849cf58c40SHal Finkel // operand.
1859cf58c40SHal Finkel for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
1869cf58c40SHal Finkel if (i != InductionOperand &&
1879cf58c40SHal Finkel !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
1889cf58c40SHal Finkel return Ptr;
1899cf58c40SHal Finkel return GEP->getOperand(InductionOperand);
1909cf58c40SHal Finkel }
1919cf58c40SHal Finkel
1925f8f34e4SAdrian Prantl /// If a value has only one user that is a CastInst, return it.
getUniqueCastUse(Value * Ptr,Loop * Lp,Type * Ty)1935eaf08ffSDavid Majnemer Value *llvm::getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
1945eaf08ffSDavid Majnemer Value *UniqueCast = nullptr;
1959cf58c40SHal Finkel for (User *U : Ptr->users()) {
1969cf58c40SHal Finkel CastInst *CI = dyn_cast<CastInst>(U);
1979cf58c40SHal Finkel if (CI && CI->getType() == Ty) {
1989cf58c40SHal Finkel if (!UniqueCast)
1999cf58c40SHal Finkel UniqueCast = CI;
2009cf58c40SHal Finkel else
2019cf58c40SHal Finkel return nullptr;
2029cf58c40SHal Finkel }
2039cf58c40SHal Finkel }
2049cf58c40SHal Finkel return UniqueCast;
2059cf58c40SHal Finkel }
2069cf58c40SHal Finkel
2075f8f34e4SAdrian Prantl /// Get the stride of a pointer access in a loop. Looks for symbolic
2089cf58c40SHal Finkel /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
getStrideFromPointer(Value * Ptr,ScalarEvolution * SE,Loop * Lp)2095eaf08ffSDavid Majnemer Value *llvm::getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
210e3dcce97SCraig Topper auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
2119cf58c40SHal Finkel if (!PtrTy || PtrTy->isAggregateType())
2129cf58c40SHal Finkel return nullptr;
2139cf58c40SHal Finkel
2149cf58c40SHal Finkel // Try to remove a gep instruction to make the pointer (actually index at this
215d319674aSVedant Kumar // point) easier analyzable. If OrigPtr is equal to Ptr we are analyzing the
2169cf58c40SHal Finkel // pointer, otherwise, we are analyzing the index.
2175eaf08ffSDavid Majnemer Value *OrigPtr = Ptr;
2189cf58c40SHal Finkel
2199cf58c40SHal Finkel // The size of the pointer access.
2209cf58c40SHal Finkel int64_t PtrAccessSize = 1;
2219cf58c40SHal Finkel
2229cf58c40SHal Finkel Ptr = stripGetElementPtr(Ptr, SE, Lp);
2239cf58c40SHal Finkel const SCEV *V = SE->getSCEV(Ptr);
2249cf58c40SHal Finkel
2259cf58c40SHal Finkel if (Ptr != OrigPtr)
2269cf58c40SHal Finkel // Strip off casts.
227d083d55cSRoman Lebedev while (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V))
2289cf58c40SHal Finkel V = C->getOperand();
2299cf58c40SHal Finkel
2309cf58c40SHal Finkel const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
2319cf58c40SHal Finkel if (!S)
2329cf58c40SHal Finkel return nullptr;
2339cf58c40SHal Finkel
2349cf58c40SHal Finkel V = S->getStepRecurrence(*SE);
2359cf58c40SHal Finkel if (!V)
2369cf58c40SHal Finkel return nullptr;
2379cf58c40SHal Finkel
2389cf58c40SHal Finkel // Strip off the size of access multiplication if we are still analyzing the
2399cf58c40SHal Finkel // pointer.
2409cf58c40SHal Finkel if (OrigPtr == Ptr) {
2419cf58c40SHal Finkel if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
2429cf58c40SHal Finkel if (M->getOperand(0)->getSCEVType() != scConstant)
2439cf58c40SHal Finkel return nullptr;
2449cf58c40SHal Finkel
2450de2feceSSanjoy Das const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
2469cf58c40SHal Finkel
2479cf58c40SHal Finkel // Huge step value - give up.
2489cf58c40SHal Finkel if (APStepVal.getBitWidth() > 64)
2499cf58c40SHal Finkel return nullptr;
2509cf58c40SHal Finkel
2519cf58c40SHal Finkel int64_t StepVal = APStepVal.getSExtValue();
2529cf58c40SHal Finkel if (PtrAccessSize != StepVal)
2539cf58c40SHal Finkel return nullptr;
2549cf58c40SHal Finkel V = M->getOperand(1);
2559cf58c40SHal Finkel }
2569cf58c40SHal Finkel }
2579cf58c40SHal Finkel
2589cf58c40SHal Finkel // Strip off casts.
2599cf58c40SHal Finkel Type *StripedOffRecurrenceCast = nullptr;
260d083d55cSRoman Lebedev if (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(V)) {
2619cf58c40SHal Finkel StripedOffRecurrenceCast = C->getType();
2629cf58c40SHal Finkel V = C->getOperand();
2639cf58c40SHal Finkel }
2649cf58c40SHal Finkel
2659cf58c40SHal Finkel // Look for the loop invariant symbolic value.
2669cf58c40SHal Finkel const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
2679cf58c40SHal Finkel if (!U)
2689cf58c40SHal Finkel return nullptr;
2699cf58c40SHal Finkel
2705eaf08ffSDavid Majnemer Value *Stride = U->getValue();
2719cf58c40SHal Finkel if (!Lp->isLoopInvariant(Stride))
2729cf58c40SHal Finkel return nullptr;
2739cf58c40SHal Finkel
2749cf58c40SHal Finkel // If we have stripped off the recurrence cast we have to make sure that we
2759cf58c40SHal Finkel // return the value that is used in this loop so that we can replace it later.
2769cf58c40SHal Finkel if (StripedOffRecurrenceCast)
2779cf58c40SHal Finkel Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
2789cf58c40SHal Finkel
2799cf58c40SHal Finkel return Stride;
2809cf58c40SHal Finkel }
281599ca442SDavid Majnemer
2825f8f34e4SAdrian Prantl /// Given a vector and an element number, see if the scalar value is
283599ca442SDavid Majnemer /// already around as a register, for example if it were inserted then extracted
284599ca442SDavid Majnemer /// from the vector.
findScalarElement(Value * V,unsigned EltNo)2855eaf08ffSDavid Majnemer Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
286599ca442SDavid Majnemer assert(V->getType()->isVectorTy() && "Not looking at a vector?");
287599ca442SDavid Majnemer VectorType *VTy = cast<VectorType>(V->getType());
2888f525739SHuihui Zhang // For fixed-length vector, return undef for out of range access.
2899174e022SChristopher Tetreault if (auto *FVTy = dyn_cast<FixedVectorType>(VTy)) {
2909174e022SChristopher Tetreault unsigned Width = FVTy->getNumElements();
2918f525739SHuihui Zhang if (EltNo >= Width)
2929174e022SChristopher Tetreault return UndefValue::get(FVTy->getElementType());
2938f525739SHuihui Zhang }
294599ca442SDavid Majnemer
295599ca442SDavid Majnemer if (Constant *C = dyn_cast<Constant>(V))
296599ca442SDavid Majnemer return C->getAggregateElement(EltNo);
297599ca442SDavid Majnemer
298599ca442SDavid Majnemer if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
299599ca442SDavid Majnemer // If this is an insert to a variable element, we don't know what it is.
300599ca442SDavid Majnemer if (!isa<ConstantInt>(III->getOperand(2)))
301599ca442SDavid Majnemer return nullptr;
302599ca442SDavid Majnemer unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
303599ca442SDavid Majnemer
304599ca442SDavid Majnemer // If this is an insert to the element we are looking for, return the
305599ca442SDavid Majnemer // inserted value.
306599ca442SDavid Majnemer if (EltNo == IIElt)
307599ca442SDavid Majnemer return III->getOperand(1);
308599ca442SDavid Majnemer
3099d6d24c2SSanjay Patel // Guard against infinite loop on malformed, unreachable IR.
3109d6d24c2SSanjay Patel if (III == III->getOperand(0))
3119d6d24c2SSanjay Patel return nullptr;
3129d6d24c2SSanjay Patel
313599ca442SDavid Majnemer // Otherwise, the insertelement doesn't modify the value, recurse on its
314599ca442SDavid Majnemer // vector input.
315599ca442SDavid Majnemer return findScalarElement(III->getOperand(0), EltNo);
316599ca442SDavid Majnemer }
317599ca442SDavid Majnemer
3181ec0cc0fSHuihui Zhang ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V);
3191ec0cc0fSHuihui Zhang // Restrict the following transformation to fixed-length vector.
3201ec0cc0fSHuihui Zhang if (SVI && isa<FixedVectorType>(SVI->getType())) {
321b96558f5SChristopher Tetreault unsigned LHSWidth =
3221ec0cc0fSHuihui Zhang cast<FixedVectorType>(SVI->getOperand(0)->getType())->getNumElements();
323599ca442SDavid Majnemer int InEl = SVI->getMaskValue(EltNo);
324599ca442SDavid Majnemer if (InEl < 0)
325599ca442SDavid Majnemer return UndefValue::get(VTy->getElementType());
326599ca442SDavid Majnemer if (InEl < (int)LHSWidth)
327599ca442SDavid Majnemer return findScalarElement(SVI->getOperand(0), InEl);
328599ca442SDavid Majnemer return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
329599ca442SDavid Majnemer }
330599ca442SDavid Majnemer
331599ca442SDavid Majnemer // Extract a value from a vector add operation with a constant zero.
3323413a66cSSanjay Patel // TODO: Use getBinOpIdentity() to generalize this.
3333413a66cSSanjay Patel Value *Val; Constant *C;
3343413a66cSSanjay Patel if (match(V, m_Add(m_Value(Val), m_Constant(C))))
3353413a66cSSanjay Patel if (Constant *Elt = C->getAggregateElement(EltNo))
336c6bb0e2aSDavid Majnemer if (Elt->isNullValue())
337599ca442SDavid Majnemer return findScalarElement(Val, EltNo);
338599ca442SDavid Majnemer
33996f6785bSSander de Smalen // If the vector is a splat then we can trivially find the scalar element.
34096f6785bSSander de Smalen if (isa<ScalableVectorType>(VTy))
34196f6785bSSander de Smalen if (Value *Splat = getSplatValue(V))
34296f6785bSSander de Smalen if (EltNo < VTy->getElementCount().getKnownMinValue())
34396f6785bSSander de Smalen return Splat;
34496f6785bSSander de Smalen
345599ca442SDavid Majnemer // Otherwise, we don't know.
346599ca442SDavid Majnemer return nullptr;
347599ca442SDavid Majnemer }
3483b1d3b0dSRenato Golin
getSplatIndex(ArrayRef<int> Mask)349686a038eSSanjay Patel int llvm::getSplatIndex(ArrayRef<int> Mask) {
350686a038eSSanjay Patel int SplatIndex = -1;
351686a038eSSanjay Patel for (int M : Mask) {
352686a038eSSanjay Patel // Ignore invalid (undefined) mask elements.
353686a038eSSanjay Patel if (M < 0)
354686a038eSSanjay Patel continue;
355686a038eSSanjay Patel
356686a038eSSanjay Patel // There can be only 1 non-negative mask element value if this is a splat.
357686a038eSSanjay Patel if (SplatIndex != -1 && SplatIndex != M)
358686a038eSSanjay Patel return -1;
359686a038eSSanjay Patel
360686a038eSSanjay Patel // Initialize the splat index to the 1st non-negative mask element.
361686a038eSSanjay Patel SplatIndex = M;
362686a038eSSanjay Patel }
363686a038eSSanjay Patel assert((SplatIndex == -1 || SplatIndex >= 0) && "Negative index?");
364686a038eSSanjay Patel return SplatIndex;
365686a038eSSanjay Patel }
366686a038eSSanjay Patel
3675f8f34e4SAdrian Prantl /// Get splat value if the input is a splat vector or return nullptr.
36863a7ca99SElena Demikhovsky /// This function is not fully general. It checks only 2 cases:
369e490e4a0SSanjay Patel /// the input value is (1) a splat constant vector or (2) a sequence
370e490e4a0SSanjay Patel /// of instructions that broadcasts a scalar at element 0.
getSplatValue(const Value * V)371b16e8687SCraig Topper Value *llvm::getSplatValue(const Value *V) {
37247fa271aSElena Demikhovsky if (isa<VectorType>(V->getType()))
373e490e4a0SSanjay Patel if (auto *C = dyn_cast<Constant>(V))
3740781d7b2SElena Demikhovsky return C->getSplatValue();
37563a7ca99SElena Demikhovsky
376e490e4a0SSanjay Patel // shuf (inselt ?, Splat, 0), ?, <0, undef, 0, ...>
377e490e4a0SSanjay Patel Value *Splat;
3787eed772aSSanjay Patel if (match(V,
3797eed772aSSanjay Patel m_Shuffle(m_InsertElt(m_Value(), m_Value(Splat), m_ZeroInt()),
3801ee6ec2bSEli Friedman m_Value(), m_ZeroMask())))
381e490e4a0SSanjay Patel return Splat;
3823b1d3b0dSRenato Golin
383e490e4a0SSanjay Patel return nullptr;
3843b1d3b0dSRenato Golin }
38555d633bdSJames Molloy
isSplatValue(const Value * V,int Index,unsigned Depth)3869b9e2da0SSanjay Patel bool llvm::isSplatValue(const Value *V, int Index, unsigned Depth) {
3876f3511a0SSanjay Patel assert(Depth <= MaxAnalysisRecursionDepth && "Limit Search Depth");
38840e3bdf8SSanjay Patel
38940e3bdf8SSanjay Patel if (isa<VectorType>(V->getType())) {
39040e3bdf8SSanjay Patel if (isa<UndefValue>(V))
39140e3bdf8SSanjay Patel return true;
3929b9e2da0SSanjay Patel // FIXME: We can allow undefs, but if Index was specified, we may want to
3939b9e2da0SSanjay Patel // check that the constant is defined at that index.
39440e3bdf8SSanjay Patel if (auto *C = dyn_cast<Constant>(V))
39540e3bdf8SSanjay Patel return C->getSplatValue() != nullptr;
39640e3bdf8SSanjay Patel }
39740e3bdf8SSanjay Patel
3989b9e2da0SSanjay Patel if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V)) {
3999b9e2da0SSanjay Patel // FIXME: We can safely allow undefs here. If Index was specified, we will
4009b9e2da0SSanjay Patel // check that the mask elt is defined at the required index.
4011ee6ec2bSEli Friedman if (!is_splat(Shuf->getShuffleMask()))
4029b9e2da0SSanjay Patel return false;
4039b9e2da0SSanjay Patel
4049b9e2da0SSanjay Patel // Match any index.
4059b9e2da0SSanjay Patel if (Index == -1)
4069b9e2da0SSanjay Patel return true;
4079b9e2da0SSanjay Patel
4089b9e2da0SSanjay Patel // Match a specific element. The mask should be defined at and match the
4099b9e2da0SSanjay Patel // specified index.
4109b9e2da0SSanjay Patel return Shuf->getMaskValue(Index) == Index;
4119b9e2da0SSanjay Patel }
41240e3bdf8SSanjay Patel
41340e3bdf8SSanjay Patel // The remaining tests are all recursive, so bail out if we hit the limit.
4146f3511a0SSanjay Patel if (Depth++ == MaxAnalysisRecursionDepth)
41540e3bdf8SSanjay Patel return false;
41640e3bdf8SSanjay Patel
41740e3bdf8SSanjay Patel // If both operands of a binop are splats, the result is a splat.
41840e3bdf8SSanjay Patel Value *X, *Y, *Z;
41940e3bdf8SSanjay Patel if (match(V, m_BinOp(m_Value(X), m_Value(Y))))
4209b9e2da0SSanjay Patel return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth);
42140e3bdf8SSanjay Patel
42240e3bdf8SSanjay Patel // If all operands of a select are splats, the result is a splat.
42340e3bdf8SSanjay Patel if (match(V, m_Select(m_Value(X), m_Value(Y), m_Value(Z))))
4249b9e2da0SSanjay Patel return isSplatValue(X, Index, Depth) && isSplatValue(Y, Index, Depth) &&
4259b9e2da0SSanjay Patel isSplatValue(Z, Index, Depth);
42640e3bdf8SSanjay Patel
42740e3bdf8SSanjay Patel // TODO: Add support for unary ops (fneg), casts, intrinsics (overflow ops).
42840e3bdf8SSanjay Patel
42940e3bdf8SSanjay Patel return false;
43040e3bdf8SSanjay Patel }
43140e3bdf8SSanjay Patel
narrowShuffleMaskElts(int Scale,ArrayRef<int> Mask,SmallVectorImpl<int> & ScaledMask)4321318ddbcSSanjay Patel void llvm::narrowShuffleMaskElts(int Scale, ArrayRef<int> Mask,
433f92563f9SCraig Topper SmallVectorImpl<int> &ScaledMask) {
434f92563f9SCraig Topper assert(Scale > 0 && "Unexpected scaling factor");
435f92563f9SCraig Topper
436f92563f9SCraig Topper // Fast-path: if no scaling, then it is just a copy.
437f92563f9SCraig Topper if (Scale == 1) {
438f92563f9SCraig Topper ScaledMask.assign(Mask.begin(), Mask.end());
439f92563f9SCraig Topper return;
440f92563f9SCraig Topper }
441f92563f9SCraig Topper
442f92563f9SCraig Topper ScaledMask.clear();
4431318ddbcSSanjay Patel for (int MaskElt : Mask) {
4441318ddbcSSanjay Patel if (MaskElt >= 0) {
44548b510c4SSimon Pilgrim assert(((uint64_t)Scale * MaskElt + (Scale - 1)) <= INT32_MAX &&
4461318ddbcSSanjay Patel "Overflowed 32-bits");
4471318ddbcSSanjay Patel }
4481318ddbcSSanjay Patel for (int SliceElt = 0; SliceElt != Scale; ++SliceElt)
4491318ddbcSSanjay Patel ScaledMask.push_back(MaskElt < 0 ? MaskElt : Scale * MaskElt + SliceElt);
4501318ddbcSSanjay Patel }
451f92563f9SCraig Topper }
452f92563f9SCraig Topper
widenShuffleMaskElts(int Scale,ArrayRef<int> Mask,SmallVectorImpl<int> & ScaledMask)453c23cbefdSSanjay Patel bool llvm::widenShuffleMaskElts(int Scale, ArrayRef<int> Mask,
454c23cbefdSSanjay Patel SmallVectorImpl<int> &ScaledMask) {
455c23cbefdSSanjay Patel assert(Scale > 0 && "Unexpected scaling factor");
456c23cbefdSSanjay Patel
457c23cbefdSSanjay Patel // Fast-path: if no scaling, then it is just a copy.
458c23cbefdSSanjay Patel if (Scale == 1) {
459c23cbefdSSanjay Patel ScaledMask.assign(Mask.begin(), Mask.end());
460c23cbefdSSanjay Patel return true;
461c23cbefdSSanjay Patel }
462c23cbefdSSanjay Patel
463c23cbefdSSanjay Patel // We must map the original elements down evenly to a type with less elements.
464c23cbefdSSanjay Patel int NumElts = Mask.size();
465c23cbefdSSanjay Patel if (NumElts % Scale != 0)
466c23cbefdSSanjay Patel return false;
467c23cbefdSSanjay Patel
468c23cbefdSSanjay Patel ScaledMask.clear();
469c23cbefdSSanjay Patel ScaledMask.reserve(NumElts / Scale);
470c23cbefdSSanjay Patel
471c23cbefdSSanjay Patel // Step through the input mask by splitting into Scale-sized slices.
472c23cbefdSSanjay Patel do {
473c23cbefdSSanjay Patel ArrayRef<int> MaskSlice = Mask.take_front(Scale);
474c23cbefdSSanjay Patel assert((int)MaskSlice.size() == Scale && "Expected Scale-sized slice.");
475c23cbefdSSanjay Patel
476c23cbefdSSanjay Patel // The first element of the slice determines how we evaluate this slice.
477c23cbefdSSanjay Patel int SliceFront = MaskSlice.front();
478c23cbefdSSanjay Patel if (SliceFront < 0) {
479c23cbefdSSanjay Patel // Negative values (undef or other "sentinel" values) must be equal across
480c23cbefdSSanjay Patel // the entire slice.
481c23cbefdSSanjay Patel if (!is_splat(MaskSlice))
482c23cbefdSSanjay Patel return false;
483c23cbefdSSanjay Patel ScaledMask.push_back(SliceFront);
484c23cbefdSSanjay Patel } else {
485c23cbefdSSanjay Patel // A positive mask element must be cleanly divisible.
486c23cbefdSSanjay Patel if (SliceFront % Scale != 0)
487c23cbefdSSanjay Patel return false;
488c23cbefdSSanjay Patel // Elements of the slice must be consecutive.
489c23cbefdSSanjay Patel for (int i = 1; i < Scale; ++i)
490c23cbefdSSanjay Patel if (MaskSlice[i] != SliceFront + i)
491c23cbefdSSanjay Patel return false;
492c23cbefdSSanjay Patel ScaledMask.push_back(SliceFront / Scale);
493c23cbefdSSanjay Patel }
494c23cbefdSSanjay Patel Mask = Mask.drop_front(Scale);
495c23cbefdSSanjay Patel } while (!Mask.empty());
496c23cbefdSSanjay Patel
497c23cbefdSSanjay Patel assert((int)ScaledMask.size() * Scale == NumElts && "Unexpected scaled mask");
498c23cbefdSSanjay Patel
499c23cbefdSSanjay Patel // All elements of the original mask can be scaled down to map to the elements
500c23cbefdSSanjay Patel // of a mask with wider elements.
501c23cbefdSSanjay Patel return true;
502c23cbefdSSanjay Patel }
503c23cbefdSSanjay Patel
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)5042cca53c8SAlexey Bataev void llvm::processShuffleMasks(
5052cca53c8SAlexey Bataev ArrayRef<int> Mask, unsigned NumOfSrcRegs, unsigned NumOfDestRegs,
5062cca53c8SAlexey Bataev unsigned NumOfUsedRegs, function_ref<void()> NoInputAction,
50775e1cf4aSAlexey Bataev function_ref<void(ArrayRef<int>, unsigned, unsigned)> SingleInputAction,
5082cca53c8SAlexey Bataev function_ref<void(ArrayRef<int>, unsigned, unsigned)> ManyInputsAction) {
5092cca53c8SAlexey Bataev SmallVector<SmallVector<SmallVector<int>>> Res(NumOfDestRegs);
5102cca53c8SAlexey Bataev // Try to perform better estimation of the permutation.
5112cca53c8SAlexey Bataev // 1. Split the source/destination vectors into real registers.
5122cca53c8SAlexey Bataev // 2. Do the mask analysis to identify which real registers are
5132cca53c8SAlexey Bataev // permuted.
5142cca53c8SAlexey Bataev int Sz = Mask.size();
5152cca53c8SAlexey Bataev unsigned SzDest = Sz / NumOfDestRegs;
5162cca53c8SAlexey Bataev unsigned SzSrc = Sz / NumOfSrcRegs;
5172cca53c8SAlexey Bataev for (unsigned I = 0; I < NumOfDestRegs; ++I) {
5182cca53c8SAlexey Bataev auto &RegMasks = Res[I];
5192cca53c8SAlexey Bataev RegMasks.assign(NumOfSrcRegs, {});
5202cca53c8SAlexey Bataev // Check that the values in dest registers are in the one src
5212cca53c8SAlexey Bataev // register.
5222cca53c8SAlexey Bataev for (unsigned K = 0; K < SzDest; ++K) {
5232cca53c8SAlexey Bataev int Idx = I * SzDest + K;
5242cca53c8SAlexey Bataev if (Idx == Sz)
5252cca53c8SAlexey Bataev break;
5262cca53c8SAlexey Bataev if (Mask[Idx] >= Sz || Mask[Idx] == UndefMaskElem)
5272cca53c8SAlexey Bataev continue;
5282cca53c8SAlexey Bataev int SrcRegIdx = Mask[Idx] / SzSrc;
5292cca53c8SAlexey Bataev // Add a cost of PermuteTwoSrc for each new source register permute,
5302cca53c8SAlexey Bataev // if we have more than one source registers.
5312cca53c8SAlexey Bataev if (RegMasks[SrcRegIdx].empty())
5322cca53c8SAlexey Bataev RegMasks[SrcRegIdx].assign(SzDest, UndefMaskElem);
5332cca53c8SAlexey Bataev RegMasks[SrcRegIdx][K] = Mask[Idx] % SzSrc;
5342cca53c8SAlexey Bataev }
5352cca53c8SAlexey Bataev }
5362cca53c8SAlexey Bataev // Process split mask.
5372cca53c8SAlexey Bataev for (unsigned I = 0; I < NumOfUsedRegs; ++I) {
5382cca53c8SAlexey Bataev auto &Dest = Res[I];
5392cca53c8SAlexey Bataev int NumSrcRegs =
5402cca53c8SAlexey Bataev count_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
5412cca53c8SAlexey Bataev switch (NumSrcRegs) {
5422cca53c8SAlexey Bataev case 0:
5432cca53c8SAlexey Bataev // No input vectors were used!
5442cca53c8SAlexey Bataev NoInputAction();
5452cca53c8SAlexey Bataev break;
5462cca53c8SAlexey Bataev case 1: {
5472cca53c8SAlexey Bataev // Find the only mask with at least single undef mask elem.
5482cca53c8SAlexey Bataev auto *It =
5492cca53c8SAlexey Bataev find_if(Dest, [](ArrayRef<int> Mask) { return !Mask.empty(); });
5502cca53c8SAlexey Bataev unsigned SrcReg = std::distance(Dest.begin(), It);
55175e1cf4aSAlexey Bataev SingleInputAction(*It, SrcReg, I);
5522cca53c8SAlexey Bataev break;
5532cca53c8SAlexey Bataev }
5542cca53c8SAlexey Bataev default: {
5552cca53c8SAlexey Bataev // The first mask is a permutation of a single register. Since we have >2
5562cca53c8SAlexey Bataev // input registers to shuffle, we merge the masks for 2 first registers
5572cca53c8SAlexey Bataev // and generate a shuffle of 2 registers rather than the reordering of the
5582cca53c8SAlexey Bataev // first register and then shuffle with the second register. Next,
5592cca53c8SAlexey Bataev // generate the shuffles of the resulting register + the remaining
5602cca53c8SAlexey Bataev // registers from the list.
5612cca53c8SAlexey Bataev auto &&CombineMasks = [](MutableArrayRef<int> FirstMask,
5622cca53c8SAlexey Bataev ArrayRef<int> SecondMask) {
5632cca53c8SAlexey Bataev for (int Idx = 0, VF = FirstMask.size(); Idx < VF; ++Idx) {
5642cca53c8SAlexey Bataev if (SecondMask[Idx] != UndefMaskElem) {
5652cca53c8SAlexey Bataev assert(FirstMask[Idx] == UndefMaskElem &&
5662cca53c8SAlexey Bataev "Expected undefined mask element.");
5672cca53c8SAlexey Bataev FirstMask[Idx] = SecondMask[Idx] + VF;
5682cca53c8SAlexey Bataev }
5692cca53c8SAlexey Bataev }
5702cca53c8SAlexey Bataev };
5712cca53c8SAlexey Bataev auto &&NormalizeMask = [](MutableArrayRef<int> Mask) {
5722cca53c8SAlexey Bataev for (int Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
5732cca53c8SAlexey Bataev if (Mask[Idx] != UndefMaskElem)
5742cca53c8SAlexey Bataev Mask[Idx] = Idx;
5752cca53c8SAlexey Bataev }
5762cca53c8SAlexey Bataev };
5772cca53c8SAlexey Bataev int SecondIdx;
5782cca53c8SAlexey Bataev do {
5792cca53c8SAlexey Bataev int FirstIdx = -1;
5802cca53c8SAlexey Bataev SecondIdx = -1;
5812cca53c8SAlexey Bataev MutableArrayRef<int> FirstMask, SecondMask;
5822cca53c8SAlexey Bataev for (unsigned I = 0; I < NumOfDestRegs; ++I) {
5832cca53c8SAlexey Bataev SmallVectorImpl<int> &RegMask = Dest[I];
5842cca53c8SAlexey Bataev if (RegMask.empty())
5852cca53c8SAlexey Bataev continue;
5862cca53c8SAlexey Bataev
5872cca53c8SAlexey Bataev if (FirstIdx == SecondIdx) {
5882cca53c8SAlexey Bataev FirstIdx = I;
5892cca53c8SAlexey Bataev FirstMask = RegMask;
5902cca53c8SAlexey Bataev continue;
5912cca53c8SAlexey Bataev }
5922cca53c8SAlexey Bataev SecondIdx = I;
5932cca53c8SAlexey Bataev SecondMask = RegMask;
5942cca53c8SAlexey Bataev CombineMasks(FirstMask, SecondMask);
5952cca53c8SAlexey Bataev ManyInputsAction(FirstMask, FirstIdx, SecondIdx);
5962cca53c8SAlexey Bataev NormalizeMask(FirstMask);
5972cca53c8SAlexey Bataev RegMask.clear();
5982cca53c8SAlexey Bataev SecondMask = FirstMask;
5992cca53c8SAlexey Bataev SecondIdx = FirstIdx;
6002cca53c8SAlexey Bataev }
6012cca53c8SAlexey Bataev if (FirstIdx != SecondIdx && SecondIdx >= 0) {
6022cca53c8SAlexey Bataev CombineMasks(SecondMask, FirstMask);
6032cca53c8SAlexey Bataev ManyInputsAction(SecondMask, SecondIdx, FirstIdx);
6042cca53c8SAlexey Bataev Dest[FirstIdx].clear();
6052cca53c8SAlexey Bataev NormalizeMask(SecondMask);
6062cca53c8SAlexey Bataev }
6072cca53c8SAlexey Bataev } while (SecondIdx >= 0);
6082cca53c8SAlexey Bataev break;
6092cca53c8SAlexey Bataev }
6102cca53c8SAlexey Bataev }
6112cca53c8SAlexey Bataev }
6122cca53c8SAlexey Bataev }
6132cca53c8SAlexey Bataev
61454336a5aSCharlie Turner MapVector<Instruction *, uint64_t>
computeMinimumValueSizes(ArrayRef<BasicBlock * > Blocks,DemandedBits & DB,const TargetTransformInfo * TTI)61545f67d52SJames Molloy llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB,
61655d633bdSJames Molloy const TargetTransformInfo *TTI) {
61755d633bdSJames Molloy
61855d633bdSJames Molloy // DemandedBits will give us every value's live-out bits. But we want
61955d633bdSJames Molloy // to ensure no extra casts would need to be inserted, so every DAG
62055d633bdSJames Molloy // of connected values must have the same minimum bitwidth.
62155d633bdSJames Molloy EquivalenceClasses<Value *> ECs;
62255d633bdSJames Molloy SmallVector<Value *, 16> Worklist;
62355d633bdSJames Molloy SmallPtrSet<Value *, 4> Roots;
62455d633bdSJames Molloy SmallPtrSet<Value *, 16> Visited;
62555d633bdSJames Molloy DenseMap<Value *, uint64_t> DBits;
62655d633bdSJames Molloy SmallPtrSet<Instruction *, 4> InstructionSet;
62754336a5aSCharlie Turner MapVector<Instruction *, uint64_t> MinBWs;
62855d633bdSJames Molloy
62955d633bdSJames Molloy // Determine the roots. We work bottom-up, from truncs or icmps.
63055d633bdSJames Molloy bool SeenExtFromIllegalType = false;
63155d633bdSJames Molloy for (auto *BB : Blocks)
63255d633bdSJames Molloy for (auto &I : *BB) {
63355d633bdSJames Molloy InstructionSet.insert(&I);
63455d633bdSJames Molloy
63555d633bdSJames Molloy if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
63655d633bdSJames Molloy !TTI->isTypeLegal(I.getOperand(0)->getType()))
63755d633bdSJames Molloy SeenExtFromIllegalType = true;
63855d633bdSJames Molloy
63955d633bdSJames Molloy // Only deal with non-vector integers up to 64-bits wide.
64055d633bdSJames Molloy if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
64155d633bdSJames Molloy !I.getType()->isVectorTy() &&
64255d633bdSJames Molloy I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
64355d633bdSJames Molloy // Don't make work for ourselves. If we know the loaded type is legal,
64455d633bdSJames Molloy // don't add it to the worklist.
64555d633bdSJames Molloy if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
64655d633bdSJames Molloy continue;
64755d633bdSJames Molloy
64855d633bdSJames Molloy Worklist.push_back(&I);
64955d633bdSJames Molloy Roots.insert(&I);
65055d633bdSJames Molloy }
65155d633bdSJames Molloy }
65255d633bdSJames Molloy // Early exit.
65355d633bdSJames Molloy if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
65455d633bdSJames Molloy return MinBWs;
65555d633bdSJames Molloy
65655d633bdSJames Molloy // Now proceed breadth-first, unioning values together.
65755d633bdSJames Molloy while (!Worklist.empty()) {
65855d633bdSJames Molloy Value *Val = Worklist.pop_back_val();
65955d633bdSJames Molloy Value *Leader = ECs.getOrInsertLeaderValue(Val);
66055d633bdSJames Molloy
661b254d671SKazu Hirata if (!Visited.insert(Val).second)
66255d633bdSJames Molloy continue;
66355d633bdSJames Molloy
66455d633bdSJames Molloy // Non-instructions terminate a chain successfully.
66555d633bdSJames Molloy if (!isa<Instruction>(Val))
66655d633bdSJames Molloy continue;
66755d633bdSJames Molloy Instruction *I = cast<Instruction>(Val);
66855d633bdSJames Molloy
66955d633bdSJames Molloy // If we encounter a type that is larger than 64 bits, we can't represent
67055d633bdSJames Molloy // it so bail out.
671aa1d6388SJames Molloy if (DB.getDemandedBits(I).getBitWidth() > 64)
67254336a5aSCharlie Turner return MapVector<Instruction *, uint64_t>();
67355d633bdSJames Molloy
674aa1d6388SJames Molloy uint64_t V = DB.getDemandedBits(I).getZExtValue();
675aa1d6388SJames Molloy DBits[Leader] |= V;
676aa1d6388SJames Molloy DBits[I] = V;
67755d633bdSJames Molloy
67855d633bdSJames Molloy // Casts, loads and instructions outside of our range terminate a chain
67955d633bdSJames Molloy // successfully.
68055d633bdSJames Molloy if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
68155d633bdSJames Molloy !InstructionSet.count(I))
68255d633bdSJames Molloy continue;
68355d633bdSJames Molloy
68455d633bdSJames Molloy // Unsafe casts terminate a chain unsuccessfully. We can't do anything
68555d633bdSJames Molloy // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
68655d633bdSJames Molloy // transform anything that relies on them.
68755d633bdSJames Molloy if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
68855d633bdSJames Molloy !I->getType()->isIntegerTy()) {
68955d633bdSJames Molloy DBits[Leader] |= ~0ULL;
69055d633bdSJames Molloy continue;
69155d633bdSJames Molloy }
69255d633bdSJames Molloy
69355d633bdSJames Molloy // We don't modify the types of PHIs. Reductions will already have been
69455d633bdSJames Molloy // truncated if possible, and inductions' sizes will have been chosen by
69555d633bdSJames Molloy // indvars.
69655d633bdSJames Molloy if (isa<PHINode>(I))
69755d633bdSJames Molloy continue;
69855d633bdSJames Molloy
69955d633bdSJames Molloy if (DBits[Leader] == ~0ULL)
70055d633bdSJames Molloy // All bits demanded, no point continuing.
70155d633bdSJames Molloy continue;
70255d633bdSJames Molloy
70355d633bdSJames Molloy for (Value *O : cast<User>(I)->operands()) {
70455d633bdSJames Molloy ECs.unionSets(Leader, O);
70555d633bdSJames Molloy Worklist.push_back(O);
70655d633bdSJames Molloy }
70755d633bdSJames Molloy }
70855d633bdSJames Molloy
70955d633bdSJames Molloy // Now we've discovered all values, walk them to see if there are
71055d633bdSJames Molloy // any users we didn't see. If there are, we can't optimize that
71155d633bdSJames Molloy // chain.
71255d633bdSJames Molloy for (auto &I : DBits)
71355d633bdSJames Molloy for (auto *U : I.first->users())
71455d633bdSJames Molloy if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
71555d633bdSJames Molloy DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
71655d633bdSJames Molloy
71755d633bdSJames Molloy for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
71855d633bdSJames Molloy uint64_t LeaderDemandedBits = 0;
719896d0e1aSKazu Hirata for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
720896d0e1aSKazu Hirata LeaderDemandedBits |= DBits[M];
72155d633bdSJames Molloy
72255d633bdSJames Molloy uint64_t MinBW = (sizeof(LeaderDemandedBits) * 8) -
72355d633bdSJames Molloy llvm::countLeadingZeros(LeaderDemandedBits);
72455d633bdSJames Molloy // Round up to a power of 2
72555d633bdSJames Molloy if (!isPowerOf2_64((uint64_t)MinBW))
72655d633bdSJames Molloy MinBW = NextPowerOf2(MinBW);
7278e46cd05SJames Molloy
7288e46cd05SJames Molloy // We don't modify the types of PHIs. Reductions will already have been
7298e46cd05SJames Molloy // truncated if possible, and inductions' sizes will have been chosen by
7308e46cd05SJames Molloy // indvars.
7318e46cd05SJames Molloy // If we are required to shrink a PHI, abandon this entire equivalence class.
7328e46cd05SJames Molloy bool Abort = false;
733896d0e1aSKazu Hirata for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end()))
734896d0e1aSKazu Hirata if (isa<PHINode>(M) && MinBW < M->getType()->getScalarSizeInBits()) {
7358e46cd05SJames Molloy Abort = true;
7368e46cd05SJames Molloy break;
7378e46cd05SJames Molloy }
7388e46cd05SJames Molloy if (Abort)
7398e46cd05SJames Molloy continue;
7408e46cd05SJames Molloy
741896d0e1aSKazu Hirata for (Value *M : llvm::make_range(ECs.member_begin(I), ECs.member_end())) {
742896d0e1aSKazu Hirata if (!isa<Instruction>(M))
74355d633bdSJames Molloy continue;
744896d0e1aSKazu Hirata Type *Ty = M->getType();
745896d0e1aSKazu Hirata if (Roots.count(M))
746896d0e1aSKazu Hirata Ty = cast<Instruction>(M)->getOperand(0)->getType();
74755d633bdSJames Molloy if (MinBW < Ty->getScalarSizeInBits())
748896d0e1aSKazu Hirata MinBWs[cast<Instruction>(M)] = MinBW;
74955d633bdSJames Molloy }
75055d633bdSJames Molloy }
75155d633bdSJames Molloy
75255d633bdSJames Molloy return MinBWs;
75355d633bdSJames Molloy }
754727e279aSMatt Arsenault
755978ba615SMichael Kruse /// Add all access groups in @p AccGroups to @p List.
756978ba615SMichael Kruse template <typename ListT>
addToAccessGroupList(ListT & List,MDNode * AccGroups)757978ba615SMichael Kruse static void addToAccessGroupList(ListT &List, MDNode *AccGroups) {
758978ba615SMichael Kruse // Interpret an access group as a list containing itself.
759978ba615SMichael Kruse if (AccGroups->getNumOperands() == 0) {
760978ba615SMichael Kruse assert(isValidAsAccessGroup(AccGroups) && "Node must be an access group");
761978ba615SMichael Kruse List.insert(AccGroups);
762978ba615SMichael Kruse return;
763978ba615SMichael Kruse }
764978ba615SMichael Kruse
765601b3a13SKazu Hirata for (const auto &AccGroupListOp : AccGroups->operands()) {
766978ba615SMichael Kruse auto *Item = cast<MDNode>(AccGroupListOp.get());
767978ba615SMichael Kruse assert(isValidAsAccessGroup(Item) && "List item must be an access group");
768978ba615SMichael Kruse List.insert(Item);
769978ba615SMichael Kruse }
770d4bd3eb8SClement Courbet }
771978ba615SMichael Kruse
uniteAccessGroups(MDNode * AccGroups1,MDNode * AccGroups2)772978ba615SMichael Kruse MDNode *llvm::uniteAccessGroups(MDNode *AccGroups1, MDNode *AccGroups2) {
773978ba615SMichael Kruse if (!AccGroups1)
774978ba615SMichael Kruse return AccGroups2;
775978ba615SMichael Kruse if (!AccGroups2)
776978ba615SMichael Kruse return AccGroups1;
777978ba615SMichael Kruse if (AccGroups1 == AccGroups2)
778978ba615SMichael Kruse return AccGroups1;
779978ba615SMichael Kruse
780978ba615SMichael Kruse SmallSetVector<Metadata *, 4> Union;
781978ba615SMichael Kruse addToAccessGroupList(Union, AccGroups1);
782978ba615SMichael Kruse addToAccessGroupList(Union, AccGroups2);
783978ba615SMichael Kruse
784978ba615SMichael Kruse if (Union.size() == 0)
785978ba615SMichael Kruse return nullptr;
786978ba615SMichael Kruse if (Union.size() == 1)
787978ba615SMichael Kruse return cast<MDNode>(Union.front());
788978ba615SMichael Kruse
789978ba615SMichael Kruse LLVMContext &Ctx = AccGroups1->getContext();
790978ba615SMichael Kruse return MDNode::get(Ctx, Union.getArrayRef());
791978ba615SMichael Kruse }
792978ba615SMichael Kruse
intersectAccessGroups(const Instruction * Inst1,const Instruction * Inst2)793978ba615SMichael Kruse MDNode *llvm::intersectAccessGroups(const Instruction *Inst1,
794978ba615SMichael Kruse const Instruction *Inst2) {
795978ba615SMichael Kruse bool MayAccessMem1 = Inst1->mayReadOrWriteMemory();
796978ba615SMichael Kruse bool MayAccessMem2 = Inst2->mayReadOrWriteMemory();
797978ba615SMichael Kruse
798978ba615SMichael Kruse if (!MayAccessMem1 && !MayAccessMem2)
799978ba615SMichael Kruse return nullptr;
800978ba615SMichael Kruse if (!MayAccessMem1)
801978ba615SMichael Kruse return Inst2->getMetadata(LLVMContext::MD_access_group);
802978ba615SMichael Kruse if (!MayAccessMem2)
803978ba615SMichael Kruse return Inst1->getMetadata(LLVMContext::MD_access_group);
804978ba615SMichael Kruse
805978ba615SMichael Kruse MDNode *MD1 = Inst1->getMetadata(LLVMContext::MD_access_group);
806978ba615SMichael Kruse MDNode *MD2 = Inst2->getMetadata(LLVMContext::MD_access_group);
807978ba615SMichael Kruse if (!MD1 || !MD2)
808978ba615SMichael Kruse return nullptr;
809978ba615SMichael Kruse if (MD1 == MD2)
810978ba615SMichael Kruse return MD1;
811978ba615SMichael Kruse
812978ba615SMichael Kruse // Use set for scalable 'contains' check.
813978ba615SMichael Kruse SmallPtrSet<Metadata *, 4> AccGroupSet2;
814978ba615SMichael Kruse addToAccessGroupList(AccGroupSet2, MD2);
815978ba615SMichael Kruse
816978ba615SMichael Kruse SmallVector<Metadata *, 4> Intersection;
817978ba615SMichael Kruse if (MD1->getNumOperands() == 0) {
818978ba615SMichael Kruse assert(isValidAsAccessGroup(MD1) && "Node must be an access group");
819978ba615SMichael Kruse if (AccGroupSet2.count(MD1))
820978ba615SMichael Kruse Intersection.push_back(MD1);
821978ba615SMichael Kruse } else {
822978ba615SMichael Kruse for (const MDOperand &Node : MD1->operands()) {
823978ba615SMichael Kruse auto *Item = cast<MDNode>(Node.get());
824978ba615SMichael Kruse assert(isValidAsAccessGroup(Item) && "List item must be an access group");
825978ba615SMichael Kruse if (AccGroupSet2.count(Item))
826978ba615SMichael Kruse Intersection.push_back(Item);
827978ba615SMichael Kruse }
828978ba615SMichael Kruse }
829978ba615SMichael Kruse
830978ba615SMichael Kruse if (Intersection.size() == 0)
831978ba615SMichael Kruse return nullptr;
832978ba615SMichael Kruse if (Intersection.size() == 1)
833978ba615SMichael Kruse return cast<MDNode>(Intersection.front());
834978ba615SMichael Kruse
835978ba615SMichael Kruse LLVMContext &Ctx = Inst1->getContext();
836978ba615SMichael Kruse return MDNode::get(Ctx, Intersection);
837978ba615SMichael Kruse }
838978ba615SMichael Kruse
839727e279aSMatt Arsenault /// \returns \p I after propagating metadata from \p VL.
propagateMetadata(Instruction * Inst,ArrayRef<Value * > VL)840727e279aSMatt Arsenault Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
84150cf0a1dSKrzysztof Parzyszek if (VL.empty())
84250cf0a1dSKrzysztof Parzyszek return Inst;
843727e279aSMatt Arsenault Instruction *I0 = cast<Instruction>(VL[0]);
844727e279aSMatt Arsenault SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
845727e279aSMatt Arsenault I0->getAllMetadataOtherThanDebugLoc(Metadata);
846727e279aSMatt Arsenault
847978ba615SMichael Kruse for (auto Kind : {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
848727e279aSMatt Arsenault LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
849978ba615SMichael Kruse LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load,
850978ba615SMichael Kruse LLVMContext::MD_access_group}) {
851727e279aSMatt Arsenault MDNode *MD = I0->getMetadata(Kind);
852727e279aSMatt Arsenault
853727e279aSMatt Arsenault for (int J = 1, E = VL.size(); MD && J != E; ++J) {
854727e279aSMatt Arsenault const Instruction *IJ = cast<Instruction>(VL[J]);
855727e279aSMatt Arsenault MDNode *IMD = IJ->getMetadata(Kind);
856727e279aSMatt Arsenault switch (Kind) {
857727e279aSMatt Arsenault case LLVMContext::MD_tbaa:
858727e279aSMatt Arsenault MD = MDNode::getMostGenericTBAA(MD, IMD);
859727e279aSMatt Arsenault break;
860727e279aSMatt Arsenault case LLVMContext::MD_alias_scope:
861727e279aSMatt Arsenault MD = MDNode::getMostGenericAliasScope(MD, IMD);
862727e279aSMatt Arsenault break;
863727e279aSMatt Arsenault case LLVMContext::MD_fpmath:
864727e279aSMatt Arsenault MD = MDNode::getMostGenericFPMath(MD, IMD);
865727e279aSMatt Arsenault break;
86611a32043SJustin Lebar case LLVMContext::MD_noalias:
867727e279aSMatt Arsenault case LLVMContext::MD_nontemporal:
86811a32043SJustin Lebar case LLVMContext::MD_invariant_load:
869727e279aSMatt Arsenault MD = MDNode::intersect(MD, IMD);
870727e279aSMatt Arsenault break;
871978ba615SMichael Kruse case LLVMContext::MD_access_group:
872978ba615SMichael Kruse MD = intersectAccessGroups(Inst, IJ);
873978ba615SMichael Kruse break;
874727e279aSMatt Arsenault default:
875727e279aSMatt Arsenault llvm_unreachable("unhandled metadata");
876727e279aSMatt Arsenault }
877727e279aSMatt Arsenault }
878727e279aSMatt Arsenault
879727e279aSMatt Arsenault Inst->setMetadata(Kind, MD);
880727e279aSMatt Arsenault }
881727e279aSMatt Arsenault
882727e279aSMatt Arsenault return Inst;
883727e279aSMatt Arsenault }
884ba5cf9dfSMatthew Simpson
885a4dc7feeSFlorian Hahn Constant *
createBitMaskForGaps(IRBuilderBase & Builder,unsigned VF,const InterleaveGroup<Instruction> & Group)886f37e899fSNikita Popov llvm::createBitMaskForGaps(IRBuilderBase &Builder, unsigned VF,
887a4dc7feeSFlorian Hahn const InterleaveGroup<Instruction> &Group) {
88834da6dd6SDorit Nuzman // All 1's means mask is not needed.
88934da6dd6SDorit Nuzman if (Group.getNumMembers() == Group.getFactor())
89034da6dd6SDorit Nuzman return nullptr;
89134da6dd6SDorit Nuzman
89234da6dd6SDorit Nuzman // TODO: support reversed access.
89334da6dd6SDorit Nuzman assert(!Group.isReverse() && "Reversed group not supported.");
89434da6dd6SDorit Nuzman
89534da6dd6SDorit Nuzman SmallVector<Constant *, 16> Mask;
89634da6dd6SDorit Nuzman for (unsigned i = 0; i < VF; i++)
89734da6dd6SDorit Nuzman for (unsigned j = 0; j < Group.getFactor(); ++j) {
89834da6dd6SDorit Nuzman unsigned HasMember = Group.getMember(j) ? 1 : 0;
89934da6dd6SDorit Nuzman Mask.push_back(Builder.getInt1(HasMember));
90034da6dd6SDorit Nuzman }
90134da6dd6SDorit Nuzman
90234da6dd6SDorit Nuzman return ConstantVector::get(Mask);
90334da6dd6SDorit Nuzman }
90434da6dd6SDorit Nuzman
905166467e8SBenjamin Kramer llvm::SmallVector<int, 16>
createReplicatedMask(unsigned ReplicationFactor,unsigned VF)906166467e8SBenjamin Kramer llvm::createReplicatedMask(unsigned ReplicationFactor, unsigned VF) {
907166467e8SBenjamin Kramer SmallVector<int, 16> MaskVec;
90838bbf81aSDorit Nuzman for (unsigned i = 0; i < VF; i++)
90938bbf81aSDorit Nuzman for (unsigned j = 0; j < ReplicationFactor; j++)
910166467e8SBenjamin Kramer MaskVec.push_back(i);
91138bbf81aSDorit Nuzman
912166467e8SBenjamin Kramer return MaskVec;
91338bbf81aSDorit Nuzman }
91438bbf81aSDorit Nuzman
createInterleaveMask(unsigned VF,unsigned NumVecs)915166467e8SBenjamin Kramer llvm::SmallVector<int, 16> llvm::createInterleaveMask(unsigned VF,
916ba5cf9dfSMatthew Simpson unsigned NumVecs) {
917166467e8SBenjamin Kramer SmallVector<int, 16> Mask;
918ba5cf9dfSMatthew Simpson for (unsigned i = 0; i < VF; i++)
919ba5cf9dfSMatthew Simpson for (unsigned j = 0; j < NumVecs; j++)
920166467e8SBenjamin Kramer Mask.push_back(j * VF + i);
921ba5cf9dfSMatthew Simpson
922166467e8SBenjamin Kramer return Mask;
923ba5cf9dfSMatthew Simpson }
924ba5cf9dfSMatthew Simpson
925166467e8SBenjamin Kramer llvm::SmallVector<int, 16>
createStrideMask(unsigned Start,unsigned Stride,unsigned VF)926166467e8SBenjamin Kramer llvm::createStrideMask(unsigned Start, unsigned Stride, unsigned VF) {
927166467e8SBenjamin Kramer SmallVector<int, 16> Mask;
928ba5cf9dfSMatthew Simpson for (unsigned i = 0; i < VF; i++)
929166467e8SBenjamin Kramer Mask.push_back(Start + i * Stride);
930ba5cf9dfSMatthew Simpson
931166467e8SBenjamin Kramer return Mask;
932ba5cf9dfSMatthew Simpson }
933ba5cf9dfSMatthew Simpson
createSequentialMask(unsigned Start,unsigned NumInts,unsigned NumUndefs)934166467e8SBenjamin Kramer llvm::SmallVector<int, 16> llvm::createSequentialMask(unsigned Start,
935166467e8SBenjamin Kramer unsigned NumInts,
936166467e8SBenjamin Kramer unsigned NumUndefs) {
937166467e8SBenjamin Kramer SmallVector<int, 16> Mask;
938ba5cf9dfSMatthew Simpson for (unsigned i = 0; i < NumInts; i++)
939166467e8SBenjamin Kramer Mask.push_back(Start + i);
940ba5cf9dfSMatthew Simpson
941ba5cf9dfSMatthew Simpson for (unsigned i = 0; i < NumUndefs; i++)
942166467e8SBenjamin Kramer Mask.push_back(-1);
943ba5cf9dfSMatthew Simpson
944166467e8SBenjamin Kramer return Mask;
945ba5cf9dfSMatthew Simpson }
946ba5cf9dfSMatthew Simpson
createUnaryMask(ArrayRef<int> Mask,unsigned NumElts)9472a3cc4d4SSanjay Patel llvm::SmallVector<int, 16> llvm::createUnaryMask(ArrayRef<int> Mask,
9482a3cc4d4SSanjay Patel unsigned NumElts) {
9492a3cc4d4SSanjay Patel // Avoid casts in the loop and make sure we have a reasonable number.
9502a3cc4d4SSanjay Patel int NumEltsSigned = NumElts;
9512a3cc4d4SSanjay Patel assert(NumEltsSigned > 0 && "Expected smaller or non-zero element count");
9522a3cc4d4SSanjay Patel
9532a3cc4d4SSanjay Patel // If the mask chooses an element from operand 1, reduce it to choose from the
9542a3cc4d4SSanjay Patel // corresponding element of operand 0. Undef mask elements are unchanged.
9552a3cc4d4SSanjay Patel SmallVector<int, 16> UnaryMask;
9562a3cc4d4SSanjay Patel for (int MaskElt : Mask) {
9572a3cc4d4SSanjay Patel assert((MaskElt < NumEltsSigned * 2) && "Expected valid shuffle mask");
9582a3cc4d4SSanjay Patel int UnaryElt = MaskElt >= NumEltsSigned ? MaskElt - NumEltsSigned : MaskElt;
9592a3cc4d4SSanjay Patel UnaryMask.push_back(UnaryElt);
9602a3cc4d4SSanjay Patel }
9612a3cc4d4SSanjay Patel return UnaryMask;
9622a3cc4d4SSanjay Patel }
9632a3cc4d4SSanjay Patel
964ba5cf9dfSMatthew Simpson /// A helper function for concatenating vectors. This function concatenates two
965ba5cf9dfSMatthew Simpson /// vectors having the same element type. If the second vector has fewer
966ba5cf9dfSMatthew Simpson /// elements than the first, it is padded with undefs.
concatenateTwoVectors(IRBuilderBase & Builder,Value * V1,Value * V2)967f37e899fSNikita Popov static Value *concatenateTwoVectors(IRBuilderBase &Builder, Value *V1,
968ba5cf9dfSMatthew Simpson Value *V2) {
969ba5cf9dfSMatthew Simpson VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
970ba5cf9dfSMatthew Simpson VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
971ba5cf9dfSMatthew Simpson assert(VecTy1 && VecTy2 &&
972ba5cf9dfSMatthew Simpson VecTy1->getScalarType() == VecTy2->getScalarType() &&
973ba5cf9dfSMatthew Simpson "Expect two vectors with the same element type");
974ba5cf9dfSMatthew Simpson
97523c5e59dSChristopher Tetreault unsigned NumElts1 = cast<FixedVectorType>(VecTy1)->getNumElements();
97623c5e59dSChristopher Tetreault unsigned NumElts2 = cast<FixedVectorType>(VecTy2)->getNumElements();
977ba5cf9dfSMatthew Simpson assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
978ba5cf9dfSMatthew Simpson
979ba5cf9dfSMatthew Simpson if (NumElts1 > NumElts2) {
980ba5cf9dfSMatthew Simpson // Extend with UNDEFs.
981166467e8SBenjamin Kramer V2 = Builder.CreateShuffleVector(
9829b296102SJuneyoung Lee V2, createSequentialMask(0, NumElts2, NumElts1 - NumElts2));
983ba5cf9dfSMatthew Simpson }
984ba5cf9dfSMatthew Simpson
985166467e8SBenjamin Kramer return Builder.CreateShuffleVector(
986166467e8SBenjamin Kramer V1, V2, createSequentialMask(0, NumElts1 + NumElts2, 0));
987ba5cf9dfSMatthew Simpson }
988ba5cf9dfSMatthew Simpson
concatenateVectors(IRBuilderBase & Builder,ArrayRef<Value * > Vecs)989f37e899fSNikita Popov Value *llvm::concatenateVectors(IRBuilderBase &Builder,
990f37e899fSNikita Popov ArrayRef<Value *> Vecs) {
991ba5cf9dfSMatthew Simpson unsigned NumVecs = Vecs.size();
992ba5cf9dfSMatthew Simpson assert(NumVecs > 1 && "Should be at least two vectors");
993ba5cf9dfSMatthew Simpson
994ba5cf9dfSMatthew Simpson SmallVector<Value *, 8> ResList;
995ba5cf9dfSMatthew Simpson ResList.append(Vecs.begin(), Vecs.end());
996ba5cf9dfSMatthew Simpson do {
997ba5cf9dfSMatthew Simpson SmallVector<Value *, 8> TmpList;
998ba5cf9dfSMatthew Simpson for (unsigned i = 0; i < NumVecs - 1; i += 2) {
999ba5cf9dfSMatthew Simpson Value *V0 = ResList[i], *V1 = ResList[i + 1];
1000ba5cf9dfSMatthew Simpson assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
1001ba5cf9dfSMatthew Simpson "Only the last vector may have a different type");
1002ba5cf9dfSMatthew Simpson
1003ba5cf9dfSMatthew Simpson TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
1004ba5cf9dfSMatthew Simpson }
1005ba5cf9dfSMatthew Simpson
1006ba5cf9dfSMatthew Simpson // Push the last vector if the total number of vectors is odd.
1007ba5cf9dfSMatthew Simpson if (NumVecs % 2 != 0)
1008ba5cf9dfSMatthew Simpson TmpList.push_back(ResList[NumVecs - 1]);
1009ba5cf9dfSMatthew Simpson
1010ba5cf9dfSMatthew Simpson ResList = TmpList;
1011ba5cf9dfSMatthew Simpson NumVecs = ResList.size();
1012ba5cf9dfSMatthew Simpson } while (NumVecs > 1);
1013ba5cf9dfSMatthew Simpson
1014ba5cf9dfSMatthew Simpson return ResList[0];
1015ba5cf9dfSMatthew Simpson }
10161086ce23SFlorian Hahn
maskIsAllZeroOrUndef(Value * Mask)101788cd69b5SPhilip Reames bool llvm::maskIsAllZeroOrUndef(Value *Mask) {
10187ddfd9b3SChristopher Tetreault assert(isa<VectorType>(Mask->getType()) &&
10197ddfd9b3SChristopher Tetreault isa<IntegerType>(Mask->getType()->getScalarType()) &&
10207ddfd9b3SChristopher Tetreault cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
10217ddfd9b3SChristopher Tetreault 1 &&
10227ddfd9b3SChristopher Tetreault "Mask must be a vector of i1");
10237ddfd9b3SChristopher Tetreault
102488cd69b5SPhilip Reames auto *ConstMask = dyn_cast<Constant>(Mask);
102588cd69b5SPhilip Reames if (!ConstMask)
102688cd69b5SPhilip Reames return false;
102788cd69b5SPhilip Reames if (ConstMask->isNullValue() || isa<UndefValue>(ConstMask))
102888cd69b5SPhilip Reames return true;
10297ddfd9b3SChristopher Tetreault if (isa<ScalableVectorType>(ConstMask->getType()))
10307ddfd9b3SChristopher Tetreault return false;
103123c5e59dSChristopher Tetreault for (unsigned
103223c5e59dSChristopher Tetreault I = 0,
103323c5e59dSChristopher Tetreault E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
1034b96558f5SChristopher Tetreault I != E; ++I) {
103588cd69b5SPhilip Reames if (auto *MaskElt = ConstMask->getAggregateElement(I))
103688cd69b5SPhilip Reames if (MaskElt->isNullValue() || isa<UndefValue>(MaskElt))
103788cd69b5SPhilip Reames continue;
103888cd69b5SPhilip Reames return false;
103988cd69b5SPhilip Reames }
104088cd69b5SPhilip Reames return true;
104188cd69b5SPhilip Reames }
104288cd69b5SPhilip Reames
maskIsAllOneOrUndef(Value * Mask)104388cd69b5SPhilip Reames bool llvm::maskIsAllOneOrUndef(Value *Mask) {
10447ddfd9b3SChristopher Tetreault assert(isa<VectorType>(Mask->getType()) &&
10457ddfd9b3SChristopher Tetreault isa<IntegerType>(Mask->getType()->getScalarType()) &&
10467ddfd9b3SChristopher Tetreault cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
10477ddfd9b3SChristopher Tetreault 1 &&
10487ddfd9b3SChristopher Tetreault "Mask must be a vector of i1");
10497ddfd9b3SChristopher Tetreault
105088cd69b5SPhilip Reames auto *ConstMask = dyn_cast<Constant>(Mask);
105188cd69b5SPhilip Reames if (!ConstMask)
105288cd69b5SPhilip Reames return false;
105388cd69b5SPhilip Reames if (ConstMask->isAllOnesValue() || isa<UndefValue>(ConstMask))
105488cd69b5SPhilip Reames return true;
10557ddfd9b3SChristopher Tetreault if (isa<ScalableVectorType>(ConstMask->getType()))
10567ddfd9b3SChristopher Tetreault return false;
105723c5e59dSChristopher Tetreault for (unsigned
105823c5e59dSChristopher Tetreault I = 0,
105923c5e59dSChristopher Tetreault E = cast<FixedVectorType>(ConstMask->getType())->getNumElements();
1060b96558f5SChristopher Tetreault I != E; ++I) {
106188cd69b5SPhilip Reames if (auto *MaskElt = ConstMask->getAggregateElement(I))
106288cd69b5SPhilip Reames if (MaskElt->isAllOnesValue() || isa<UndefValue>(MaskElt))
106388cd69b5SPhilip Reames continue;
106488cd69b5SPhilip Reames return false;
106588cd69b5SPhilip Reames }
106688cd69b5SPhilip Reames return true;
106788cd69b5SPhilip Reames }
106888cd69b5SPhilip Reames
106988cd69b5SPhilip Reames /// TODO: This is a lot like known bits, but for
107088cd69b5SPhilip Reames /// vectors. Is there something we can common this with?
possiblyDemandedEltsInMask(Value * Mask)107188cd69b5SPhilip Reames APInt llvm::possiblyDemandedEltsInMask(Value *Mask) {
10727ddfd9b3SChristopher Tetreault assert(isa<FixedVectorType>(Mask->getType()) &&
10737ddfd9b3SChristopher Tetreault isa<IntegerType>(Mask->getType()->getScalarType()) &&
10747ddfd9b3SChristopher Tetreault cast<IntegerType>(Mask->getType()->getScalarType())->getBitWidth() ==
10757ddfd9b3SChristopher Tetreault 1 &&
10767ddfd9b3SChristopher Tetreault "Mask must be a fixed width vector of i1");
107788cd69b5SPhilip Reames
107823c5e59dSChristopher Tetreault const unsigned VWidth =
107923c5e59dSChristopher Tetreault cast<FixedVectorType>(Mask->getType())->getNumElements();
1080735f4671SChris Lattner APInt DemandedElts = APInt::getAllOnes(VWidth);
108188cd69b5SPhilip Reames if (auto *CV = dyn_cast<ConstantVector>(Mask))
108288cd69b5SPhilip Reames for (unsigned i = 0; i < VWidth; i++)
108388cd69b5SPhilip Reames if (CV->getAggregateElement(i)->isNullValue())
108488cd69b5SPhilip Reames DemandedElts.clearBit(i);
108588cd69b5SPhilip Reames return DemandedElts;
108688cd69b5SPhilip Reames }
108788cd69b5SPhilip Reames
isStrided(int Stride)10881086ce23SFlorian Hahn bool InterleavedAccessInfo::isStrided(int Stride) {
10891086ce23SFlorian Hahn unsigned Factor = std::abs(Stride);
10901086ce23SFlorian Hahn return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
10911086ce23SFlorian Hahn }
10921086ce23SFlorian Hahn
collectConstStrideAccesses(MapVector<Instruction *,StrideDescriptor> & AccessStrideInfo,const ValueToValueMap & Strides)10931086ce23SFlorian Hahn void InterleavedAccessInfo::collectConstStrideAccesses(
10941086ce23SFlorian Hahn MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
10951086ce23SFlorian Hahn const ValueToValueMap &Strides) {
10961086ce23SFlorian Hahn auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
10971086ce23SFlorian Hahn
10981086ce23SFlorian Hahn // Since it's desired that the load/store instructions be maintained in
10991086ce23SFlorian Hahn // "program order" for the interleaved access analysis, we have to visit the
11001086ce23SFlorian Hahn // blocks in the loop in reverse postorder (i.e., in a topological order).
11011086ce23SFlorian Hahn // Such an ordering will ensure that any load/store that may be executed
11021086ce23SFlorian Hahn // before a second load/store will precede the second load/store in
11031086ce23SFlorian Hahn // AccessStrideInfo.
11041086ce23SFlorian Hahn LoopBlocksDFS DFS(TheLoop);
11051086ce23SFlorian Hahn DFS.perform(LI);
11061086ce23SFlorian Hahn for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
11071086ce23SFlorian Hahn for (auto &I : *BB) {
11081086ce23SFlorian Hahn Value *Ptr = getLoadStorePointerOperand(&I);
1109cc64ece7SArthur Eubanks if (!Ptr)
1110cc64ece7SArthur Eubanks continue;
1111cc64ece7SArthur Eubanks Type *ElementTy = getLoadStoreType(&I);
1112cc64ece7SArthur Eubanks
1113*a3998966SFlorian Hahn // Currently, codegen doesn't support cases where the type size doesn't
1114*a3998966SFlorian Hahn // match the alloc size. Skip them for now.
1115*a3998966SFlorian Hahn uint64_t Size = DL.getTypeAllocSize(ElementTy);
1116*a3998966SFlorian Hahn if (Size * 8 != DL.getTypeSizeInBits(ElementTy))
1117*a3998966SFlorian Hahn continue;
1118*a3998966SFlorian Hahn
11191086ce23SFlorian Hahn // We don't check wrapping here because we don't know yet if Ptr will be
11201086ce23SFlorian Hahn // part of a full group or a group with gaps. Checking wrapping for all
11211086ce23SFlorian Hahn // pointers (even those that end up in groups with no gaps) will be overly
11221086ce23SFlorian Hahn // conservative. For full groups, wrapping should be ok since if we would
11231086ce23SFlorian Hahn // wrap around the address space we would do a memory access at nullptr
11241086ce23SFlorian Hahn // even without the transformation. The wrapping checks are therefore
11251086ce23SFlorian Hahn // deferred until after we've formed the interleaved groups.
112645c46734SNikita Popov int64_t Stride = getPtrStride(PSE, ElementTy, Ptr, TheLoop, Strides,
11271086ce23SFlorian Hahn /*Assume=*/true, /*ShouldCheckWrap=*/false);
11281086ce23SFlorian Hahn
11291086ce23SFlorian Hahn const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
113052e98f62SNikita Popov AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size,
113152e98f62SNikita Popov getLoadStoreAlignment(&I));
11321086ce23SFlorian Hahn }
11331086ce23SFlorian Hahn }
11341086ce23SFlorian Hahn
11351086ce23SFlorian Hahn // Analyze interleaved accesses and collect them into interleaved load and
11361086ce23SFlorian Hahn // store groups.
11371086ce23SFlorian Hahn //
11381086ce23SFlorian Hahn // When generating code for an interleaved load group, we effectively hoist all
11391086ce23SFlorian Hahn // loads in the group to the location of the first load in program order. When
11401086ce23SFlorian Hahn // generating code for an interleaved store group, we sink all stores to the
11411086ce23SFlorian Hahn // location of the last store. This code motion can change the order of load
11421086ce23SFlorian Hahn // and store instructions and may break dependences.
11431086ce23SFlorian Hahn //
11441086ce23SFlorian Hahn // The code generation strategy mentioned above ensures that we won't violate
11451086ce23SFlorian Hahn // any write-after-read (WAR) dependences.
11461086ce23SFlorian Hahn //
11471086ce23SFlorian Hahn // E.g., for the WAR dependence: a = A[i]; // (1)
11481086ce23SFlorian Hahn // A[i] = b; // (2)
11491086ce23SFlorian Hahn //
11501086ce23SFlorian Hahn // The store group of (2) is always inserted at or below (2), and the load
11511086ce23SFlorian Hahn // group of (1) is always inserted at or above (1). Thus, the instructions will
11521086ce23SFlorian Hahn // never be reordered. All other dependences are checked to ensure the
11531086ce23SFlorian Hahn // correctness of the instruction reordering.
11541086ce23SFlorian Hahn //
11551086ce23SFlorian Hahn // The algorithm visits all memory accesses in the loop in bottom-up program
11561086ce23SFlorian Hahn // order. Program order is established by traversing the blocks in the loop in
11571086ce23SFlorian Hahn // reverse postorder when collecting the accesses.
11581086ce23SFlorian Hahn //
11591086ce23SFlorian Hahn // We visit the memory accesses in bottom-up order because it can simplify the
11601086ce23SFlorian Hahn // construction of store groups in the presence of write-after-write (WAW)
11611086ce23SFlorian Hahn // dependences.
11621086ce23SFlorian Hahn //
11631086ce23SFlorian Hahn // E.g., for the WAW dependence: A[i] = a; // (1)
11641086ce23SFlorian Hahn // A[i] = b; // (2)
11651086ce23SFlorian Hahn // A[i + 1] = c; // (3)
11661086ce23SFlorian Hahn //
11671086ce23SFlorian Hahn // We will first create a store group with (3) and (2). (1) can't be added to
11681086ce23SFlorian Hahn // this group because it and (2) are dependent. However, (1) can be grouped
11691086ce23SFlorian Hahn // with other accesses that may precede it in program order. Note that a
11701086ce23SFlorian Hahn // bottom-up order does not imply that WAW dependences should not be checked.
analyzeInterleaving(bool EnablePredicatedInterleavedMemAccesses)117138bbf81aSDorit Nuzman void InterleavedAccessInfo::analyzeInterleaving(
117238bbf81aSDorit Nuzman bool EnablePredicatedInterleavedMemAccesses) {
11731086ce23SFlorian Hahn LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
11741086ce23SFlorian Hahn const ValueToValueMap &Strides = LAI->getSymbolicStrides();
11751086ce23SFlorian Hahn
11761086ce23SFlorian Hahn // Holds all accesses with a constant stride.
11771086ce23SFlorian Hahn MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
11781086ce23SFlorian Hahn collectConstStrideAccesses(AccessStrideInfo, Strides);
11791086ce23SFlorian Hahn
11801086ce23SFlorian Hahn if (AccessStrideInfo.empty())
11811086ce23SFlorian Hahn return;
11821086ce23SFlorian Hahn
11831086ce23SFlorian Hahn // Collect the dependences in the loop.
11841086ce23SFlorian Hahn collectDependences();
11851086ce23SFlorian Hahn
11861086ce23SFlorian Hahn // Holds all interleaved store groups temporarily.
1187a4dc7feeSFlorian Hahn SmallSetVector<InterleaveGroup<Instruction> *, 4> StoreGroups;
11881086ce23SFlorian Hahn // Holds all interleaved load groups temporarily.
1189a4dc7feeSFlorian Hahn SmallSetVector<InterleaveGroup<Instruction> *, 4> LoadGroups;
11901086ce23SFlorian Hahn
11911086ce23SFlorian Hahn // Search in bottom-up program order for pairs of accesses (A and B) that can
11921086ce23SFlorian Hahn // form interleaved load or store groups. In the algorithm below, access A
11931086ce23SFlorian Hahn // precedes access B in program order. We initialize a group for B in the
11941086ce23SFlorian Hahn // outer loop of the algorithm, and then in the inner loop, we attempt to
11951086ce23SFlorian Hahn // insert each A into B's group if:
11961086ce23SFlorian Hahn //
11971086ce23SFlorian Hahn // 1. A and B have the same stride,
11981086ce23SFlorian Hahn // 2. A and B have the same memory object size, and
11991086ce23SFlorian Hahn // 3. A belongs in B's group according to its distance from B.
12001086ce23SFlorian Hahn //
12011086ce23SFlorian Hahn // Special care is taken to ensure group formation will not break any
12021086ce23SFlorian Hahn // dependences.
12031086ce23SFlorian Hahn for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
12041086ce23SFlorian Hahn BI != E; ++BI) {
12051086ce23SFlorian Hahn Instruction *B = BI->first;
12061086ce23SFlorian Hahn StrideDescriptor DesB = BI->second;
12071086ce23SFlorian Hahn
12081086ce23SFlorian Hahn // Initialize a group for B if it has an allowable stride. Even if we don't
12091086ce23SFlorian Hahn // create a group for B, we continue with the bottom-up algorithm to ensure
12101086ce23SFlorian Hahn // we don't break any of B's dependences.
1211a4dc7feeSFlorian Hahn InterleaveGroup<Instruction> *Group = nullptr;
121238bbf81aSDorit Nuzman if (isStrided(DesB.Stride) &&
121338bbf81aSDorit Nuzman (!isPredicated(B->getParent()) || EnablePredicatedInterleavedMemAccesses)) {
12141086ce23SFlorian Hahn Group = getInterleaveGroup(B);
12151086ce23SFlorian Hahn if (!Group) {
12161086ce23SFlorian Hahn LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
12171086ce23SFlorian Hahn << '\n');
1218837a1b84SGuillaume Chatelet Group = createInterleaveGroup(B, DesB.Stride, DesB.Alignment);
12191086ce23SFlorian Hahn }
12201086ce23SFlorian Hahn if (B->mayWriteToMemory())
12211086ce23SFlorian Hahn StoreGroups.insert(Group);
12221086ce23SFlorian Hahn else
12231086ce23SFlorian Hahn LoadGroups.insert(Group);
12241086ce23SFlorian Hahn }
12251086ce23SFlorian Hahn
12261086ce23SFlorian Hahn for (auto AI = std::next(BI); AI != E; ++AI) {
12271086ce23SFlorian Hahn Instruction *A = AI->first;
12281086ce23SFlorian Hahn StrideDescriptor DesA = AI->second;
12291086ce23SFlorian Hahn
12301086ce23SFlorian Hahn // Our code motion strategy implies that we can't have dependences
12311086ce23SFlorian Hahn // between accesses in an interleaved group and other accesses located
12321086ce23SFlorian Hahn // between the first and last member of the group. Note that this also
12331086ce23SFlorian Hahn // means that a group can't have more than one member at a given offset.
12341086ce23SFlorian Hahn // The accesses in a group can have dependences with other accesses, but
12351086ce23SFlorian Hahn // we must ensure we don't extend the boundaries of the group such that
12361086ce23SFlorian Hahn // we encompass those dependent accesses.
12371086ce23SFlorian Hahn //
12381086ce23SFlorian Hahn // For example, assume we have the sequence of accesses shown below in a
12391086ce23SFlorian Hahn // stride-2 loop:
12401086ce23SFlorian Hahn //
12411086ce23SFlorian Hahn // (1, 2) is a group | A[i] = a; // (1)
12421086ce23SFlorian Hahn // | A[i-1] = b; // (2) |
12431086ce23SFlorian Hahn // A[i-3] = c; // (3)
12441086ce23SFlorian Hahn // A[i] = d; // (4) | (2, 4) is not a group
12451086ce23SFlorian Hahn //
12461086ce23SFlorian Hahn // Because accesses (2) and (3) are dependent, we can group (2) with (1)
12471086ce23SFlorian Hahn // but not with (4). If we did, the dependent access (3) would be within
12481086ce23SFlorian Hahn // the boundaries of the (2, 4) group.
12491086ce23SFlorian Hahn if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
12501086ce23SFlorian Hahn // If a dependence exists and A is already in a group, we know that A
12511086ce23SFlorian Hahn // must be a store since A precedes B and WAR dependences are allowed.
12521086ce23SFlorian Hahn // Thus, A would be sunk below B. We release A's group to prevent this
12531086ce23SFlorian Hahn // illegal code motion. A will then be free to form another group with
12541086ce23SFlorian Hahn // instructions that precede it.
12551086ce23SFlorian Hahn if (isInterleaved(A)) {
1256a4dc7feeSFlorian Hahn InterleaveGroup<Instruction> *StoreGroup = getInterleaveGroup(A);
125709fac245SHideki Saito
125809fac245SHideki Saito LLVM_DEBUG(dbgs() << "LV: Invalidated store group due to "
125909fac245SHideki Saito "dependence between " << *A << " and "<< *B << '\n');
126009fac245SHideki Saito
12611086ce23SFlorian Hahn StoreGroups.remove(StoreGroup);
12621086ce23SFlorian Hahn releaseGroup(StoreGroup);
12631086ce23SFlorian Hahn }
12641086ce23SFlorian Hahn
12651086ce23SFlorian Hahn // If a dependence exists and A is not already in a group (or it was
12661086ce23SFlorian Hahn // and we just released it), B might be hoisted above A (if B is a
12671086ce23SFlorian Hahn // load) or another store might be sunk below A (if B is a store). In
12681086ce23SFlorian Hahn // either case, we can't add additional instructions to B's group. B
12691086ce23SFlorian Hahn // will only form a group with instructions that it precedes.
12701086ce23SFlorian Hahn break;
12711086ce23SFlorian Hahn }
12721086ce23SFlorian Hahn
12731086ce23SFlorian Hahn // At this point, we've checked for illegal code motion. If either A or B
12741086ce23SFlorian Hahn // isn't strided, there's nothing left to do.
12751086ce23SFlorian Hahn if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
12761086ce23SFlorian Hahn continue;
12771086ce23SFlorian Hahn
12781086ce23SFlorian Hahn // Ignore A if it's already in a group or isn't the same kind of memory
12791086ce23SFlorian Hahn // operation as B.
12801086ce23SFlorian Hahn // Note that mayReadFromMemory() isn't mutually exclusive to
12811086ce23SFlorian Hahn // mayWriteToMemory in the case of atomic loads. We shouldn't see those
12821086ce23SFlorian Hahn // here, canVectorizeMemory() should have returned false - except for the
12831086ce23SFlorian Hahn // case we asked for optimization remarks.
12841086ce23SFlorian Hahn if (isInterleaved(A) ||
12851086ce23SFlorian Hahn (A->mayReadFromMemory() != B->mayReadFromMemory()) ||
12861086ce23SFlorian Hahn (A->mayWriteToMemory() != B->mayWriteToMemory()))
12871086ce23SFlorian Hahn continue;
12881086ce23SFlorian Hahn
12891086ce23SFlorian Hahn // Check rules 1 and 2. Ignore A if its stride or size is different from
12901086ce23SFlorian Hahn // that of B.
12911086ce23SFlorian Hahn if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
12921086ce23SFlorian Hahn continue;
12931086ce23SFlorian Hahn
12941086ce23SFlorian Hahn // Ignore A if the memory object of A and B don't belong to the same
12951086ce23SFlorian Hahn // address space
12961086ce23SFlorian Hahn if (getLoadStoreAddressSpace(A) != getLoadStoreAddressSpace(B))
12971086ce23SFlorian Hahn continue;
12981086ce23SFlorian Hahn
12991086ce23SFlorian Hahn // Calculate the distance from A to B.
13001086ce23SFlorian Hahn const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
13011086ce23SFlorian Hahn PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
13021086ce23SFlorian Hahn if (!DistToB)
13031086ce23SFlorian Hahn continue;
13041086ce23SFlorian Hahn int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
13051086ce23SFlorian Hahn
13061086ce23SFlorian Hahn // Check rule 3. Ignore A if its distance to B is not a multiple of the
13071086ce23SFlorian Hahn // size.
13081086ce23SFlorian Hahn if (DistanceToB % static_cast<int64_t>(DesB.Size))
13091086ce23SFlorian Hahn continue;
13101086ce23SFlorian Hahn
131138bbf81aSDorit Nuzman // All members of a predicated interleave-group must have the same predicate,
131238bbf81aSDorit Nuzman // and currently must reside in the same BB.
131338bbf81aSDorit Nuzman BasicBlock *BlockA = A->getParent();
131438bbf81aSDorit Nuzman BasicBlock *BlockB = B->getParent();
131538bbf81aSDorit Nuzman if ((isPredicated(BlockA) || isPredicated(BlockB)) &&
131638bbf81aSDorit Nuzman (!EnablePredicatedInterleavedMemAccesses || BlockA != BlockB))
13171086ce23SFlorian Hahn continue;
13181086ce23SFlorian Hahn
13191086ce23SFlorian Hahn // The index of A is the index of B plus A's distance to B in multiples
13201086ce23SFlorian Hahn // of the size.
13211086ce23SFlorian Hahn int IndexA =
13221086ce23SFlorian Hahn Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
13231086ce23SFlorian Hahn
13241086ce23SFlorian Hahn // Try to insert A into B's group.
1325837a1b84SGuillaume Chatelet if (Group->insertMember(A, IndexA, DesA.Alignment)) {
13261086ce23SFlorian Hahn LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
13271086ce23SFlorian Hahn << " into the interleave group with" << *B
13281086ce23SFlorian Hahn << '\n');
13291086ce23SFlorian Hahn InterleaveGroupMap[A] = Group;
13301086ce23SFlorian Hahn
13311086ce23SFlorian Hahn // Set the first load in program order as the insert position.
13321086ce23SFlorian Hahn if (A->mayReadFromMemory())
13331086ce23SFlorian Hahn Group->setInsertPos(A);
13341086ce23SFlorian Hahn }
13351086ce23SFlorian Hahn } // Iteration over A accesses.
13361086ce23SFlorian Hahn } // Iteration over B accesses.
13371086ce23SFlorian Hahn
133867278b8aSDorit Nuzman auto InvalidateGroupIfMemberMayWrap = [&](InterleaveGroup<Instruction> *Group,
133967278b8aSDorit Nuzman int Index,
134067278b8aSDorit Nuzman std::string FirstOrLast) -> bool {
134167278b8aSDorit Nuzman Instruction *Member = Group->getMember(Index);
134267278b8aSDorit Nuzman assert(Member && "Group member does not exist");
134367278b8aSDorit Nuzman Value *MemberPtr = getLoadStorePointerOperand(Member);
134445c46734SNikita Popov Type *AccessTy = getLoadStoreType(Member);
134545c46734SNikita Popov if (getPtrStride(PSE, AccessTy, MemberPtr, TheLoop, Strides,
134645c46734SNikita Popov /*Assume=*/false, /*ShouldCheckWrap=*/true))
134767278b8aSDorit Nuzman return false;
134867278b8aSDorit Nuzman LLVM_DEBUG(dbgs() << "LV: Invalidate candidate interleaved group due to "
134967278b8aSDorit Nuzman << FirstOrLast
135067278b8aSDorit Nuzman << " group member potentially pointer-wrapping.\n");
13511086ce23SFlorian Hahn releaseGroup(Group);
135267278b8aSDorit Nuzman return true;
135367278b8aSDorit Nuzman };
135467278b8aSDorit Nuzman
135567278b8aSDorit Nuzman // Remove interleaved groups with gaps whose memory
13561086ce23SFlorian Hahn // accesses may wrap around. We have to revisit the getPtrStride analysis,
13571086ce23SFlorian Hahn // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
13581086ce23SFlorian Hahn // not check wrapping (see documentation there).
13591086ce23SFlorian Hahn // FORNOW we use Assume=false;
13601086ce23SFlorian Hahn // TODO: Change to Assume=true but making sure we don't exceed the threshold
13611086ce23SFlorian Hahn // of runtime SCEV assumptions checks (thereby potentially failing to
13621086ce23SFlorian Hahn // vectorize altogether).
13631086ce23SFlorian Hahn // Additional optional optimizations:
13641086ce23SFlorian Hahn // TODO: If we are peeling the loop and we know that the first pointer doesn't
13651086ce23SFlorian Hahn // wrap then we can deduce that all pointers in the group don't wrap.
13661086ce23SFlorian Hahn // This means that we can forcefully peel the loop in order to only have to
13671086ce23SFlorian Hahn // check the first pointer for no-wrap. When we'll change to use Assume=true
13681086ce23SFlorian Hahn // we'll only need at most one runtime check per interleaved group.
1369a4dc7feeSFlorian Hahn for (auto *Group : LoadGroups) {
13701086ce23SFlorian Hahn // Case 1: A full group. Can Skip the checks; For full groups, if the wide
13711086ce23SFlorian Hahn // load would wrap around the address space we would do a memory access at
13721086ce23SFlorian Hahn // nullptr even without the transformation.
13731086ce23SFlorian Hahn if (Group->getNumMembers() == Group->getFactor())
13741086ce23SFlorian Hahn continue;
13751086ce23SFlorian Hahn
13761086ce23SFlorian Hahn // Case 2: If first and last members of the group don't wrap this implies
13771086ce23SFlorian Hahn // that all the pointers in the group don't wrap.
13781086ce23SFlorian Hahn // So we check only group member 0 (which is always guaranteed to exist),
13791086ce23SFlorian Hahn // and group member Factor - 1; If the latter doesn't exist we rely on
138002a2bb2fSHiroshi Inoue // peeling (if it is a non-reversed accsess -- see Case 3).
138167278b8aSDorit Nuzman if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
13821086ce23SFlorian Hahn continue;
138367278b8aSDorit Nuzman if (Group->getMember(Group->getFactor() - 1))
138467278b8aSDorit Nuzman InvalidateGroupIfMemberMayWrap(Group, Group->getFactor() - 1,
138567278b8aSDorit Nuzman std::string("last"));
138667278b8aSDorit Nuzman else {
13871086ce23SFlorian Hahn // Case 3: A non-reversed interleaved load group with gaps: We need
13881086ce23SFlorian Hahn // to execute at least one scalar epilogue iteration. This will ensure
13891086ce23SFlorian Hahn // we don't speculatively access memory out-of-bounds. We only need
13901086ce23SFlorian Hahn // to look for a member at index factor - 1, since every group must have
13911086ce23SFlorian Hahn // a member at index zero.
13921086ce23SFlorian Hahn if (Group->isReverse()) {
13931086ce23SFlorian Hahn LLVM_DEBUG(
13941086ce23SFlorian Hahn dbgs() << "LV: Invalidate candidate interleaved group due to "
13951086ce23SFlorian Hahn "a reverse access with gaps.\n");
13961086ce23SFlorian Hahn releaseGroup(Group);
13971086ce23SFlorian Hahn continue;
13981086ce23SFlorian Hahn }
13991086ce23SFlorian Hahn LLVM_DEBUG(
14001086ce23SFlorian Hahn dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
14011086ce23SFlorian Hahn RequiresScalarEpilogue = true;
14021086ce23SFlorian Hahn }
14031086ce23SFlorian Hahn }
140467278b8aSDorit Nuzman
140567278b8aSDorit Nuzman for (auto *Group : StoreGroups) {
140667278b8aSDorit Nuzman // Case 1: A full group. Can Skip the checks; For full groups, if the wide
140767278b8aSDorit Nuzman // store would wrap around the address space we would do a memory access at
140867278b8aSDorit Nuzman // nullptr even without the transformation.
140967278b8aSDorit Nuzman if (Group->getNumMembers() == Group->getFactor())
141067278b8aSDorit Nuzman continue;
141167278b8aSDorit Nuzman
141267278b8aSDorit Nuzman // Interleave-store-group with gaps is implemented using masked wide store.
141367278b8aSDorit Nuzman // Remove interleaved store groups with gaps if
141467278b8aSDorit Nuzman // masked-interleaved-accesses are not enabled by the target.
141567278b8aSDorit Nuzman if (!EnablePredicatedInterleavedMemAccesses) {
141667278b8aSDorit Nuzman LLVM_DEBUG(
141767278b8aSDorit Nuzman dbgs() << "LV: Invalidate candidate interleaved store group due "
141867278b8aSDorit Nuzman "to gaps.\n");
141967278b8aSDorit Nuzman releaseGroup(Group);
142067278b8aSDorit Nuzman continue;
142167278b8aSDorit Nuzman }
142267278b8aSDorit Nuzman
142367278b8aSDorit Nuzman // Case 2: If first and last members of the group don't wrap this implies
142467278b8aSDorit Nuzman // that all the pointers in the group don't wrap.
142567278b8aSDorit Nuzman // So we check only group member 0 (which is always guaranteed to exist),
142667278b8aSDorit Nuzman // and the last group member. Case 3 (scalar epilog) is not relevant for
142767278b8aSDorit Nuzman // stores with gaps, which are implemented with masked-store (rather than
142867278b8aSDorit Nuzman // speculative access, as in loads).
142967278b8aSDorit Nuzman if (InvalidateGroupIfMemberMayWrap(Group, 0, std::string("first")))
143067278b8aSDorit Nuzman continue;
143167278b8aSDorit Nuzman for (int Index = Group->getFactor() - 1; Index > 0; Index--)
143267278b8aSDorit Nuzman if (Group->getMember(Index)) {
143367278b8aSDorit Nuzman InvalidateGroupIfMemberMayWrap(Group, Index, std::string("last"));
143467278b8aSDorit Nuzman break;
143567278b8aSDorit Nuzman }
143667278b8aSDorit Nuzman }
14371086ce23SFlorian Hahn }
14383ec99fe2SDorit Nuzman
invalidateGroupsRequiringScalarEpilogue()14393ec99fe2SDorit Nuzman void InterleavedAccessInfo::invalidateGroupsRequiringScalarEpilogue() {
14403ec99fe2SDorit Nuzman // If no group had triggered the requirement to create an epilogue loop,
14413ec99fe2SDorit Nuzman // there is nothing to do.
14423ec99fe2SDorit Nuzman if (!requiresScalarEpilogue())
14433ec99fe2SDorit Nuzman return;
14443ec99fe2SDorit Nuzman
14452737362eSFlorian Hahn bool ReleasedGroup = false;
14462737362eSFlorian Hahn // Release groups requiring scalar epilogues. Note that this also removes them
14472737362eSFlorian Hahn // from InterleaveGroups.
14482737362eSFlorian Hahn for (auto *Group : make_early_inc_range(InterleaveGroups)) {
14492737362eSFlorian Hahn if (!Group->requiresScalarEpilogue())
14502737362eSFlorian Hahn continue;
14513ec99fe2SDorit Nuzman LLVM_DEBUG(
14523ec99fe2SDorit Nuzman dbgs()
14533ec99fe2SDorit Nuzman << "LV: Invalidate candidate interleaved group due to gaps that "
145434da6dd6SDorit Nuzman "require a scalar epilogue (not allowed under optsize) and cannot "
145534da6dd6SDorit Nuzman "be masked (not enabled). \n");
14562737362eSFlorian Hahn releaseGroup(Group);
14572737362eSFlorian Hahn ReleasedGroup = true;
14583ec99fe2SDorit Nuzman }
14592737362eSFlorian Hahn assert(ReleasedGroup && "At least one group must be invalidated, as a "
14602737362eSFlorian Hahn "scalar epilogue was required");
14612737362eSFlorian Hahn (void)ReleasedGroup;
14623ec99fe2SDorit Nuzman RequiresScalarEpilogue = false;
14633ec99fe2SDorit Nuzman }
1464a4dc7feeSFlorian Hahn
146586ed347bSFlorian Hahn template <typename InstT>
addMetadata(InstT * NewInst) const146686ed347bSFlorian Hahn void InterleaveGroup<InstT>::addMetadata(InstT *NewInst) const {
146786ed347bSFlorian Hahn llvm_unreachable("addMetadata can only be used for Instruction");
146886ed347bSFlorian Hahn }
146986ed347bSFlorian Hahn
147086ed347bSFlorian Hahn namespace llvm {
1471a4dc7feeSFlorian Hahn template <>
addMetadata(Instruction * NewInst) const1472a4dc7feeSFlorian Hahn void InterleaveGroup<Instruction>::addMetadata(Instruction *NewInst) const {
1473a4dc7feeSFlorian Hahn SmallVector<Value *, 4> VL;
1474a4dc7feeSFlorian Hahn std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
1475a4dc7feeSFlorian Hahn [](std::pair<int, Instruction *> p) { return p.second; });
1476a4dc7feeSFlorian Hahn propagateMetadata(NewInst, VL);
1477a4dc7feeSFlorian Hahn }
1478a4dc7feeSFlorian Hahn }
1479e9a06e06SFrancesco Petrogalli
mangleTLIVectorName(StringRef VectorName,StringRef ScalarName,unsigned numArgs,ElementCount VF)14807cc3769aSAnna Thomas std::string VFABI::mangleTLIVectorName(StringRef VectorName,
14817cc3769aSAnna Thomas StringRef ScalarName, unsigned numArgs,
14829700228aSDavid Sherwood ElementCount VF) {
14837cc3769aSAnna Thomas SmallString<256> Buffer;
14847cc3769aSAnna Thomas llvm::raw_svector_ostream Out(Buffer);
14859700228aSDavid Sherwood Out << "_ZGV" << VFABI::_LLVM_ << "N";
14869700228aSDavid Sherwood if (VF.isScalable())
14879700228aSDavid Sherwood Out << 'x';
14889700228aSDavid Sherwood else
14899700228aSDavid Sherwood Out << VF.getFixedValue();
14907cc3769aSAnna Thomas for (unsigned I = 0; I < numArgs; ++I)
14917cc3769aSAnna Thomas Out << "v";
14927cc3769aSAnna Thomas Out << "_" << ScalarName << "(" << VectorName << ")";
14937cc3769aSAnna Thomas return std::string(Out.str());
14947cc3769aSAnna Thomas }
14957cc3769aSAnna Thomas
getVectorVariantNames(const CallInst & CI,SmallVectorImpl<std::string> & VariantMappings)1496e9a06e06SFrancesco Petrogalli void VFABI::getVectorVariantNames(
1497e9a06e06SFrancesco Petrogalli const CallInst &CI, SmallVectorImpl<std::string> &VariantMappings) {
14987557d6c8SArthur Eubanks const StringRef S = CI.getFnAttr(VFABI::MappingsAttrName).getValueAsString();
1499d6de5f12SFrancesco Petrogalli if (S.empty())
1500d6de5f12SFrancesco Petrogalli return;
1501d6de5f12SFrancesco Petrogalli
1502e9a06e06SFrancesco Petrogalli SmallVector<StringRef, 8> ListAttr;
1503e9a06e06SFrancesco Petrogalli S.split(ListAttr, ",");
1504e9a06e06SFrancesco Petrogalli
1505601b3a13SKazu Hirata for (const auto &S : SetVector<StringRef>(ListAttr.begin(), ListAttr.end())) {
1506e9a06e06SFrancesco Petrogalli #ifndef NDEBUG
150766c120f0SFrancesco Petrogalli LLVM_DEBUG(dbgs() << "VFABI: adding mapping '" << S << "'\n");
1508623cff81SFrancesco Petrogalli Optional<VFInfo> Info = VFABI::tryDemangleForVFABI(S, *(CI.getModule()));
1509a7938c74SKazu Hirata assert(Info && "Invalid name for a VFABI variant.");
1510611ffcf4SKazu Hirata assert(CI.getModule()->getFunction(Info.value().VectorName) &&
1511e9a06e06SFrancesco Petrogalli "Vector function is missing.");
1512e9a06e06SFrancesco Petrogalli #endif
1513adcd0268SBenjamin Kramer VariantMappings.push_back(std::string(S));
1514e9a06e06SFrancesco Petrogalli }
1515e9a06e06SFrancesco Petrogalli }
1516eac93757SFrancesco Petrogalli
hasValidParameterList() const1517eac93757SFrancesco Petrogalli bool VFShape::hasValidParameterList() const {
1518eac93757SFrancesco Petrogalli for (unsigned Pos = 0, NumParams = Parameters.size(); Pos < NumParams;
1519eac93757SFrancesco Petrogalli ++Pos) {
1520eac93757SFrancesco Petrogalli assert(Parameters[Pos].ParamPos == Pos && "Broken parameter list.");
1521eac93757SFrancesco Petrogalli
1522eac93757SFrancesco Petrogalli switch (Parameters[Pos].ParamKind) {
1523eac93757SFrancesco Petrogalli default: // Nothing to check.
1524eac93757SFrancesco Petrogalli break;
1525eac93757SFrancesco Petrogalli case VFParamKind::OMP_Linear:
1526eac93757SFrancesco Petrogalli case VFParamKind::OMP_LinearRef:
1527eac93757SFrancesco Petrogalli case VFParamKind::OMP_LinearVal:
1528eac93757SFrancesco Petrogalli case VFParamKind::OMP_LinearUVal:
1529eac93757SFrancesco Petrogalli // Compile time linear steps must be non-zero.
1530eac93757SFrancesco Petrogalli if (Parameters[Pos].LinearStepOrPos == 0)
1531eac93757SFrancesco Petrogalli return false;
1532eac93757SFrancesco Petrogalli break;
1533eac93757SFrancesco Petrogalli case VFParamKind::OMP_LinearPos:
1534eac93757SFrancesco Petrogalli case VFParamKind::OMP_LinearRefPos:
1535eac93757SFrancesco Petrogalli case VFParamKind::OMP_LinearValPos:
1536eac93757SFrancesco Petrogalli case VFParamKind::OMP_LinearUValPos:
1537eac93757SFrancesco Petrogalli // The runtime linear step must be referring to some other
1538eac93757SFrancesco Petrogalli // parameters in the signature.
1539eac93757SFrancesco Petrogalli if (Parameters[Pos].LinearStepOrPos >= int(NumParams))
1540eac93757SFrancesco Petrogalli return false;
1541eac93757SFrancesco Petrogalli // The linear step parameter must be marked as uniform.
1542eac93757SFrancesco Petrogalli if (Parameters[Parameters[Pos].LinearStepOrPos].ParamKind !=
1543eac93757SFrancesco Petrogalli VFParamKind::OMP_Uniform)
1544eac93757SFrancesco Petrogalli return false;
1545eac93757SFrancesco Petrogalli // The linear step parameter can't point at itself.
1546eac93757SFrancesco Petrogalli if (Parameters[Pos].LinearStepOrPos == int(Pos))
1547eac93757SFrancesco Petrogalli return false;
1548eac93757SFrancesco Petrogalli break;
1549eac93757SFrancesco Petrogalli case VFParamKind::GlobalPredicate:
1550eac93757SFrancesco Petrogalli // The global predicate must be the unique. Can be placed anywhere in the
1551eac93757SFrancesco Petrogalli // signature.
1552eac93757SFrancesco Petrogalli for (unsigned NextPos = Pos + 1; NextPos < NumParams; ++NextPos)
1553eac93757SFrancesco Petrogalli if (Parameters[NextPos].ParamKind == VFParamKind::GlobalPredicate)
1554eac93757SFrancesco Petrogalli return false;
1555eac93757SFrancesco Petrogalli break;
1556eac93757SFrancesco Petrogalli }
1557eac93757SFrancesco Petrogalli }
1558eac93757SFrancesco Petrogalli return true;
1559eac93757SFrancesco Petrogalli }
1560