1 //===----------- VectorUtils.cpp - Vectorizer utility functions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines vectorizer utilities.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/EquivalenceClasses.h"
15 #include "llvm/Analysis/DemandedBits.h"
16 #include "llvm/Analysis/LoopInfo.h"
17 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
18 #include "llvm/Analysis/ScalarEvolution.h"
19 #include "llvm/Analysis/TargetTransformInfo.h"
20 #include "llvm/Analysis/ValueTracking.h"
21 #include "llvm/Analysis/VectorUtils.h"
22 #include "llvm/IR/GetElementPtrTypeIterator.h"
23 #include "llvm/IR/PatternMatch.h"
24 #include "llvm/IR/Value.h"
25 #include "llvm/IR/Constants.h"
28 using namespace llvm::PatternMatch;
30 /// \brief Identify if the intrinsic is trivially vectorizable.
31 /// This method returns true if the intrinsic's argument types are all
32 /// scalars for the scalar form of the intrinsic and all vectors for
33 /// the vector form of the intrinsic.
34 bool llvm::isTriviallyVectorizable(Intrinsic::ID ID) {
42 case Intrinsic::log10:
45 case Intrinsic::minnum:
46 case Intrinsic::maxnum:
47 case Intrinsic::copysign:
48 case Intrinsic::floor:
50 case Intrinsic::trunc:
52 case Intrinsic::nearbyint:
53 case Intrinsic::round:
54 case Intrinsic::bswap:
55 case Intrinsic::bitreverse:
56 case Intrinsic::ctpop:
59 case Intrinsic::fmuladd:
69 /// \brief Identifies if the intrinsic has a scalar operand. It check for
70 /// ctlz,cttz and powi special intrinsics whose argument is scalar.
71 bool llvm::hasVectorInstrinsicScalarOpd(Intrinsic::ID ID,
72 unsigned ScalarOpdIdx) {
77 return (ScalarOpdIdx == 1);
83 /// \brief Returns intrinsic ID for call.
84 /// For the input call instruction it finds mapping intrinsic and returns
85 /// its ID, in case it does not found it return not_intrinsic.
86 Intrinsic::ID llvm::getVectorIntrinsicIDForCall(const CallInst *CI,
87 const TargetLibraryInfo *TLI) {
88 Intrinsic::ID ID = getIntrinsicForCallSite(CI, TLI);
89 if (ID == Intrinsic::not_intrinsic)
90 return Intrinsic::not_intrinsic;
92 if (isTriviallyVectorizable(ID) || ID == Intrinsic::lifetime_start ||
93 ID == Intrinsic::lifetime_end || ID == Intrinsic::assume)
95 return Intrinsic::not_intrinsic;
98 /// \brief Find the operand of the GEP that should be checked for consecutive
99 /// stores. This ignores trailing indices that have no effect on the final
101 unsigned llvm::getGEPInductionOperand(const GetElementPtrInst *Gep) {
102 const DataLayout &DL = Gep->getModule()->getDataLayout();
103 unsigned LastOperand = Gep->getNumOperands() - 1;
104 unsigned GEPAllocSize = DL.getTypeAllocSize(Gep->getResultElementType());
106 // Walk backwards and try to peel off zeros.
107 while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
108 // Find the type we're currently indexing into.
109 gep_type_iterator GEPTI = gep_type_begin(Gep);
110 std::advance(GEPTI, LastOperand - 2);
112 // If it's a type with the same allocation size as the result of the GEP we
113 // can peel off the zero index.
114 if (DL.getTypeAllocSize(GEPTI.getIndexedType()) != GEPAllocSize)
122 /// \brief If the argument is a GEP, then returns the operand identified by
123 /// getGEPInductionOperand. However, if there is some other non-loop-invariant
124 /// operand, it returns that instead.
125 Value *llvm::stripGetElementPtr(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
126 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
130 unsigned InductionOperand = getGEPInductionOperand(GEP);
132 // Check that all of the gep indices are uniform except for our induction
134 for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
135 if (i != InductionOperand &&
136 !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
138 return GEP->getOperand(InductionOperand);
141 /// \brief If a value has only one user that is a CastInst, return it.
142 Value *llvm::getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
143 Value *UniqueCast = nullptr;
144 for (User *U : Ptr->users()) {
145 CastInst *CI = dyn_cast<CastInst>(U);
146 if (CI && CI->getType() == Ty) {
156 /// \brief Get the stride of a pointer access in a loop. Looks for symbolic
157 /// strides "a[i*stride]". Returns the symbolic stride, or null otherwise.
158 Value *llvm::getStrideFromPointer(Value *Ptr, ScalarEvolution *SE, Loop *Lp) {
159 auto *PtrTy = dyn_cast<PointerType>(Ptr->getType());
160 if (!PtrTy || PtrTy->isAggregateType())
163 // Try to remove a gep instruction to make the pointer (actually index at this
164 // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
165 // pointer, otherwise, we are analyzing the index.
166 Value *OrigPtr = Ptr;
168 // The size of the pointer access.
169 int64_t PtrAccessSize = 1;
171 Ptr = stripGetElementPtr(Ptr, SE, Lp);
172 const SCEV *V = SE->getSCEV(Ptr);
176 while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
179 const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
183 V = S->getStepRecurrence(*SE);
187 // Strip off the size of access multiplication if we are still analyzing the
189 if (OrigPtr == Ptr) {
190 if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
191 if (M->getOperand(0)->getSCEVType() != scConstant)
194 const APInt &APStepVal = cast<SCEVConstant>(M->getOperand(0))->getAPInt();
196 // Huge step value - give up.
197 if (APStepVal.getBitWidth() > 64)
200 int64_t StepVal = APStepVal.getSExtValue();
201 if (PtrAccessSize != StepVal)
203 V = M->getOperand(1);
208 Type *StripedOffRecurrenceCast = nullptr;
209 if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
210 StripedOffRecurrenceCast = C->getType();
214 // Look for the loop invariant symbolic value.
215 const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
219 Value *Stride = U->getValue();
220 if (!Lp->isLoopInvariant(Stride))
223 // If we have stripped off the recurrence cast we have to make sure that we
224 // return the value that is used in this loop so that we can replace it later.
225 if (StripedOffRecurrenceCast)
226 Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
231 /// \brief Given a vector and an element number, see if the scalar value is
232 /// already around as a register, for example if it were inserted then extracted
234 Value *llvm::findScalarElement(Value *V, unsigned EltNo) {
235 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
236 VectorType *VTy = cast<VectorType>(V->getType());
237 unsigned Width = VTy->getNumElements();
238 if (EltNo >= Width) // Out of range access.
239 return UndefValue::get(VTy->getElementType());
241 if (Constant *C = dyn_cast<Constant>(V))
242 return C->getAggregateElement(EltNo);
244 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
245 // If this is an insert to a variable element, we don't know what it is.
246 if (!isa<ConstantInt>(III->getOperand(2)))
248 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
250 // If this is an insert to the element we are looking for, return the
253 return III->getOperand(1);
255 // Otherwise, the insertelement doesn't modify the value, recurse on its
257 return findScalarElement(III->getOperand(0), EltNo);
260 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
261 unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
262 int InEl = SVI->getMaskValue(EltNo);
264 return UndefValue::get(VTy->getElementType());
265 if (InEl < (int)LHSWidth)
266 return findScalarElement(SVI->getOperand(0), InEl);
267 return findScalarElement(SVI->getOperand(1), InEl - LHSWidth);
270 // Extract a value from a vector add operation with a constant zero.
271 Value *Val = nullptr; Constant *Con = nullptr;
272 if (match(V, m_Add(m_Value(Val), m_Constant(Con))))
273 if (Constant *Elt = Con->getAggregateElement(EltNo))
274 if (Elt->isNullValue())
275 return findScalarElement(Val, EltNo);
277 // Otherwise, we don't know.
281 /// \brief Get splat value if the input is a splat vector or return nullptr.
282 /// This function is not fully general. It checks only 2 cases:
283 /// the input value is (1) a splat constants vector or (2) a sequence
284 /// of instructions that broadcast a single value into a vector.
286 const llvm::Value *llvm::getSplatValue(const Value *V) {
288 if (auto *C = dyn_cast<Constant>(V))
289 if (isa<VectorType>(V->getType()))
290 return C->getSplatValue();
292 auto *ShuffleInst = dyn_cast<ShuffleVectorInst>(V);
295 // All-zero (or undef) shuffle mask elements.
296 for (int MaskElt : ShuffleInst->getShuffleMask())
297 if (MaskElt != 0 && MaskElt != -1)
299 // The first shuffle source is 'insertelement' with index 0.
300 auto *InsertEltInst =
301 dyn_cast<InsertElementInst>(ShuffleInst->getOperand(0));
302 if (!InsertEltInst || !isa<ConstantInt>(InsertEltInst->getOperand(2)) ||
303 !cast<ConstantInt>(InsertEltInst->getOperand(2))->isNullValue())
306 return InsertEltInst->getOperand(1);
309 MapVector<Instruction *, uint64_t>
310 llvm::computeMinimumValueSizes(ArrayRef<BasicBlock *> Blocks, DemandedBits &DB,
311 const TargetTransformInfo *TTI) {
313 // DemandedBits will give us every value's live-out bits. But we want
314 // to ensure no extra casts would need to be inserted, so every DAG
315 // of connected values must have the same minimum bitwidth.
316 EquivalenceClasses<Value *> ECs;
317 SmallVector<Value *, 16> Worklist;
318 SmallPtrSet<Value *, 4> Roots;
319 SmallPtrSet<Value *, 16> Visited;
320 DenseMap<Value *, uint64_t> DBits;
321 SmallPtrSet<Instruction *, 4> InstructionSet;
322 MapVector<Instruction *, uint64_t> MinBWs;
324 // Determine the roots. We work bottom-up, from truncs or icmps.
325 bool SeenExtFromIllegalType = false;
326 for (auto *BB : Blocks)
327 for (auto &I : *BB) {
328 InstructionSet.insert(&I);
330 if (TTI && (isa<ZExtInst>(&I) || isa<SExtInst>(&I)) &&
331 !TTI->isTypeLegal(I.getOperand(0)->getType()))
332 SeenExtFromIllegalType = true;
334 // Only deal with non-vector integers up to 64-bits wide.
335 if ((isa<TruncInst>(&I) || isa<ICmpInst>(&I)) &&
336 !I.getType()->isVectorTy() &&
337 I.getOperand(0)->getType()->getScalarSizeInBits() <= 64) {
338 // Don't make work for ourselves. If we know the loaded type is legal,
339 // don't add it to the worklist.
340 if (TTI && isa<TruncInst>(&I) && TTI->isTypeLegal(I.getType()))
343 Worklist.push_back(&I);
348 if (Worklist.empty() || (TTI && !SeenExtFromIllegalType))
351 // Now proceed breadth-first, unioning values together.
352 while (!Worklist.empty()) {
353 Value *Val = Worklist.pop_back_val();
354 Value *Leader = ECs.getOrInsertLeaderValue(Val);
356 if (Visited.count(Val))
360 // Non-instructions terminate a chain successfully.
361 if (!isa<Instruction>(Val))
363 Instruction *I = cast<Instruction>(Val);
365 // If we encounter a type that is larger than 64 bits, we can't represent
367 if (DB.getDemandedBits(I).getBitWidth() > 64)
368 return MapVector<Instruction *, uint64_t>();
370 uint64_t V = DB.getDemandedBits(I).getZExtValue();
374 // Casts, loads and instructions outside of our range terminate a chain
376 if (isa<SExtInst>(I) || isa<ZExtInst>(I) || isa<LoadInst>(I) ||
377 !InstructionSet.count(I))
380 // Unsafe casts terminate a chain unsuccessfully. We can't do anything
381 // useful with bitcasts, ptrtoints or inttoptrs and it'd be unsafe to
382 // transform anything that relies on them.
383 if (isa<BitCastInst>(I) || isa<PtrToIntInst>(I) || isa<IntToPtrInst>(I) ||
384 !I->getType()->isIntegerTy()) {
385 DBits[Leader] |= ~0ULL;
389 // We don't modify the types of PHIs. Reductions will already have been
390 // truncated if possible, and inductions' sizes will have been chosen by
395 if (DBits[Leader] == ~0ULL)
396 // All bits demanded, no point continuing.
399 for (Value *O : cast<User>(I)->operands()) {
400 ECs.unionSets(Leader, O);
401 Worklist.push_back(O);
405 // Now we've discovered all values, walk them to see if there are
406 // any users we didn't see. If there are, we can't optimize that
408 for (auto &I : DBits)
409 for (auto *U : I.first->users())
410 if (U->getType()->isIntegerTy() && DBits.count(U) == 0)
411 DBits[ECs.getOrInsertLeaderValue(I.first)] |= ~0ULL;
413 for (auto I = ECs.begin(), E = ECs.end(); I != E; ++I) {
414 uint64_t LeaderDemandedBits = 0;
415 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
416 LeaderDemandedBits |= DBits[*MI];
418 uint64_t MinBW = (sizeof(LeaderDemandedBits) * 8) -
419 llvm::countLeadingZeros(LeaderDemandedBits);
420 // Round up to a power of 2
421 if (!isPowerOf2_64((uint64_t)MinBW))
422 MinBW = NextPowerOf2(MinBW);
424 // We don't modify the types of PHIs. Reductions will already have been
425 // truncated if possible, and inductions' sizes will have been chosen by
427 // If we are required to shrink a PHI, abandon this entire equivalence class.
429 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI)
430 if (isa<PHINode>(*MI) && MinBW < (*MI)->getType()->getScalarSizeInBits()) {
437 for (auto MI = ECs.member_begin(I), ME = ECs.member_end(); MI != ME; ++MI) {
438 if (!isa<Instruction>(*MI))
440 Type *Ty = (*MI)->getType();
441 if (Roots.count(*MI))
442 Ty = cast<Instruction>(*MI)->getOperand(0)->getType();
443 if (MinBW < Ty->getScalarSizeInBits())
444 MinBWs[cast<Instruction>(*MI)] = MinBW;
451 /// \returns \p I after propagating metadata from \p VL.
452 Instruction *llvm::propagateMetadata(Instruction *Inst, ArrayRef<Value *> VL) {
453 Instruction *I0 = cast<Instruction>(VL[0]);
454 SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
455 I0->getAllMetadataOtherThanDebugLoc(Metadata);
458 {LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
459 LLVMContext::MD_noalias, LLVMContext::MD_fpmath,
460 LLVMContext::MD_nontemporal, LLVMContext::MD_invariant_load}) {
461 MDNode *MD = I0->getMetadata(Kind);
463 for (int J = 1, E = VL.size(); MD && J != E; ++J) {
464 const Instruction *IJ = cast<Instruction>(VL[J]);
465 MDNode *IMD = IJ->getMetadata(Kind);
467 case LLVMContext::MD_tbaa:
468 MD = MDNode::getMostGenericTBAA(MD, IMD);
470 case LLVMContext::MD_alias_scope:
471 MD = MDNode::getMostGenericAliasScope(MD, IMD);
473 case LLVMContext::MD_fpmath:
474 MD = MDNode::getMostGenericFPMath(MD, IMD);
476 case LLVMContext::MD_noalias:
477 case LLVMContext::MD_nontemporal:
478 case LLVMContext::MD_invariant_load:
479 MD = MDNode::intersect(MD, IMD);
482 llvm_unreachable("unhandled metadata");
486 Inst->setMetadata(Kind, MD);
492 Constant *llvm::createInterleaveMask(IRBuilder<> &Builder, unsigned VF,
494 SmallVector<Constant *, 16> Mask;
495 for (unsigned i = 0; i < VF; i++)
496 for (unsigned j = 0; j < NumVecs; j++)
497 Mask.push_back(Builder.getInt32(j * VF + i));
499 return ConstantVector::get(Mask);
502 Constant *llvm::createStrideMask(IRBuilder<> &Builder, unsigned Start,
503 unsigned Stride, unsigned VF) {
504 SmallVector<Constant *, 16> Mask;
505 for (unsigned i = 0; i < VF; i++)
506 Mask.push_back(Builder.getInt32(Start + i * Stride));
508 return ConstantVector::get(Mask);
511 Constant *llvm::createSequentialMask(IRBuilder<> &Builder, unsigned Start,
512 unsigned NumInts, unsigned NumUndefs) {
513 SmallVector<Constant *, 16> Mask;
514 for (unsigned i = 0; i < NumInts; i++)
515 Mask.push_back(Builder.getInt32(Start + i));
517 Constant *Undef = UndefValue::get(Builder.getInt32Ty());
518 for (unsigned i = 0; i < NumUndefs; i++)
519 Mask.push_back(Undef);
521 return ConstantVector::get(Mask);
524 /// A helper function for concatenating vectors. This function concatenates two
525 /// vectors having the same element type. If the second vector has fewer
526 /// elements than the first, it is padded with undefs.
527 static Value *concatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
529 VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
530 VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
531 assert(VecTy1 && VecTy2 &&
532 VecTy1->getScalarType() == VecTy2->getScalarType() &&
533 "Expect two vectors with the same element type");
535 unsigned NumElts1 = VecTy1->getNumElements();
536 unsigned NumElts2 = VecTy2->getNumElements();
537 assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
539 if (NumElts1 > NumElts2) {
540 // Extend with UNDEFs.
542 createSequentialMask(Builder, 0, NumElts2, NumElts1 - NumElts2);
543 V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
546 Constant *Mask = createSequentialMask(Builder, 0, NumElts1 + NumElts2, 0);
547 return Builder.CreateShuffleVector(V1, V2, Mask);
550 Value *llvm::concatenateVectors(IRBuilder<> &Builder, ArrayRef<Value *> Vecs) {
551 unsigned NumVecs = Vecs.size();
552 assert(NumVecs > 1 && "Should be at least two vectors");
554 SmallVector<Value *, 8> ResList;
555 ResList.append(Vecs.begin(), Vecs.end());
557 SmallVector<Value *, 8> TmpList;
558 for (unsigned i = 0; i < NumVecs - 1; i += 2) {
559 Value *V0 = ResList[i], *V1 = ResList[i + 1];
560 assert((V0->getType() == V1->getType() || i == NumVecs - 2) &&
561 "Only the last vector may have a different type");
563 TmpList.push_back(concatenateTwoVectors(Builder, V0, V1));
566 // Push the last vector if the total number of vectors is odd.
567 if (NumVecs % 2 != 0)
568 TmpList.push_back(ResList[NumVecs - 1]);
571 NumVecs = ResList.size();
572 } while (NumVecs > 1);