LLVM 24.0.0git
SLPUtils.cpp
Go to the documentation of this file.
1//===- SLPUtils.cpp - SLP Vectorizer free utility helpers -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "SLPUtils.h"
10#include "SLPMemoryUtils.h"
11
12#include "llvm/ADT/APInt.h"
13#include "llvm/ADT/STLExtras.h"
14#include "llvm/ADT/Sequence.h"
21#include "llvm/IR/Constants.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/DebugInfo.h"
24#include "llvm/IR/DebugLoc.h"
26#include "llvm/IR/Dominators.h"
27#include "llvm/IR/IRBuilder.h"
36
37#include <algorithm>
38#include <numeric>
39#include <optional>
40#include <string>
41#include <type_traits>
42
43using namespace llvm;
44using namespace llvm::PatternMatch;
45
46namespace llvm::slpvectorizer {
47
51
52Constant *getReassocIdentity(unsigned Opcode, Type *Ty, bool Negated) {
53 // Subtracting -0.0 turns a -0.0 total into +0.0.
54 if (Negated && Opcode == Instruction::FAdd)
55 Opcode = Instruction::FSub;
56 return ConstantExpr::getBinOpIdentity(Opcode, Ty, /*AllowRHSConstant=*/true);
57}
58
59bool isBinOpIdentityConstant(const Value *V, unsigned Opcode, bool Negated) {
61 V == getReassocIdentity(Opcode, V->getType(), Negated);
62}
63
65 const BinaryOperator *BO;
66 return match(V, m_BinOp(BO)) && BO->getType()->isIntOrIntVectorTy() &&
67 !BO->isShift() && !BO->isIntDivRem();
68}
69
72 return nullptr;
73 for (const Value *Op : cast<BinaryOperator>(V)->operands())
74 if (const auto *LI = dyn_cast<LoadInst>(Op))
75 return LI;
76 return nullptr;
77}
78
79unsigned getReassocCombineOpcode(unsigned Opcode) {
80 switch (Opcode) {
81 case Instruction::Sub:
82 return Instruction::Add;
83 case Instruction::FSub:
84 return Instruction::FAdd;
85 default:
86 return Opcode;
87 }
88}
89
91 if (I->getOpcode() == Instruction::Sub)
92 return true;
93 if (I->getOpcode() == Instruction::FSub)
94 return I->hasAllowReassoc();
95 return I->isAssociative();
96}
97
99 auto *I = dyn_cast<Instruction>(V);
100 // Non-instructions are vector-like only if they are undef.
101 if (!I)
102 return isa<UndefValue>(V);
103 switch (I->getOpcode()) {
104 case Instruction::ExtractValue:
105 case Instruction::InsertValue:
106 return true;
107 case Instruction::ExtractElement:
108 return isa<FixedVectorType>(I->getOperand(0)->getType()) &&
109 isConstant(I->getOperand(1));
110 case Instruction::InsertElement:
111 return isa<FixedVectorType>(I->getOperand(0)->getType()) &&
112 isConstant(I->getOperand(2));
113 default:
114 return false;
115 }
116}
117
118unsigned getNumElements(Type *Ty) {
120 "ScalableVectorType is not supported.");
121 if (isVectorizedTy(Ty))
123 return 1;
124}
125
126unsigned getPartNumElems(unsigned Size, unsigned NumParts) {
127 return std::min<unsigned>(Size, bit_ceil(divideCeil(Size, NumParts)));
128}
129
130unsigned getNumElems(unsigned Size, unsigned PartNumElems, unsigned Part) {
131 return std::min<unsigned>(PartNumElems, Size - Part * PartNumElems);
132}
133
134#if !defined(NDEBUG)
135std::string shortBundleName(ArrayRef<Value *> VL, int Idx) {
136 std::string Result;
137 raw_string_ostream OS(Result);
138 if (Idx >= 0)
139 OS << "Idx: " << Idx << ", ";
140 OS << "n=" << VL.size() << " [" << *VL.front() << ", ..]";
141 return Result;
142}
143#endif
144
146 auto *It = find_if(VL, IsaPred<Instruction>);
147 if (It == VL.end())
148 return false;
151 return true;
152
153 BasicBlock *BB = I0->getParent();
154 for (Value *V : make_filter_range(iterator_range(It, VL.end()), [](Value *V) {
155 return !isa<PoisonValue>(V);
156 })) {
157 auto *II = dyn_cast<Instruction>(V);
158 if (!II)
159 return false;
160
161 if (BB != II->getParent())
162 return false;
163 }
164 return true;
165}
166
168 // Constant expressions and globals can't be vectorized like normal integer/FP
169 // constants.
170 return all_of(VL, isConstant);
171}
172
174 Value *FirstNonUndef = nullptr;
175 for (Value *V :
176 make_filter_range(VL, [](Value *V) { return !isa<UndefValue>(V); })) {
177 if (!FirstNonUndef) {
178 FirstNonUndef = V;
179 continue;
180 }
181 if (V != FirstNonUndef)
182 return false;
183 }
184 return FirstNonUndef != nullptr;
185}
186
188 if (LHS == RHS)
189 return RHS;
190 if ((LHS == Intrinsic::fma || LHS == Intrinsic::fmuladd) &&
191 (RHS == Intrinsic::fma || RHS == Intrinsic::fmuladd))
192 return Intrinsic::fma;
194}
195
196bool isCommutative(const Instruction *I, const Value *ValWithUses,
197 bool IsCopyable) {
198 // The trunc X to i1 lanes of a compare have the single operand X.
199 if (auto *Cmp = dyn_cast<CmpInst>(I))
200 return isa<CmpInst>(ValWithUses) && Cmp->isCommutative();
201 if (auto *BO = dyn_cast<BinaryOperator>(I))
202 return BO->isCommutative() ||
203 (BO->getOpcode() == Instruction::Sub && ValWithUses->hasUseList() &&
204 !ValWithUses->hasNUsesOrMore(UsesLimit) &&
205 all_of(
206 ValWithUses->uses(),
207 [&](const Use &U) {
208 // Commutative, if icmp eq/ne sub, 0
209 CmpPredicate Pred;
210 if (match(U.getUser(),
211 m_ICmp(Pred, m_Specific(U.get()), m_Zero())) &&
212 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE))
213 return true;
214 // Commutative, if abs(sub nsw, true) or abs(sub, false).
215 // A lane without wrap flags, like an or converted to sub,
216 // does not clear nsw of the vector sub.
217 ConstantInt *Flag;
218 auto *I = dyn_cast<OverflowingBinaryOperator>(U.get());
219 return match(U.getUser(),
220 m_Intrinsic<Intrinsic::abs>(
221 m_Specific(U.get()), m_ConstantInt(Flag))) &&
222 ((!IsCopyable && I && !I->hasNoSignedWrap()) ||
223 Flag->isOne());
224 })) ||
225 (BO->getOpcode() == Instruction::FSub && ValWithUses->hasUseList() &&
226 !ValWithUses->hasNUsesOrMore(UsesLimit) &&
227 all_of(ValWithUses->uses(), [](const Use &U) {
228 return match(U.getUser(),
229 m_Intrinsic<Intrinsic::fabs>(m_Specific(U.get())));
230 }));
231 return I->isCommutative();
232}
233
234bool isCommutative(const Instruction *I) { return isCommutative(I, I); }
235
236bool isCommutableOperand(const Instruction *I, Value *ValWithUses, unsigned Op,
237 bool IsCopyable) {
238 assert(isCommutative(I, ValWithUses, IsCopyable) &&
239 "The instruction is not commutative.");
240 if (isa<CmpInst>(I))
241 return true;
242 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
243 switch (BO->getOpcode()) {
244 case Instruction::Sub:
245 case Instruction::FSub:
246 return true;
247 default:
248 break;
249 }
250 }
251 return I->isCommutableOperand(Op);
252}
253
256 // IntrinsicInst::isCommutative returns true if swapping the first "two"
257 // arguments to the intrinsic produces the same result.
258 constexpr unsigned IntrinsicNumOperands = 2;
259 return IntrinsicNumOperands;
260 }
261 return I->getNumOperands();
262}
263
264std::optional<unsigned> getElementIndex(const Value *Inst, unsigned Offset) {
265 if (auto Index = getInsertExtractIndex<InsertElementInst>(Inst, Offset))
266 return Index;
268 return Index;
269
270 unsigned Index = Offset;
271
272 const auto *IV = dyn_cast<InsertValueInst>(Inst);
273 if (!IV)
274 return std::nullopt;
275
276 Type *CurrentType = IV->getType();
277 for (unsigned I : IV->indices()) {
278 if (const auto *ST = dyn_cast<StructType>(CurrentType)) {
279 Index *= ST->getNumElements();
280 CurrentType = ST->getElementType(I);
281 } else if (const auto *AT = dyn_cast<ArrayType>(CurrentType)) {
282 Index *= AT->getNumElements();
283 CurrentType = AT->getElementType();
284 } else {
285 return std::nullopt;
286 }
287 Index += I;
288 }
289 return Index;
290}
291
293 auto *It = find_if(VL, IsaPred<Instruction>);
294 if (It == VL.end())
295 return true;
296 Instruction *MainOp = cast<Instruction>(*It);
297 unsigned Opcode = MainOp->getOpcode();
298 bool IsCmpOp = isa<CmpInst>(MainOp);
299 CmpInst::Predicate BasePred = IsCmpOp ? cast<CmpInst>(MainOp)->getPredicate()
301 return all_of(make_range(It, VL.end()), [&](Value *V) {
302 if (auto *CI = dyn_cast<CmpInst>(V))
303 return BasePred == CI->getPredicate();
304 if (auto *I = dyn_cast<Instruction>(V))
305 return I->getOpcode() == Opcode;
306 return isa<PoisonValue>(V);
307 });
308}
309
310std::optional<unsigned> getExtractIndex(const Instruction *E) {
311 unsigned Opcode = E->getOpcode();
312 assert((Opcode == Instruction::ExtractElement ||
313 Opcode == Instruction::ExtractValue) &&
314 "Expected extractelement or extractvalue instruction.");
315 if (Opcode == Instruction::ExtractElement)
316 return getInsertExtractIndex<ExtractElementInst>(E, /*Offset=*/0);
317 auto *EI = cast<ExtractValueInst>(E);
318 if (EI->getNumIndices() != 1)
319 return std::nullopt;
320 return *EI->idx_begin();
321}
322
324 SmallVectorImpl<int> &Mask) {
325 Mask.clear();
326 const unsigned E = Indices.size();
327 Mask.resize(E, PoisonMaskElem);
328 for (unsigned I = 0; I < E; ++I)
329 Mask[Indices[I]] = I;
330}
331
333 assert(!Mask.empty() && "Expected non-empty mask.");
334 SmallVector<Value *> Prev(Scalars.size(),
335 PoisonValue::get(Scalars.front()->getType()));
336 Prev.swap(Scalars);
337 for (unsigned I = 0, E = Prev.size(); I < E; ++I)
338 if (Mask[I] != PoisonMaskElem)
339 Scalars[Mask[I]] = Prev[I];
340}
341
343 assert(!Mask.empty() && Reuses.size() == Mask.size() &&
344 "Expected non-empty mask.");
345 SmallVector<int> Prev(Reuses.begin(), Reuses.end());
346 Prev.swap(Reuses);
347 for (unsigned I = 0, E = Prev.size(); I < E; ++I)
348 if (Mask[I] != PoisonMaskElem)
349 Reuses[Mask[I]] = Prev[I];
350}
351
353 bool BottomOrder) {
354 assert(!Mask.empty() && "Expected non-empty mask.");
355 unsigned Sz = Mask.size();
356 if (BottomOrder) {
357 SmallVector<unsigned> PrevOrder;
358 if (Order.empty()) {
359 PrevOrder.resize(Sz);
360 std::iota(PrevOrder.begin(), PrevOrder.end(), 0);
361 } else {
362 PrevOrder.swap(Order);
363 }
364 Order.assign(Sz, Sz);
365 for (unsigned I = 0; I < Sz; ++I)
366 if (Mask[I] != PoisonMaskElem)
367 Order[I] = PrevOrder[Mask[I]];
368 if (all_of(enumerate(Order), [&](const auto &Data) {
369 return Data.value() == Sz || Data.index() == Data.value();
370 })) {
371 Order.clear();
372 return;
373 }
375 return;
376 }
377 SmallVector<int> MaskOrder;
378 if (Order.empty()) {
379 MaskOrder.resize(Sz);
380 std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
381 } else {
382 inversePermutation(Order, MaskOrder);
383 }
384 reorderReuses(MaskOrder, Mask);
385 if (ShuffleVectorInst::isIdentityMask(MaskOrder, Sz)) {
386 Order.clear();
387 return;
388 }
389 Order.assign(Sz, Sz);
390 for (unsigned I = 0; I < Sz; ++I)
391 if (MaskOrder[I] != PoisonMaskElem)
392 Order[MaskOrder[I]] = I;
394}
395
397 assert(!Order.empty() &&
398 "Order is empty. Please check it before using isReverseOrder.");
399 unsigned Sz = Order.size();
400 return all_of(enumerate(Order), [&](const auto &Pair) {
401 return Pair.value() == Sz || Sz - Pair.index() - 1 == Pair.value();
402 });
403}
404
406 ArrayRef<int> FirstCluster = Mask.slice(0, Sz);
407 if (ShuffleVectorInst::isIdentityMask(FirstCluster, Sz))
408 return false;
409 for (unsigned I = Sz, E = Mask.size(); I < E; I += Sz) {
410 ArrayRef<int> Cluster = Mask.slice(I, Sz);
411 if (Cluster != FirstCluster)
412 return false;
413 }
414 return true;
415}
416
418 ArrayRef<unsigned> SecondaryOrder) {
419 assert((SecondaryOrder.empty() || Order.size() == SecondaryOrder.size()) &&
420 "Expected same size of orders");
421 size_t Sz = Order.size();
422 SmallBitVector UsedIndices(Sz);
423 for (unsigned Idx : seq<unsigned>(0, Sz)) {
424 if (Order[Idx] != Sz)
425 UsedIndices.set(Order[Idx]);
426 }
427 if (SecondaryOrder.empty()) {
428 for (unsigned Idx : seq<unsigned>(0, Sz))
429 if (Order[Idx] == Sz && !UsedIndices.test(Idx))
430 Order[Idx] = Idx;
431 } else {
432 for (unsigned Idx : seq<unsigned>(0, Sz))
433 if (SecondaryOrder[Idx] != Sz && Order[Idx] == Sz &&
434 !UsedIndices.test(SecondaryOrder[Idx]))
435 Order[Idx] = SecondaryOrder[Idx];
436 }
437}
438
440 assert(!VL.empty() && "Expected non-empty list of values.");
441 Type *Ty = VL.consume_front()->getType();
442 return all_of(VL, [&](Value *V) { return V->getType() == Ty; });
443}
444
445template <typename T>
446std::optional<unsigned> getInsertExtractIndex(const Value *Inst,
447 unsigned Offset) {
448 static_assert(std::is_same_v<T, InsertElementInst> ||
449 std::is_same_v<T, ExtractElementInst>,
450 "unsupported T");
451 const auto *IE = dyn_cast<T>(Inst);
452 if (!IE)
453 return std::nullopt;
454 // InsertElement: result is the vector, index is op 2.
455 // ExtractElement: result is scalar, vector is op 0, index is op 1.
456 constexpr bool IsInsert = std::is_same_v<T, InsertElementInst>;
457 Type *VecTy = IsInsert ? IE->getType() : IE->getOperand(0)->getType();
458 const auto *VT = dyn_cast<FixedVectorType>(VecTy);
459 if (!VT)
460 return std::nullopt;
461 const auto *CI = dyn_cast<ConstantInt>(IE->getOperand(IsInsert ? 2 : 1));
462 if (!CI)
463 return std::nullopt;
464 if (CI->getValue().uge(VT->getNumElements()))
465 return std::nullopt;
466 unsigned Index = Offset;
467 Index *= VT->getNumElements();
468 Index += CI->getZExtValue();
469 return Index;
470}
471
472// Only these two specializations are used; instantiate them here so the
473// definition can stay out of the header.
474template std::optional<unsigned>
476template std::optional<unsigned>
478
480 auto *I = dyn_cast<Instruction>(V);
481 if (!I)
482 return true;
483 return all_of(make_isa_range<Instruction>(I->operands()),
484 [I](Instruction *IO) {
485 return isa<PHINode>(IO) || IO->getParent() != I->getParent();
486 }) &&
488}
489
491 auto *I = dyn_cast<Instruction>(V);
492 if (!I)
493 return true;
494 // Limits the number of uses to save compile time.
495 return !I->hasNUsesOrMore(UsesLimit) && all_of(I->users(), [I](User *U) {
496 auto *IU = dyn_cast<Instruction>(U);
497 if (!IU)
498 return true;
499 return IU->getParent() != I->getParent() || isa<PHINode>(IU);
500 }) && !I->mayReadOrWriteMemory();
501}
502
506
511
512void transformScalarShuffleIndiciesToVector(unsigned VecTyNumElements,
513 SmallVectorImpl<int> &Mask) {
514 // The ShuffleBuilder implementation use shufflevector to splat an "element".
515 // But the element have different meaning for SLP (scalar) and REVEC
516 // (vector). We need to expand Mask into masks which shufflevector can use
517 // directly.
518 SmallVector<int> NewMask(Mask.size() * VecTyNumElements);
519 for (unsigned I : seq<unsigned>(Mask.size()))
520 for (auto [J, MaskV] : enumerate(MutableArrayRef(NewMask).slice(
521 I * VecTyNumElements, VecTyNumElements)))
522 MaskV = Mask[I] == PoisonMaskElem ? PoisonMaskElem
523 : Mask[I] * VecTyNumElements + J;
524 Mask.swap(NewMask);
525}
526
528 if (VL.empty())
529 return 0;
531 return 0;
532 auto *SV = cast<ShuffleVectorInst>(VL.front());
533 unsigned SVNumElements =
534 cast<FixedVectorType>(SV->getOperand(0)->getType())->getNumElements();
535 unsigned ShuffleMaskSize = SV->getShuffleMask().size();
536 if (SVNumElements % ShuffleMaskSize != 0)
537 return 0;
538 unsigned GroupSize = SVNumElements / ShuffleMaskSize;
539 if (GroupSize == 0 || (VL.size() % GroupSize) != 0)
540 return 0;
541 unsigned NumGroup = 0;
542 for (size_t I = 0, E = VL.size(); I != E; I += GroupSize) {
543 auto *SV = cast<ShuffleVectorInst>(VL[I]);
544 Value *Src = SV->getOperand(0);
545 ArrayRef<Value *> Group = VL.slice(I, GroupSize);
546 SmallBitVector ExpectedIndex(GroupSize);
547 if (!all_of(Group, [&](Value *V) {
548 auto *SV = cast<ShuffleVectorInst>(V);
549 // From the same source.
550 if (SV->getOperand(0) != Src)
551 return false;
552 int Index;
553 if (!SV->isExtractSubvectorMask(Index))
554 return false;
555 ExpectedIndex.set(Index / ShuffleMaskSize);
556 return true;
557 }))
558 return 0;
559 if (!ExpectedIndex.all())
560 return 0;
561 ++NumGroup;
562 }
563 assert(NumGroup == (VL.size() / GroupSize) && "Unexpected number of groups");
564 return NumGroup;
565}
566
568 assert(getShufflevectorNumGroups(VL) && "Not supported shufflevector usage.");
569 auto *SV = cast<ShuffleVectorInst>(VL.front());
570 unsigned SVNumElements =
571 cast<FixedVectorType>(SV->getOperand(0)->getType())->getNumElements();
572 SmallVector<int> Mask;
573 unsigned AccumulateLength = 0;
574 for (Value *V : VL) {
575 auto *SV = cast<ShuffleVectorInst>(V);
576 for (int M : SV->getShuffleMask())
577 Mask.push_back(M == PoisonMaskElem ? PoisonMaskElem
578 : AccumulateLength + M);
579 AccumulateLength += SVNumElements;
580 }
581 return Mask;
582}
583
584/// Checks if the vector of instructions can be represented as a shuffle, like:
585/// %x0 = extractelement <4 x i8> %x, i32 0
586/// %x3 = extractelement <4 x i8> %x, i32 3
587/// %y1 = extractelement <4 x i8> %y, i32 1
588/// %y2 = extractelement <4 x i8> %y, i32 2
589/// %x0x0 = mul i8 %x0, %x0
590/// %x3x3 = mul i8 %x3, %x3
591/// %y1y1 = mul i8 %y1, %y1
592/// %y2y2 = mul i8 %y2, %y2
593/// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
594/// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
595/// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
596/// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
597/// ret <4 x i8> %ins4
598/// can be transformed into:
599/// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
600/// i32 6>
601/// %2 = mul <4 x i8> %1, %1
602/// ret <4 x i8> %2
603/// Mask will return the Shuffle Mask equivalent to the extracted elements.
604/// TODO: Can we split off and reuse the shuffle mask detection from
605/// ShuffleVectorInst/getShuffleCost?
606std::optional<TargetTransformInfo::ShuffleKind>
608 AssumptionCache *AC, SLPAnalysisCache &Cache) {
609 const auto *It = find_if(VL, IsaPred<ExtractElementInst>);
610 if (It == VL.end())
611 return std::nullopt;
612 unsigned Size = 0;
613 Value *Vec1 = nullptr;
614 Value *Vec2 = nullptr;
615 // The poison analysis is expensive, it is required only for the undef
616 // vectors.
617 std::optional<bool> HasNonUndefVec;
618 auto IsNonUndefVecPresent = [&]() {
619 if (!HasNonUndefVec)
620 HasNonUndefVec = any_of(make_isa_range<ExtractElementInst>(VL),
621 [&](ExtractElementInst *EE) {
622 Value *Vec = EE->getVectorOperand();
623 if (isa<UndefValue>(Vec))
624 return false;
625 return Cache.isGuaranteedNotToBePoison(Vec, AC);
626 });
627 return *HasNonUndefVec;
628 };
629 enum ShuffleMode { Unknown, Select, Permute };
630 ShuffleMode CommonShuffleMode = Unknown;
631 Mask.assign(VL.size(), PoisonMaskElem);
632 for (unsigned I = 0, E = VL.size(); I < E; ++I) {
633 // Undef, or a copyable lane modeled on an extract main op, can be
634 // represented as an undef element in a vector.
635 if (isa<UndefValue>(VL[I]))
636 continue;
637 auto *EI = dyn_cast<ExtractElementInst>(VL[I]);
638 if (!EI)
639 continue;
640 if (isa<ScalableVectorType>(EI->getVectorOperandType()))
641 return std::nullopt;
642 auto *Vec = EI->getVectorOperand();
643 // We can extractelement from undef or poison vector.
645 continue;
646 // All vector operands must have the same number of vector elements.
647 if (isa<UndefValue>(Vec)) {
648 Mask[I] = I;
649 } else {
650 if (isa<UndefValue>(EI->getIndexOperand()))
651 continue;
652 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
653 if (!Idx)
654 return std::nullopt;
655 // Undefined behavior if Idx is negative or out of bounds.
656 if (Idx->getValue().uge(getNumElements(Vec->getType())))
657 continue;
658 unsigned IntIdx = Idx->getValue().getZExtValue();
659 Mask[I] = IntIdx;
660 }
661 // The width is defined only by the lanes that are present in the mask.
662 Size = std::max(Size, getNumElements(Vec->getType()));
663 if (isUndefVector(Vec).all() && IsNonUndefVecPresent())
664 continue;
665 // For correct shuffling we have to have at most 2 different vector operands
666 // in all extractelement instructions.
667 if (!Vec1 || Vec1 == Vec) {
668 Vec1 = Vec;
669 } else if (!Vec2 || Vec2 == Vec) {
670 Vec2 = Vec;
671 } else {
672 return std::nullopt;
673 }
674 }
675 if (Vec2 && Size != std::max(getNumElements(Vec1->getType()),
676 getNumElements(Vec2->getType())))
677 return std::nullopt;
678 for (auto [I, Idx] : enumerate(Mask)) {
679 if (Idx == PoisonMaskElem)
680 continue;
681 auto *Vec = cast<ExtractElementInst>(VL[I])->getVectorOperand();
682 if (Vec == Vec2)
683 Idx += Size;
684 else if (Vec != Vec1)
685 continue;
686 if (CommonShuffleMode == Permute)
687 continue;
688 // If the extract index is not the same as the operation number, it is a
689 // permutation.
690 if (Idx % Size != I) {
691 CommonShuffleMode = Permute;
692 continue;
693 }
694 CommonShuffleMode = Select;
695 }
696 // If we're not crossing lanes in different vectors, consider it as blending.
697 if (CommonShuffleMode == Select && Vec2)
699 // If Vec2 was never used, we have a permutation of a single vector, otherwise
700 // we have permutation of 2 vectors.
703}
704
706 IRBuilderBase &Builder, Value *Vec, Value *V, unsigned Index,
707 function_ref<Value *(Value *, Value *, ArrayRef<int>)> Generator) {
708 if (isa<PoisonValue>(Vec) && isa<PoisonValue>(V))
709 return Vec;
710 const unsigned SubVecVF = getNumElements(V->getType());
711 // Create shuffle, insertvector requires that index is multiple of
712 // the subvector length.
713 const unsigned VecVF = getNumElements(Vec->getType());
714 SmallVector<int> Mask(VecVF, PoisonMaskElem);
715 if (isa<PoisonValue>(Vec)) {
716 auto *Begin = std::next(Mask.begin(), Index);
717 std::iota(Begin, std::next(Begin, SubVecVF), 0);
718 Vec = Builder.CreateShuffleVector(V, Mask);
719 return Vec;
720 }
721 std::iota(Mask.begin(), Mask.end(), 0);
722 std::iota(std::next(Mask.begin(), Index),
723 std::next(Mask.begin(), Index + SubVecVF), VecVF);
724 if (Generator)
725 return Generator(Vec, V, Mask);
726 // 1. Resize V to the size of Vec.
727 SmallVector<int> ResizeMask(VecVF, PoisonMaskElem);
728 std::iota(ResizeMask.begin(), std::next(ResizeMask.begin(), SubVecVF), 0);
729 V = Builder.CreateShuffleVector(V, ResizeMask);
730 // 2. Insert V into Vec.
731 return Builder.CreateShuffleVector(Vec, V, Mask);
732}
733
735 unsigned SubVecVF, unsigned Index) {
736 SmallVector<int> Mask(SubVecVF, PoisonMaskElem);
737 std::iota(Mask.begin(), Mask.end(), Index);
738 return Builder.CreateShuffleVector(Vec, Mask);
739}
740
741bool dominatesAllUses(const DominatorTree &DT, const Instruction &InsertPt,
742 const Instruction &I) {
743 assert(InsertPt.getParent() == I.getParent() && "Expected same block.");
744 assert(DT.isReachableFromEntry(InsertPt.getParent()) &&
745 "Expected reachable block.");
746 // The uses of the instruction after InsertPt are dominated by InsertPt.
747 if (InsertPt.comesBefore(&I))
748 return true;
749 return !I.hasNUsesOrMore(UsesLimit) && all_of(I.uses(), [&](const Use &U) {
750 return DT.dominates(&InsertPt, U);
751 });
752}
753
755 const BasicBlock *BB,
756 function_ref<bool(Instruction *)> Pred) {
757 assert((Opcode == Instruction::URem || Opcode == Instruction::SRem) &&
758 "Expected remainder.");
759 // The paired division is another user of both operands.
760 if (X->hasOneUse() || Y->hasOneUse())
761 return nullptr;
762 // Constants have context-wide use lists, walk the variable operand. The
763 // dividend usually has fewer users than the divisor, the divisor is walked
764 // only if the dividend has too many.
765 Value *Op = X;
766 if (isa<Constant>(X) || X->hasNUsesOrMore(UsesLimit)) {
767 if (isa<Constant>(Y) || Y->hasNUsesOrMore(UsesLimit))
768 return nullptr;
769 Op = Y;
770 }
771 const unsigned DivOpcode =
772 Opcode == Instruction::URem ? Instruction::UDiv : Instruction::SDiv;
773 for (User *U : Op->users()) {
774 auto *I = dyn_cast<Instruction>(U);
775 if (I && match(I, m_BinOp(DivOpcode, m_Specific(X), m_Specific(Y))) &&
776 I->getParent() == BB && Pred(I))
777 return I;
778 }
779 return nullptr;
780}
781
783 SmallBitVector UseMask(VF, true);
784 for (auto [Idx, Value] : enumerate(Mask)) {
785 if (Value == PoisonMaskElem) {
786 if (MaskArg == UseMask::UndefsAsMask)
787 UseMask.reset(Idx);
788 continue;
789 }
790 if (MaskArg == UseMask::FirstArg && Value < VF)
791 UseMask.reset(Value);
792 else if (MaskArg == UseMask::SecondArg && Value >= VF)
793 UseMask.reset(Value - VF);
794 }
795 return UseMask;
796}
797
798template <bool IsPoisonOnly>
800 SmallBitVector Res(UseMask.empty() ? 1 : UseMask.size(), true);
801 using T = std::conditional_t<IsPoisonOnly, PoisonValue, UndefValue>;
802 if (isa<T>(V))
803 return Res;
804 auto *VecTy = dyn_cast<FixedVectorType>(V->getType());
805 if (!VecTy)
806 return Res.reset();
807 auto *C = dyn_cast<Constant>(V);
808 if (!C) {
809 if (!UseMask.empty()) {
810 const Value *Base = V;
811 while (auto *II = dyn_cast<InsertElementInst>(Base)) {
812 Base = II->getOperand(0);
813 if (isa<T>(II->getOperand(1)))
814 continue;
815 std::optional<unsigned> Idx = getElementIndex(II);
816 if (!Idx) {
817 Res.reset();
818 return Res;
819 }
820 if (*Idx < UseMask.size() && !UseMask.test(*Idx))
821 Res.reset(*Idx);
822 }
823 // TODO: Add analysis for shuffles here too.
824 if (V == Base) {
825 Res.reset();
826 } else {
827 SmallBitVector SubMask(UseMask.size(), false);
828 Res &= isUndefVector<IsPoisonOnly>(Base, SubMask);
829 }
830 } else {
831 Res.reset();
832 }
833 return Res;
834 }
835 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
836 if (Constant *Elem = C->getAggregateElement(I))
837 if (!isa<T>(Elem) &&
838 (UseMask.empty() || (I < UseMask.size() && !UseMask.test(I))))
839 Res.reset(I);
840 }
841 return Res;
842}
843
845 const SmallBitVector &);
847 const SmallBitVector &);
848
851 const TargetTransformInfo *TTI) {
852 if (!UserInst)
853 return false;
854 unsigned Opcode = UserInst->getOpcode();
855 switch (Opcode) {
856 case Instruction::Load: {
857 LoadInst *LI = cast<LoadInst>(UserInst);
858 return (LI->getPointerOperand() == Scalar);
859 }
860 case Instruction::Store: {
861 StoreInst *SI = cast<StoreInst>(UserInst);
862 return (SI->getPointerOperand() == Scalar);
863 }
864 case Instruction::Call: {
865 CallInst *CI = cast<CallInst>(UserInst);
867 return any_of(enumerate(CI->args()), [&](auto &&Arg) {
868 return isVectorIntrinsicWithScalarOpAtArg(ID, Arg.index(), TTI) &&
869 Arg.value().get() == Scalar;
870 });
871 }
872 default:
873 return false;
874 }
875}
876
884
886 if (LoadInst *LI = dyn_cast<LoadInst>(I))
887 return LI->isSimple();
889 return SI->isSimple();
891 return !MI->isVolatile();
892 return true;
893}
894
895bool isSelectedBaseLoad(Type *ScalarTy, ArrayRef<Value *> PointerOps,
896 const DataLayout &DL, Value *&TrueBase,
897 Value *&FalseBase,
898 SmallVectorImpl<Value *> &Conditions) {
899 TrueBase = nullptr;
900 FalseBase = nullptr;
901 uint64_t ScalarSize = DL.getTypeStoreSize(ScalarTy);
902 Conditions.assign(PointerOps.size(), nullptr);
903 for (auto [Idx, P] : enumerate(PointerOps)) {
904 Value *Base = P;
905 uint64_t Offset = 0;
906 if (auto *GEP = dyn_cast<GetElementPtrInst>(P)) {
907 APInt OffsetAP(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
908 if (!GEP->accumulateConstantOffset(DL, OffsetAP) || OffsetAP.isNegative())
909 return false;
910 Offset = OffsetAP.getZExtValue();
911 Base = GEP->getPointerOperand();
912 }
913 auto *Sel = dyn_cast<SelectInst>(Base);
914 if (!Sel)
915 return false;
916 Value *T = Sel->getTrueValue();
917 Value *F = Sel->getFalseValue();
918 if (!TrueBase) {
919 if (T == F)
920 return false;
921 TrueBase = T;
922 FalseBase = F;
923 } else if (TrueBase != T || FalseBase != F) {
924 return false;
925 }
926 // Lane Idx must be at exactly Base + Idx * sizeof(ScalarTy); codegen reads
927 // contiguously from TrueBase/FalseBase starting at lane 0.
928 if (Offset != static_cast<uint64_t>(Idx) * ScalarSize)
929 return false;
930 Conditions[Idx] = Sel->getCondition();
931 }
932 return TrueBase != nullptr;
933}
934
936 const DataLayout &DL) {
938 "Expected only load lanes in a blended load.");
939 const uint64_t ScalarSize = DL.getTypeStoreSize(VL.front()->getType());
940 Align BaseAlignment = cast<LoadInst>(VL.front())->getAlign();
941 for (auto [Idx, V] : enumerate(VL))
942 BaseAlignment =
943 std::min(BaseAlignment, commonAlignment(cast<LoadInst>(V)->getAlign(),
944 Idx * ScalarSize));
945 return BaseAlignment;
946}
947
949 Value *Ptr = cast<LoadInst>(VL.front())->getPointerOperand();
950 if (auto *GEP = dyn_cast<GetElementPtrInst>(Ptr))
951 Ptr = GEP->getPointerOperand();
952 return cast<SelectInst>(Ptr);
953}
954
956 function_ref<bool(Value *)> IsGEPLane,
957 const DataLayout &DL) {
958 constexpr unsigned IndexIdx = 1;
959 Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
960 Type *PtrIdxTy =
961 DL.getIndexType(VL0->getOperand(0)->getType()->getScalarType());
962 bool AllSameTy = true;
963 bool HasNonConstIdx = false;
964 bool ConstsFitVL0Ty = true;
965 for (Value *V : make_filter_range(VL, IsGEPLane)) {
966 Value *Op = cast<GetElementPtrInst>(V)->getOperand(IndexIdx);
967 if (Op->getType() != VL0Ty)
968 AllSameTy = false;
969 auto *CI = dyn_cast<ConstantInt>(Op);
970 if (!CI) {
971 // Non-constant indices are not cast, they must have the main op type.
972 if (Op->getType() != VL0Ty)
973 return nullptr;
974 HasNonConstIdx = true;
975 continue;
976 }
977 if (!CI->getValue().isSignedIntN(VL0Ty->getIntegerBitWidth()))
978 ConstsFitVL0Ty = false;
979 }
980 if (AllSameTy)
981 return VL0Ty;
982 if (!HasNonConstIdx || VL0Ty == PtrIdxTy)
983 return PtrIdxTy;
984 return ConstsFitVL0Ty ? VL0Ty : nullptr;
985}
986
988 SmallPtrSet<Value *, 16> UniquePtrs(llvm::from_range, PointerOps);
989 if (UniquePtrs.size() != PointerOps.size())
990 return false;
991 auto IsConstantOffsetPtr = [](Value *P) {
993 return !GEP ||
994 (GEP->getNumOperands() == 2 && isConstant(GEP->getOperand(1)));
995 };
996 auto *RefIt = find_if_not(PointerOps, IsConstantOffsetPtr);
997 if (RefIt == PointerOps.end())
998 return false;
999 auto *RefGEP = dyn_cast<GetElementPtrInst>(*RefIt);
1000 if (!RefGEP || RefGEP->getNumOperands() != 2)
1001 return false;
1002 Value *Base = RefGEP->getPointerOperand();
1003 Type *PtrTy = RefGEP->getType();
1004 Type *SrcElemTy = RefGEP->getSourceElementType();
1005 // The stride and the (optional) cast opcode of the runtime indices.
1006 Value *Stride = nullptr;
1007 unsigned CastOpcode = 0;
1008 for (Value *P : PointerOps) {
1009 if (P->getType() != PtrTy)
1010 return false;
1011 if (P == Base)
1012 continue;
1014 if (!GEP || GEP->getNumOperands() != 2 ||
1015 GEP->getPointerOperand() != Base ||
1016 GEP->getSourceElementType() != SrcElemTy)
1017 return false;
1018 Value *Idx = GEP->getOperand(1);
1019 if (isConstant(Idx))
1020 continue;
1021 unsigned LaneCastOpcode = 0;
1022 if (auto *Cast = dyn_cast<CastInst>(Idx)) {
1023 LaneCastOpcode = Cast->getOpcode();
1024 Idx = Cast->getOperand(0);
1025 }
1026 Value *LaneStride = Idx;
1027 if (auto *BO = dyn_cast<BinaryOperator>(Idx)) {
1028 if (isa<Constant>(BO->getOperand(1)))
1029 LaneStride = BO->getOperand(0);
1030 else if (isa<Constant>(BO->getOperand(0)))
1031 LaneStride = BO->getOperand(1);
1032 }
1033 if (!Stride) {
1034 Stride = LaneStride;
1035 CastOpcode = LaneCastOpcode;
1036 continue;
1037 }
1038 if (LaneStride != Stride || LaneCastOpcode != CastOpcode)
1039 return false;
1040 }
1041 return Stride != nullptr;
1042}
1043
1045 bool ExtendingManyInputs) {
1046 if (SubMask.empty())
1047 return;
1048 assert(
1049 (!ExtendingManyInputs || SubMask.size() > Mask.size() ||
1050 // Check if input scalars were extended to match the size of other node.
1051 (SubMask.size() == Mask.size() && Mask.back() == PoisonMaskElem)) &&
1052 "SubMask with many inputs support must be larger than the mask.");
1053 if (Mask.empty()) {
1054 Mask.append(SubMask.begin(), SubMask.end());
1055 return;
1056 }
1057 SmallVector<int> NewMask(SubMask.size(), PoisonMaskElem);
1058 int TermValue = std::min(Mask.size(), SubMask.size());
1059 for (int I = 0, E = SubMask.size(); I < E; ++I) {
1060 if (SubMask[I] == PoisonMaskElem ||
1061 (!ExtendingManyInputs &&
1062 (SubMask[I] >= TermValue || Mask[SubMask[I]] >= TermValue)))
1063 continue;
1064 NewMask[I] = Mask[SubMask[I]];
1065 }
1066 Mask.swap(NewMask);
1067}
1068
1070 const size_t Sz = Order.size();
1071 SmallBitVector UnusedIndices(Sz, /*t=*/true);
1072 SmallBitVector MaskedIndices(Sz);
1073 for (unsigned I = 0; I < Sz; ++I) {
1074 if (Order[I] < Sz)
1075 UnusedIndices.reset(Order[I]);
1076 else
1077 MaskedIndices.set(I);
1078 }
1079 if (MaskedIndices.none())
1080 return;
1081 assert(UnusedIndices.count() == MaskedIndices.count() &&
1082 "Non-synced masked/available indices.");
1083 int Idx = UnusedIndices.find_first();
1084 int MIdx = MaskedIndices.find_first();
1085 while (MIdx >= 0) {
1086 assert(Idx >= 0 && "Indices must be synced.");
1087 Order[MIdx] = Idx;
1088 Idx = UnusedIndices.find_next(Idx);
1089 MIdx = MaskedIndices.find_next(MIdx);
1090 }
1091}
1092
1094 unsigned Opcode0, unsigned Opcode1) {
1095 unsigned ScalarTyNumElements = getNumElements(ScalarTy);
1096 SmallBitVector OpcodeMask(VL.size() * ScalarTyNumElements, false);
1097 for (unsigned Lane : seq<unsigned>(VL.size())) {
1098 if (isa<PoisonValue>(VL[Lane]))
1099 continue;
1100 if (cast<Instruction>(VL[Lane])->getOpcode() == Opcode1)
1101 OpcodeMask.set(Lane * ScalarTyNumElements,
1102 Lane * ScalarTyNumElements + ScalarTyNumElements);
1103 }
1104 return OpcodeMask;
1105}
1106
1108 assert(none_of(Val, [](Constant *C) { return C->getType()->isVectorTy(); }) &&
1109 "Expected scalar constants.");
1110 SmallVector<Constant *> NewVal(Val.size() * VF);
1111 for (auto [I, V] : enumerate(Val))
1112 std::fill_n(NewVal.begin() + I * VF, VF, V);
1113 return NewVal;
1114}
1115
1117 switch (Opcode) {
1118 case Instruction::UDiv:
1119 return Intrinsic::masked_udiv;
1120 case Instruction::SDiv:
1121 return Intrinsic::masked_sdiv;
1122 case Instruction::URem:
1123 return Intrinsic::masked_urem;
1124 case Instruction::SRem:
1125 return Intrinsic::masked_srem;
1126 default:
1127 llvm_unreachable("Unexpected opcode");
1128 }
1129}
1130
1131/// Returns true if \p I is a part of a single-use chain, computing an address,
1132/// which does not pay off the vectorization: all the lanes are extracted for
1133/// the scalar addresses, the extracts delay the memory accesses.
1135 constexpr unsigned MaxIndexChainLength = 3;
1136 const User *U = I->user_back();
1137 for ([[maybe_unused]] unsigned _ : seq<unsigned>(MaxIndexChainLength)) {
1139 return true;
1140 if (!isa<Instruction>(U) || !U->hasOneUse())
1141 return false;
1142 U = U->user_back();
1143 }
1144 return false;
1145}
1146
1148 if (!I->hasOneUse() || isNonProfitableIndex(I))
1149 return false;
1150 // The operation with the identity or the absorbing constant is folded away
1151 // before the codegen, the vector node only repacks the lanes.
1152 if (const auto *BO = dyn_cast<BinaryOperator>(I)) {
1153 unsigned Opcode = BO->getOpcode();
1154 Type *Ty = BO->getType();
1155 for (unsigned Idx : seq<unsigned>(2)) {
1156 const auto *C = dyn_cast<Constant>(BO->getOperand(Idx));
1158 Opcode, Ty, /*AllowRHSConstant=*/Idx == 1) ||
1160 Opcode, Ty, /*AllowLHSConstant=*/Idx == 0)))
1161 return false;
1162 }
1163 }
1164 const User *U = I->user_back();
1167 if (isa<CastInst>(I))
1168 return !isa<FPToSIInst, FPToUIInst>(I) &&
1169 (!isa<CastInst>(U) || U->hasOneUse());
1171 I);
1172}
1173
1174Instruction *lookThroughCastRoundTrip(Value *V, bool MustBeElidable) {
1175 auto *Wide = dyn_cast<FPExtInst>(V);
1176 if (!Wide || !Wide->hasOneUse())
1177 return nullptr;
1178 auto *Narrow = dyn_cast<FPTruncInst>(Wide->getOperand(0));
1179 if (!Narrow || !Narrow->hasOneUse())
1180 return nullptr;
1181 Value *Src = Narrow->getOperand(0);
1182 if (!isa<Instruction>(Src) || Src->getType() != Wide->getType())
1183 return nullptr;
1184 if (MustBeElidable && !(Wide->hasAllowContract() && Wide->hasNoNaNs() &&
1185 Wide->hasNoInfs() && Narrow->hasAllowContract()))
1186 return nullptr;
1187 return Narrow;
1188}
1189
1190namespace {
1191
1192/// Shifts and the mask accumulated from the narrow ops on the current path:
1193/// the shifts above and at the narrow level, the bitwidth of the narrow ops
1194/// (0 if none) and the mask from the absorbed narrow ands.
1195struct NarrowedChainState {
1196 unsigned Shift = 0;
1197 unsigned NarrowShift = 0;
1198 unsigned NarrowBW = 0;
1199 APInt NarrowMask = APInt(1, 0);
1200
1201 /// The mask for the absorbed narrow ops in the leaf type, applied before
1202 /// widening and shifting; all-ones if nothing was absorbed.
1203 APInt getMask(unsigned LeafBW) const {
1204 if (NarrowBW == 0)
1205 return APInt::getAllOnes(LeafBW);
1206 return (NarrowMask & (APInt::getAllOnes(NarrowBW) << NarrowShift))
1207 .lshr(NarrowShift)
1208 .trunc(LeafBW);
1209 }
1210};
1211
1212} // namespace
1213
1214static void
1215collectNarrowedLeavesImpl(Value *V, unsigned RdxOpcode, unsigned WideBW,
1216 NarrowedChainState S, unsigned Depth,
1217 unsigned MaxDepth,
1219 SmallVectorImpl<Instruction *> &ChainInsts) {
1220 if (Depth < MaxDepth) {
1221 if (auto *Z = dyn_cast<ZExtInst>(V);
1222 Z && Z->getSrcTy()->isIntegerTy() && !Z->getSrcTy()->isIntegerTy(1)) {
1223 ChainInsts.push_back(Z);
1224 return collectNarrowedLeavesImpl(Z->getOperand(0), RdxOpcode, WideBW, S,
1225 Depth + 1, MaxDepth, Leaves, ChainInsts);
1226 }
1227 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
1228 if (BO->getOpcode() == RdxOpcode) {
1229 ChainInsts.push_back(BO);
1230 collectNarrowedLeavesImpl(BO->getOperand(0), RdxOpcode, WideBW, S,
1231 Depth + 1, MaxDepth, Leaves, ChainInsts);
1232 collectNarrowedLeavesImpl(BO->getOperand(1), RdxOpcode, WideBW, S,
1233 Depth + 1, MaxDepth, Leaves, ChainInsts);
1234 return;
1235 }
1236 const APInt *Amt;
1237 unsigned BW = V->getType()->getScalarSizeInBits();
1238 auto *Z = dyn_cast<ZExtInst>(BO->getOperand(0));
1239 if (BO->getOpcode() == Instruction::Shl && Z && S.NarrowBW == 0 &&
1240 match(BO->getOperand(1), m_APInt(Amt)) && Amt->ult(BW) &&
1241 Z->getSrcTy()->isIntegerTy() && !Z->getSrcTy()->isIntegerTy(1) &&
1242 (BW == WideBW ||
1243 Z->getSrcTy()->getIntegerBitWidth() + Amt->getZExtValue() <= BW) &&
1244 S.Shift + Amt->getZExtValue() < WideBW) {
1245 ChainInsts.push_back(BO);
1246 ChainInsts.push_back(Z);
1247 S.Shift += Amt->getZExtValue();
1248 return collectNarrowedLeavesImpl(Z->getOperand(0), RdxOpcode, WideBW, S,
1249 Depth + 1, MaxDepth, Leaves,
1250 ChainInsts);
1251 }
1252 // Narrow shls fold into the shift and narrow ands into the mask; the
1253 // mask clears the bits the shls shift out. Only same-width ops compose
1254 // on one path, and the combined shift must stay a valid shift amount in
1255 // both types.
1256 if (BW < WideBW && (S.NarrowBW == 0 || BW == S.NarrowBW)) {
1257 if (BO->getOpcode() == Instruction::Shl &&
1258 match(BO->getOperand(1), m_APInt(Amt)) && Amt->ult(BW) &&
1259 S.NarrowShift + Amt->getZExtValue() < BW &&
1260 S.Shift + S.NarrowShift + Amt->getZExtValue() < WideBW) {
1261 ChainInsts.push_back(BO);
1262 if (BO->hasNoUnsignedWrap() && S.NarrowBW == 0) {
1263 S.Shift += Amt->getZExtValue();
1264 // Lossless shls shift out only known-zero bits; record them as
1265 // the mask so matching lanes can form a splat.
1266 S.NarrowBW = BW;
1267 S.NarrowMask = APInt::getLowBitsSet(BW, BW - Amt->getZExtValue());
1268 } else {
1269 if (S.NarrowBW == 0) {
1270 S.NarrowBW = BW;
1271 S.NarrowMask = APInt::getAllOnes(BW);
1272 }
1273 S.NarrowShift += Amt->getZExtValue();
1274 }
1275 return collectNarrowedLeavesImpl(BO->getOperand(0), RdxOpcode, WideBW,
1276 S, Depth + 1, MaxDepth, Leaves,
1277 ChainInsts);
1278 }
1279 Value *X;
1280 if (match(BO, m_c_And(m_Value(X), m_APInt(Amt)))) {
1281 ChainInsts.push_back(BO);
1282 if (S.NarrowBW == 0) {
1283 S.NarrowBW = BW;
1284 S.NarrowMask = APInt::getAllOnes(BW);
1285 }
1286 S.NarrowMask &= *Amt << S.NarrowShift;
1287 return collectNarrowedLeavesImpl(X, RdxOpcode, WideBW, S, Depth + 1,
1288 MaxDepth, Leaves, ChainInsts);
1289 }
1290 }
1291 }
1292 }
1293 Leaves.emplace_back(V, S.Shift + S.NarrowShift,
1294 S.getMask(V->getType()->getScalarSizeInBits()));
1295}
1296
1297void collectNarrowedLeaves(Value *V, unsigned RdxOpcode, unsigned WideBW,
1298 unsigned MaxDepth,
1300 SmallVectorImpl<Instruction *> &ChainInsts) {
1301 collectNarrowedLeavesImpl(V, RdxOpcode, WideBW, NarrowedChainState(),
1302 /*Depth=*/0, MaxDepth, Leaves, ChainInsts);
1303}
1304
1306 assert(F && "Expected function.");
1307 return F->hasOptSize() ? TTI::TCK_CodeSize : TTI::TCK_RecipThroughput;
1308}
1309
1310/// Checks if \p V is a zero-extended sub-field of a wider integer scalar.
1311/// Returns the source scalar, the field width and the field offset.
1312static std::optional<std::tuple<Value *, unsigned, unsigned>>
1314 if (!V->getType()->isIntegerTy())
1315 return std::nullopt;
1316 // Field offset for the field-aligned shift amount, if the shifted value of
1317 // the given bit width keeps at least one full field.
1318 auto GetFieldOffset = [](const APInt *Amt, unsigned BitWidth,
1319 unsigned FieldWidth) -> std::optional<unsigned> {
1320 uint64_t ShAmt = Amt->getLimitedValue(BitWidth);
1321 if (ShAmt % FieldWidth != 0 || ShAmt + FieldWidth > BitWidth)
1322 return std::nullopt;
1323 return ShAmt / FieldWidth;
1324 };
1325 // Checks if the low bits of Val are a sub-field of the given width of a
1326 // wider integer scalar. Val is a scalar integer, since V is one, and so is
1327 // the matched source.
1328 auto MatchLowField =
1329 [&](Value *Val,
1330 unsigned FieldWidth) -> std::optional<std::pair<Value *, unsigned>> {
1331 Value *Src;
1332 const APInt *Amt;
1333 // Only the low bits of Val are observed, so lshr and ashr are equivalent.
1334 if (match(Val, m_Trunc(m_Shr(m_Value(Src), m_APInt(Amt)))) ||
1335 match(Val, m_Shr(m_Value(Src), m_APInt(Amt)))) {
1336 if (std::optional<unsigned> Offset = GetFieldOffset(
1337 Amt, Src->getType()->getIntegerBitWidth(), FieldWidth)) {
1338 // The truncation of the shifted value keeps the field, look through it.
1339 match(Src, m_Trunc(m_Value(Src)));
1340 return std::make_pair(Src, *Offset);
1341 }
1342 return std::nullopt;
1343 }
1344 if (match(Val, m_Trunc(m_Value(Src))) &&
1345 Src->getType()->getIntegerBitWidth() >= FieldWidth)
1346 return std::make_pair(Src, 0u);
1347 // Val itself is the source of its low field.
1348 if (Val->getType()->getIntegerBitWidth() > FieldWidth)
1349 return std::make_pair(Val, 0u);
1350 return std::nullopt;
1351 };
1352 Value *Val;
1353 const APInt *Mask;
1354 // and Val, (1 << FieldWidth) - 1 or zext i<FieldWidth> Val - the low bits of
1355 // Val.
1356 unsigned FieldWidth = 0;
1357 if (match(V, m_c_And(m_Value(Val), m_APInt(Mask))) && Mask->isMask())
1358 FieldWidth = Mask->popcount();
1359 else if (match(V, m_ZExt(m_Value(Val))))
1360 FieldWidth = Val->getType()->getIntegerBitWidth();
1361 if (FieldWidth != 0) {
1362 if (std::optional<std::pair<Value *, unsigned>> Field =
1363 MatchLowField(Val, FieldWidth))
1364 return std::make_tuple(Field->first, FieldWidth, Field->second);
1365 return std::nullopt;
1366 }
1367 unsigned LaneWidth = V->getType()->getIntegerBitWidth();
1368 Value *Src;
1369 const APInt *Amt;
1370 if (match(V, m_Trunc(m_LShr(m_Value(Src), m_APInt(Amt))))) {
1371 unsigned SrcWidth = Src->getType()->getIntegerBitWidth();
1372 uint64_t ShAmt = Amt->getLimitedValue(SrcWidth);
1373 // The field itself, if the lane width is the field width.
1374 if (std::optional<unsigned> Offset =
1375 GetFieldOffset(Amt, SrcWidth, LaneWidth))
1376 return std::make_tuple(Src, LaneWidth, *Offset);
1377 // The zero-extended top field of the source.
1378 unsigned FieldWidth = SrcWidth - ShAmt;
1379 if (FieldWidth > 0 && FieldWidth < LaneWidth && ShAmt % FieldWidth == 0)
1380 return std::make_tuple(Src, FieldWidth, ShAmt / FieldWidth);
1381 return std::nullopt;
1382 }
1383 if (match(V, m_LShr(m_Value(Src), m_APInt(Amt)))) {
1384 // The zero-extended top field of the source, if the result keeps exactly
1385 // one field. Look through a truncation of the shifted value.
1386 unsigned ShfWidth = Src->getType()->getIntegerBitWidth();
1387 uint64_t ShAmt = Amt->getLimitedValue(ShfWidth);
1388 unsigned FieldWidth = ShfWidth - ShAmt;
1389 if (FieldWidth > 0 && ShAmt % FieldWidth == 0) {
1390 match(Src, m_Trunc(m_Value(Src)));
1391 return std::make_tuple(Src, FieldWidth, ShAmt / FieldWidth);
1392 }
1393 return std::nullopt;
1394 }
1395 if (match(V, m_Trunc(m_Value(Src))))
1396 return std::make_tuple(Src, LaneWidth, 0u);
1397 return std::nullopt;
1398}
1399
1400std::optional<std::tuple<Value *, unsigned, SmallVector<int>>>
1402 // Splats are emitted as broadcasts, sub-fields of a constant are folded.
1403 // The bitcast to the field vector maps lane 0 to the least significant
1404 // field on little-endian targets only.
1405 if (VL.size() < 2 || !VL.front()->getType()->isIntegerTy() || isSplat(VL) ||
1406 DL.isBigEndian())
1407 return std::nullopt;
1408 Value *Src = nullptr;
1409 unsigned FieldWidth = 0;
1411 for (auto [Idx, V] : make_filter_range(enumerate(VL), [](const auto &P) {
1412 return !isa<UndefValue>(P.value());
1413 })) {
1414 if (V->getType() != VL.front()->getType())
1415 return std::nullopt;
1416 std::optional<std::tuple<Value *, unsigned, unsigned>> Field =
1418 if (!Field || (Src && (Src != std::get<0>(*Field) ||
1419 FieldWidth != std::get<1>(*Field))))
1420 return std::nullopt;
1421 Src = std::get<0>(*Field);
1422 FieldWidth = std::get<1>(*Field);
1423 Mask[Idx] = std::get<2>(*Field);
1424 }
1425 // The field width is a whole number of bytes and divides the source
1426 // exactly, same as for the packing layout, so the source bitcasts to the
1427 // field vector.
1428 if (!Src || isa<Constant>(Src) || FieldWidth % 8 != 0 ||
1429 Src->getType()->getIntegerBitWidth() % FieldWidth != 0)
1430 return std::nullopt;
1431 // The same field in every lane is a splat, emitted as a broadcast.
1432 if (all_of(Mask, [First = *find_if(Mask, not_equal_to(PoisonMaskElem))](
1433 int MaskElt) {
1434 return MaskElt == PoisonMaskElem || MaskElt == First;
1435 }))
1436 return std::nullopt;
1437 return std::make_tuple(Src, FieldWidth, std::move(Mask));
1438}
1439
1440/// Deeper than the standard analysis recursion depth to keep the numeric
1441/// bound precise through arithmetic carry chains.
1443
1444APInt getScalarMaxValue(const Value *V, unsigned Depth) {
1445 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1447 if (Depth > MaxBitPackAnalysisDepth || !V->getType()->isIntegerTy())
1448 return Unknown;
1449 const APInt *C, *Amt;
1450 if (match(V, m_APInt(C)))
1451 return *C;
1452 Value *L, *R;
1453 if (match(V, m_Add(m_Value(L), m_Value(R))) ||
1454 match(V, m_Or(m_Value(L), m_Value(R))) ||
1455 match(V, m_Xor(m_Value(L), m_Value(R))))
1456 return getScalarMaxValue(L, Depth + 1)
1458 if (match(V, m_NUWSub(m_Value(L), m_Value(R))))
1459 return getScalarMaxValue(L, Depth + 1);
1460 if (match(V, m_Mul(m_Value(L), m_Value(R))))
1461 return getScalarMaxValue(L, Depth + 1)
1463 if (match(V, m_And(m_Value(L), m_Value(R))))
1464 return APIntOps::umin(getScalarMaxValue(L, Depth + 1),
1465 getScalarMaxValue(R, Depth + 1));
1466 if (match(V, m_LShr(m_Value(L), m_APInt(Amt))) && Amt->ult(BitWidth))
1467 return getScalarMaxValue(L, Depth + 1).lshr(*Amt);
1468 if (match(V, m_Shl(m_Value(L), m_APInt(Amt))) && Amt->ult(BitWidth)) {
1469 APInt LMax = getScalarMaxValue(L, Depth + 1);
1470 return LMax.getActiveBits() + Amt->getZExtValue() <= BitWidth
1471 ? LMax.shl(*Amt)
1472 : Unknown;
1473 }
1474 if (match(V, m_ZExt(m_Value(L))))
1475 return getScalarMaxValue(L, Depth + 1).zext(BitWidth);
1476 if (match(V, m_Trunc(m_Value(L)))) {
1477 APInt Max = getScalarMaxValue(L, Depth + 1);
1478 return Max.getActiveBits() <= BitWidth ? Max.trunc(BitWidth) : Unknown;
1479 }
1480 if (match(V, m_SExt(m_Value(L)))) {
1481 APInt Max = getScalarMaxValue(L, Depth + 1);
1482 return Max.isNonNegative() ? Max.zext(BitWidth) : Unknown;
1483 }
1484 Value *F;
1485 if (match(V, m_Select(m_Value(), m_Value(L), m_Value(F))))
1486 return APIntOps::umax(getScalarMaxValue(L, Depth + 1),
1487 getScalarMaxValue(F, Depth + 1));
1488 return Unknown;
1489}
1490
1491std::optional<BitPackInfo> computeBitPackInfo(unsigned BitWidth,
1492 ArrayRef<APInt> PossibleBits,
1493 ArrayRef<uint64_t> ShlAmts,
1494 ArrayRef<APInt> Masks) {
1495 unsigned NumElts = PossibleBits.size();
1496 BitPackInfo Info;
1497 Info.LShrAmts.assign(NumElts, 0);
1498 for (unsigned Idx : seq(NumElts)) {
1499 APInt Possible = PossibleBits[Idx].shl(ShlAmts[Idx]) & Masks[Idx];
1500 if (Possible.isZero())
1501 continue;
1502 unsigned Lo, W;
1503 if (!Possible.isShiftedMask(Lo, W))
1504 return std::nullopt;
1505 if (Info.FieldWidth == 0) {
1506 if (W % 8 != 0 || BitWidth % W != 0)
1507 return std::nullopt;
1508 Info.FieldWidth = W;
1509 Info.LaneOfField.assign(BitWidth / W, BitPackInfo::NoLane);
1510 }
1511 if (W != Info.FieldWidth || Lo % W != 0)
1512 return std::nullopt;
1513 unsigned Field = Lo / W;
1514 if (Info.LaneOfField[Field] != BitPackInfo::NoLane)
1515 return std::nullopt;
1516 Info.LaneOfField[Field] = Idx;
1517 Info.LShrAmts[Idx] = Lo - ShlAmts[Idx];
1518 }
1519 if (Info.FieldWidth == 0)
1520 return std::nullopt;
1521 return Info;
1522}
1523
1524SmallVector<int> getBitPackMask(const BitPackInfo &Info, unsigned NumBytes,
1525 unsigned NumElts, unsigned BytesPerLane) {
1526 unsigned BytesPerField = Info.FieldWidth / 8;
1527 SmallVector<int> Mask;
1528 for (unsigned J : seq(NumBytes)) {
1529 unsigned Lane = Info.LaneOfField[J / BytesPerField];
1530 Mask.push_back(Lane == BitPackInfo::NoLane
1531 ? (int)(NumElts * BytesPerLane)
1532 : (int)(Lane * BytesPerLane + J % BytesPerField));
1533 }
1534 return Mask;
1535}
1536
1538 Type *ResultTy, unsigned ShiftWidth, unsigned &NumInsts) {
1539 NumInsts = 0;
1540 auto *VecTy = cast<FixedVectorType>(X->getType());
1541 unsigned BitWidth = VecTy->getScalarSizeInBits();
1542 assert(BitWidth % 8 == 0 &&
1543 "The byte-multiple field width divides the result bit width.");
1544 unsigned NumElts = VecTy->getNumElements();
1545 Value *Y = X;
1546 if (ShiftWidth != BitWidth) {
1547 // Compacting a zext back to its source is free, use it directly.
1548 if (auto *Z = dyn_cast<ZExtInst>(X);
1549 Z && Z->getSrcTy()->getScalarSizeInBits() == ShiftWidth)
1550 Y = Z->getOperand(0);
1551 else {
1552 Y = Builder.CreateTrunc(
1553 Y, FixedVectorType::get(IntegerType::get(X->getContext(), ShiftWidth),
1554 NumElts));
1555 ++NumInsts;
1556 }
1557 }
1558 if (Info.needsShift()) {
1560 for (uint64_t A : Info.LShrAmts)
1561 Amts.push_back(
1562 ConstantInt::get(IntegerType::get(X->getContext(), ShiftWidth), A));
1563 Y = Builder.CreateLShr(Y, ConstantVector::get(Amts));
1564 ++NumInsts;
1565 }
1566 unsigned InBytes = NumElts * (ShiftWidth / 8);
1567 auto *ByteTy = FixedVectorType::get(Builder.getInt8Ty(), InBytes);
1569 Info, ResultTy->getScalarSizeInBits() / 8, NumElts, ShiftWidth / 8);
1570 // Fields in lane order, possibly reversed, are a truncation of the shifted
1571 // lanes. A reversal of byte fields is a bswap.
1572 bool IsReversed = equal(Info.LaneOfField, reverse(seq<unsigned>(NumElts)));
1573 if (IsReversed || equal(Info.LaneOfField, seq<unsigned>(NumElts))) {
1574 Value *Fields = Builder.CreateTrunc(
1575 Y, Y->getType()->getWithNewBitWidth(Info.FieldWidth));
1576 NumInsts += 1 + (Info.FieldWidth != ShiftWidth) + IsReversed;
1577 if (IsReversed && Info.FieldWidth == 8)
1578 return Builder.CreateUnaryIntrinsic(
1579 Intrinsic::bswap, Builder.CreateBitCast(Fields, ResultTy));
1580 if (IsReversed)
1581 Fields = Builder.CreateVectorReverse(Fields);
1582 return Builder.CreateBitCast(Fields, ResultTy);
1583 }
1584 Value *Packed = Builder.CreateShuffleVector(
1585 Builder.CreateBitCast(Y, ByteTy),
1586 is_contained(Info.LaneOfField, BitPackInfo::NoLane)
1587 ? Constant::getNullValue(ByteTy)
1588 : PoisonValue::get(ByteTy),
1589 Mask);
1590 NumInsts += 3;
1591 return Builder.CreateBitCast(Packed, ResultTy);
1592}
1593
1596 findDbgValues(&From, DVRs);
1597 auto *ExI = dyn_cast<Instruction>(&To);
1598 for (DbgVariableRecord *DVR : DVRs) {
1599 if (!DVR->isDbgValue())
1600 continue;
1601 Instruction *MarkedI = DVR->getInstruction();
1602 if (ExI && MarkedI->getParent() != ExI->getParent())
1603 continue;
1604 if (!ExI || ExI->comesBefore(MarkedI)) {
1605 DVR->replaceVariableLocationOp(&From, &To);
1606 continue;
1607 }
1608 DebugVariableAggregate Var(DVR);
1609 auto HasSameVar = [&](auto Records) {
1610 return any_of(filterDbgVars(Records),
1611 [&](const DbgVariableRecord &Other) {
1612 return DebugVariableAggregate(&Other) == Var;
1613 });
1614 };
1615 if (HasSameVar(make_range(std::next(DVR->getIterator()),
1616 MarkedI->getDbgRecordRange().end())) ||
1617 any_of(make_range(std::next(MarkedI->getIterator()),
1618 std::next(ExI->getIterator())),
1619 [&](const Instruction &I) {
1620 return HasSameVar(I.getDbgRecordRange());
1621 }))
1622 continue;
1623 DbgVariableRecord *NewDVR = DVR->clone();
1624 NewDVR->replaceVariableLocationOp(&From, &To);
1625 ExI->getParent()->insertDbgRecordAfter(NewDVR, ExI);
1626 }
1627}
1628
1630 const InsertElementInst *IE2) {
1631 if (IE1 == IE2)
1632 return false;
1633 const auto *I1 = IE1;
1634 const auto *I2 = IE2;
1635 const InsertElementInst *PrevI1;
1636 const InsertElementInst *PrevI2;
1637 unsigned Idx1 = *getElementIndex(IE1);
1638 unsigned Idx2 = *getElementIndex(IE2);
1639 do {
1640 if (I2 == IE1)
1641 return true;
1642 if (I1 == IE2)
1643 return false;
1644 PrevI1 = I1;
1645 PrevI2 = I2;
1646 if (I1 && (I1 == IE1 || I1->hasOneUse()) &&
1647 getElementIndex(I1).value_or(Idx2) != Idx2)
1648 I1 = dyn_cast<InsertElementInst>(I1->getOperand(0));
1649 if (I2 && ((I2 == IE2 || I2->hasOneUse())) &&
1650 getElementIndex(I2).value_or(Idx1) != Idx1)
1651 I2 = dyn_cast<InsertElementInst>(I2->getOperand(0));
1652 } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2));
1653 llvm_unreachable("Two different buildvectors not expected.");
1654}
1655
1657 if (DebugLoc DL = PN.getDebugLoc())
1658 return DL;
1659 return DebugLoc::getUnknown();
1660}
1661
1662std::optional<unsigned> getAggregateSize(Instruction *InsertInst) {
1663 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
1664 return cast<FixedVectorType>(IE->getType())->getNumElements();
1665
1666 unsigned AggregateSize = 1;
1667 auto *IV = cast<InsertValueInst>(InsertInst);
1668 Type *CurrentType = IV->getType();
1669 do {
1670 if (auto *ST = dyn_cast<StructType>(CurrentType)) {
1671 for (auto *Elt : ST->elements())
1672 if (Elt != ST->getElementType(0)) // check homogeneity
1673 return std::nullopt;
1674 AggregateSize *= ST->getNumElements();
1675 CurrentType = ST->getElementType(0);
1676 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
1677 AggregateSize *= AT->getNumElements();
1678 CurrentType = AT->getElementType();
1679 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
1680 AggregateSize *= VT->getNumElements();
1681 return AggregateSize;
1682 } else if (CurrentType->isSingleValueType()) {
1683 return AggregateSize;
1684 } else {
1685 return std::nullopt;
1686 }
1687 } while (true);
1688}
1689
1691 assert(L && "Expected valid loop");
1692 auto IsLoopInvariant = [&](const Loop *L, ArrayRef<Value *> VL) {
1694 [L](Instruction *I) { return L->isLoopInvariant(I); });
1695 };
1696 while (L && IsLoopInvariant(L, VL))
1697 L = L->getParentLoop();
1698 return L;
1699}
1700
1702 unsigned LoopAwareTripCount) {
1703 if (LoopAwareTripCount == 0)
1704 return 1;
1705 unsigned Scale = SE.getSmallConstantTripCount(L);
1706 if (Scale == 0)
1707 Scale = getLoopEstimatedTripCount(const_cast<Loop *>(L)).value_or(0);
1708 if (Scale != 0) {
1709 // Multiple exiting blocks - choose the minimum between trip count (scale)
1710 // and LoopAwareTripCount, since the multiple exit loops can be terminated
1711 // early.
1712 if (!L->getExitingBlock())
1713 return std::min<unsigned>(LoopAwareTripCount, Scale);
1714 return Scale;
1715 }
1716 return LoopAwareTripCount;
1717}
1718
1721 function_ref<Value *(InsertElementInst *)> GetBaseOperand) {
1722 // Instructions must be from the same basic blocks.
1723 if (VU->getParent() != V->getParent())
1724 return false;
1725 // Checks if 2 insertelements are from the same buildvector.
1726 if (VU->getType() != V->getType())
1727 return false;
1728 // Multiple used inserts are separate nodes.
1729 if (!VU->hasOneUse() && !V->hasOneUse())
1730 return false;
1731 auto *IE1 = VU;
1732 auto *IE2 = V;
1733 std::optional<unsigned> Idx1 = getElementIndex(IE1);
1734 std::optional<unsigned> Idx2 = getElementIndex(IE2);
1735 if (Idx1 == std::nullopt || Idx2 == std::nullopt)
1736 return false;
1737 // Go through the vector operand of insertelement instructions trying to find
1738 // either VU as the original vector for IE2 or V as the original vector for
1739 // IE1.
1741 bool IsReusedIdx = false;
1742 do {
1743 if (IE2 == VU && !IE1)
1744 return VU->hasOneUse();
1745 if (IE1 == V && !IE2)
1746 return V->hasOneUse();
1747 if (IE1 && IE1 != V) {
1748 unsigned Idx1 = getElementIndex(IE1).value_or(*Idx2);
1749 IsReusedIdx |= ReusedIdx.test(Idx1);
1750 ReusedIdx.set(Idx1);
1751 if ((IE1 != VU && !IE1->hasOneUse()) || IsReusedIdx)
1752 IE1 = nullptr;
1753 else
1754 IE1 = dyn_cast_if_present<InsertElementInst>(GetBaseOperand(IE1));
1755 }
1756 if (IE2 && IE2 != VU) {
1757 unsigned Idx2 = getElementIndex(IE2).value_or(*Idx1);
1758 IsReusedIdx |= ReusedIdx.test(Idx2);
1759 ReusedIdx.set(Idx2);
1760 if ((IE2 != V && !IE2->hasOneUse()) || IsReusedIdx)
1761 IE2 = nullptr;
1762 else
1763 IE2 = dyn_cast_if_present<InsertElementInst>(GetBaseOperand(IE2));
1764 }
1765 } while (!IsReusedIdx && (IE1 || IE2));
1766 return false;
1767}
1768
1769} // namespace llvm::slpvectorizer
unsigned NumParts
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
AMDGPU Register Bank Select
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Hexagon Common GEP
#define _
static MaybeAlign getAlign(Value *Ptr)
IRTranslator LLVM IR MI
static std::pair< Value *, APInt > getMask(Value *WideMask, unsigned Factor, ElementCount LeafValueEC)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
Provides some synthesis utilities to produce sequences of values.
This file defines the SmallPtrSet class.
static unsigned getScalarSizeInBits(Type *Ty)
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:230
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1532
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1115
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
bool isShiftedMask() const
Return true if this APInt value contains a non-empty sequence of ones with the remainder zero.
Definition APInt.h:506
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
Definition APInt.h:471
LLVM_ABI APInt uadd_sat(const APInt &RHS) const
Definition APInt.cpp:2083
APInt shl(unsigned shiftAmt) const
Left-shift function.
Definition APInt.h:875
LLVM_ABI APInt umul_sat(const APInt &RHS) const
Definition APInt.cpp:2124
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
APInt lshr(unsigned shiftAmt) const
Logical right-shift function.
Definition APInt.h:853
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
bool empty() const
Check if the array is empty.
Definition ArrayRef.h:136
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
const T & consume_front()
consume_front() - Returns the first element and drops it from ArrayRef.
Definition ArrayRef.h:156
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
Definition BasicBlock.h:62
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
This class represents a function call, abstracting a target machine's calling convention.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
static LLVM_ABI Constant * getBinOpAbsorber(unsigned Opcode, Type *Ty, bool AllowLHSConstant=false)
Return the absorbing element for the given binary operation, i.e.
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:44
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
Record of a variable value-assignment, aka a non instruction representation of the dbg....
LLVM_ABI void replaceVariableLocationOp(Value *OldValue, Value *NewValue, bool AllowEmpty=false)
LLVM_ABI DbgVariableRecord * clone() const
A debug info location.
Definition DebugLoc.h:127
static DebugLoc getUnknown()
Definition DebugLoc.h:154
Identifies a unique instance of a whole variable (discards/ignores fragment information).
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
This instruction extracts a single (scalar) element from a VectorType value.
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
This instruction inserts a single (scalar) element into a VectorType value.
VectorType * getType() const
Overload to return most specific vector type.
iterator_range< simple_ilist< DbgRecord >::iterator > getDbgRecordRange() const
Return a range over the DbgRecords attached to this instruction.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isShift() const
bool isIntDivRem() const
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
An instruction for reading from memory.
Value * getPointerOperand()
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This is the common base class for memset/memcpy/memmove.
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
The main scalar evolution driver.
LLVM_ABI unsigned getSmallConstantTripCount(const Loop *L)
Returns the exact trip count of the loop if we can compute it, and the result is a small constant.
This class represents the LLVM 'select' instruction.
static LLVM_ABI bool isIdentityMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector without lane crossin...
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
SmallBitVector & set()
bool test(unsigned Idx) const
Returns true if bit Idx is set.
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
bool all() const
Returns true if all bits are set.
size_type count() const
Returns the number of bits which are set.
SmallBitVector & reset()
bool none() const
Returns true if none of the bits are set.
size_type size() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void swap(SmallVectorImpl &RHS)
void resize(size_type N)
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
An instruction for storing to memory.
Provides information about what library functions are available for the current target.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
@ SK_Select
Selects elements from the corresponding lane of either source operand.
@ SK_PermuteSingleSrc
Shuffle elements of single source vector with any shuffle mask.
@ SK_PermuteTwoSrc
Merge elements from two source vectors into one with any shuffle mask.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:258
bool isSingleValueType() const
Return true if the type is a valid type for a register in codegen.
Definition Type.h:306
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.h:354
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
bool hasUseList() const
Check if this Value has a use-list.
Definition Value.h:346
LLVM_ABI bool hasNUsesOrMore(unsigned N) const
Return true if this value has N uses or more.
Definition Value.cpp:150
iterator_range< use_iterator > uses()
Definition Value.h:382
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
An efficient, type-erasing, non-owning reference to a callable.
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
A raw_ostream that writes to an std::string.
Caches the results of the expensive analyses that are queried repeatedly for the same values while th...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const APInt & umin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be unsigned.
Definition APInt.h:2284
const APInt & umax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be unsigned.
Definition APInt.h:2289
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
BinaryOp_match< LHS, RHS, Instruction::And, true > m_c_And(const LHS &L, const RHS &R)
Matches an And with LHS and RHS in either order.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
BinaryOp_match< LHS, RHS, Instruction::Xor > m_Xor(const LHS &L, const RHS &R)
bool match(Val *V, const Pattern &P)
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Sub, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWSub(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
A private "module" namespace for types and utilities used by this pass.
std::optional< unsigned > getExtractIndex(const Instruction *E)
Definition SLPUtils.cpp:310
template SmallBitVector isUndefVector< true >(const Value *, const SmallBitVector &)
Constant * getReassocIdentity(unsigned Opcode, Type *Ty, bool Negated)
Definition SLPUtils.cpp:52
Value * createInsertVector(IRBuilderBase &Builder, Value *Vec, Value *V, unsigned Index, function_ref< Value *(Value *, Value *, ArrayRef< int >)> Generator)
Creates subvector insert.
Definition SLPUtils.cpp:705
bool areAllOperandsNonInsts(Value *V)
Checks if the provided value does not require scheduling.
Definition SLPUtils.cpp:479
Instruction * findPairedDivision(unsigned Opcode, Value *X, Value *Y, const BasicBlock *BB, function_ref< bool(Instruction *)> Pred)
Definition SLPUtils.cpp:754
std::optional< unsigned > getElementIndex(const Value *Inst, unsigned Offset)
Definition SLPUtils.cpp:264
DebugLoc getDebugLocFromPHI(const PHINode &PN)
bool isBinOpIdentityConstant(const Value *V, unsigned Opcode, bool Negated)
Definition SLPUtils.cpp:59
bool doesInTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, TargetLibraryInfo *TLI, const TargetTransformInfo *TTI)
Definition SLPUtils.cpp:849
bool isCopyableGEPAddressVector(ArrayRef< Value * > PointerOps)
Checks if the pointers PointerOps of the gathered loads, which are not compatible in the usual sense ...
Definition SLPUtils.cpp:987
std::optional< std::tuple< Value *, unsigned, SmallVector< int > > > matchGatheredExtractedFields(ArrayRef< Value * > VL, const DataLayout &DL)
Checks if the values in VL are zero-extended sub-fields of the same wider integer scalar.
MemoryLocation getLocation(Instruction *I)
Definition SLPUtils.cpp:877
std::optional< BitPackInfo > computeBitPackInfo(unsigned BitWidth, ArrayRef< APInt > PossibleBits, ArrayRef< uint64_t > ShlAmts, ArrayRef< APInt > Masks)
Computes the bitfield packing layout from the per-lane possibly set bits of the source values,...
bool isSelectedBaseLoad(Type *ScalarTy, ArrayRef< Value * > PointerOps, const DataLayout &DL, Value *&TrueBase, Value *&FalseBase, SmallVectorImpl< Value * > &Conditions)
Checks if the loads with scalar type ScalarTy and pointer operands PointerOps are each (optionally vi...
Definition SLPUtils.cpp:895
SmallBitVector getAltInstrMask(ArrayRef< Value * > VL, Type *ScalarTy, unsigned Opcode0, unsigned Opcode1)
SmallBitVector isUndefVector(const Value *V, const SmallBitVector &UseMask)
Checks if the given value is actually an undefined constant vector.
Definition SLPUtils.cpp:799
Intrinsic::ID getMaskedDivRemIntrinsic(unsigned Opcode)
bool isUsedOutsideBlock(Value *V)
Checks if the provided value does not require scheduling.
Definition SLPUtils.cpp:490
bool doesNotNeedToSchedule(ArrayRef< Value * > VL)
Checks if the specified array of instructions does not require scheduling.
Definition SLPUtils.cpp:507
std::optional< unsigned > getInsertExtractIndex(const Value *Inst, unsigned Offset)
Definition SLPUtils.cpp:446
void redirectDbgValues(Instruction &From, Value &To)
The debug values of the erased From are kept on its replacement To.
void reorderScalars(SmallVectorImpl< Value * > &Scalars, ArrayRef< int > Mask)
Reorders the list of scalars in accordance with the given Mask.
Definition SLPUtils.cpp:332
SmallVector< int > getBitPackMask(const BitPackInfo &Info, unsigned NumBytes, unsigned NumElts, unsigned BytesPerLane)
Returns the byte shuffle mask packing the per-lane fields of the shifted lanes (BytesPerLane bytes ea...
SelectInst * getBlendedLoadSelect(ArrayRef< Value * > VL)
Returns the select instruction picking between the candidate base pointers of the blended loads VL.
Definition SLPUtils.cpp:948
static std::optional< std::tuple< Value *, unsigned, unsigned > > matchExtractedField(Value *V)
Checks if V is a zero-extended sub-field of a wider integer scalar.
bool allSameType(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:439
bool dominatesAllUses(const DominatorTree &DT, const Instruction &InsertPt, const Instruction &I)
Definition SLPUtils.cpp:741
void combineOrders(MutableArrayRef< unsigned > Order, ArrayRef< unsigned > SecondaryOrder)
Fills unset elements of Order (marked with the sentinel value equal to the order size) with the corre...
Definition SLPUtils.cpp:417
bool allSameOpcode(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:292
bool isSplat(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:173
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:118
std::string shortBundleName(ArrayRef< Value * > VL, int Idx)
Print a short descriptor of the instruction bundle suitable for debug output.
Definition SLPUtils.cpp:135
unsigned getLoopTripCount(const Loop *L, ScalarEvolution &SE, unsigned LoopAwareTripCount)
bool isOnceUsedSeed(const Instruction *I)
Returns true if I forms a vectorizable bundle on its own and its single user does not tear the vector...
unsigned getPartNumElems(unsigned Size, unsigned NumParts)
Returns power-of-2 number of elements in a single register (part), given the total number of elements...
Definition SLPUtils.cpp:126
constexpr unsigned MaxBitPackAnalysisDepth
Deeper than the standard analysis recursion depth to keep the numeric bound precise through arithmeti...
bool isCommutableOperand(const Instruction *I, Value *ValWithUses, unsigned Op, bool IsCopyable)
Checks if the operand is commutative.
Definition SLPUtils.cpp:236
Align computeBlendedLoadBaseAlignment(ArrayRef< Value * > VL, const DataLayout &DL)
Returns the alignment of the shared base pointer of a blended load for the loads VL.
Definition SLPUtils.cpp:935
TargetTransformInfo::TargetCostKind getSLPCostKind(const Function *F)
bool isReverseOrder(ArrayRef< unsigned > Order)
Check if Order represents reverse order.
Definition SLPUtils.cpp:396
Type * getCommonGEPIndexType(ArrayRef< Value * > VL, Instruction *VL0, function_ref< bool(Value *)> IsGEPLane, const DataLayout &DL)
Returns the common type for the indices of the single-index GEP lanes of a GEP node with the main op ...
Definition SLPUtils.cpp:955
void transformScalarShuffleIndiciesToVector(unsigned VecTyNumElements, SmallVectorImpl< int > &Mask)
Definition SLPUtils.cpp:512
bool areTwoInsertFromSameBuildVector(InsertElementInst *VU, InsertElementInst *V, function_ref< Value *(InsertElementInst *)> GetBaseOperand)
Check if two insertelement instructions are from the same buildvector.
SmallVector< int > calculateShufflevectorMask(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:567
SmallBitVector buildUseMask(int VF, ArrayRef< int > Mask, UseMask MaskArg)
Prepares a use bitset for the given mask either for the first argument or for the second.
Definition SLPUtils.cpp:782
bool isCommutative(const Instruction *I, const Value *ValWithUses, bool IsCopyable)
Definition SLPUtils.cpp:196
template SmallBitVector isUndefVector< false >(const Value *, const SmallBitVector &)
unsigned getNumberOfPotentiallyCommutativeOps(Instruction *I)
Definition SLPUtils.cpp:254
bool allConstant(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:167
template std::optional< unsigned > getInsertExtractIndex< InsertElementInst >(const Value *, unsigned)
void inversePermutation(ArrayRef< unsigned > Indices, SmallVectorImpl< int > &Mask)
Compute the inverse permutation Mask of Indices.
Definition SLPUtils.cpp:323
bool allSameBlock(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:145
bool isReassocChainLink(const Instruction *I)
Definition SLPUtils.cpp:90
Intrinsic::ID isEquivalentIntrinsicID(Intrinsic::ID LHS, Intrinsic::ID RHS)
Checks if LHS and RHS are the same intrinsic, or one is llvm.fma and the other is llvm....
Definition SLPUtils.cpp:187
std::optional< TargetTransformInfo::ShuffleKind > isFixedVectorShuffle(ArrayRef< Value * > VL, SmallVectorImpl< int > &Mask, AssumptionCache *AC, SLPAnalysisCache &Cache)
Checks if the vector of instructions can be represented as a shuffle, like: x0 = extractelement <4 x ...
Definition SLPUtils.cpp:607
UseMask
Specifies the way the mask should be analyzed for undefs/poisonous elements in the shuffle mask.
Definition SLPUtils.h:328
@ SecondArg
The mask is expected to be for permutation of 2 vectors, check for the mask elements for the second a...
Definition SLPUtils.h:332
@ UndefsAsMask
Consider undef mask elements (-1) as placeholders for future shuffle elements and mark them as ones a...
Definition SLPUtils.h:335
@ FirstArg
The mask is expected to be for permutation of 1-2 vectors, check for the mask elements for the first ...
Definition SLPUtils.h:329
void reorderOrder(SmallVectorImpl< unsigned > &Order, ArrayRef< int > Mask, bool BottomOrder)
Reorders the given Order according to the given Mask.
Definition SLPUtils.cpp:352
static void collectNarrowedLeavesImpl(Value *V, unsigned RdxOpcode, unsigned WideBW, NarrowedChainState S, unsigned Depth, unsigned MaxDepth, SmallVectorImpl< NarrowedLeafInfo > &Leaves, SmallVectorImpl< Instruction * > &ChainInsts)
void reorderReuses(SmallVectorImpl< int > &Reuses, ArrayRef< int > Mask)
Reorders the given Reuses mask according to the given Mask.
Definition SLPUtils.cpp:342
void addMask(SmallVectorImpl< int > &Mask, ArrayRef< int > SubMask, bool ExtendingManyInputs)
Shuffles Mask in accordance with the given SubMask.
bool isSimple(Instruction *I)
Definition SLPUtils.cpp:885
Instruction * lookThroughCastRoundTrip(Value *V, bool MustBeElidable)
If V is a single-use fpext of a single-use fptrunc forming a round-trip back to the type of V,...
std::optional< unsigned > getAggregateSize(Instruction *InsertInst)
const LoadInst * getLoadOfUndefTolerantBinOp(const Value *V)
Definition SLPUtils.cpp:70
bool isUndefTolerantBinOp(const Value *V)
Definition SLPUtils.cpp:64
APInt getScalarMaxValue(const Value *V, unsigned Depth)
Returns a saturating unsigned upper bound of the scalar V.
Value * buildBitPack(IRBuilderBase &Builder, Value *X, const BitPackInfo &Info, Type *ResultTy, unsigned ShiftWidth, unsigned &NumInsts)
Builds the bitfield packing of X into ResultTy per the layout and the shift width.
unsigned getShufflevectorNumGroups(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:527
const Loop * findInnermostNonInvariantLoop(const Loop *L, ArrayRef< Value * > VL)
SmallVector< Constant * > replicateMask(ArrayRef< Constant * > Val, unsigned VF)
Replicates the given Val VF times.
unsigned getReassocCombineOpcode(unsigned Opcode)
Definition SLPUtils.cpp:79
bool isVectorLikeInstWithConstOps(Value *V)
Checks if V is one of vector-like instructions, i.e.
Definition SLPUtils.cpp:98
bool doesNotNeedToBeScheduled(Value *V)
Checks if the specified value does not require scheduling.
Definition SLPUtils.cpp:503
unsigned getNumElems(unsigned Size, unsigned PartNumElems, unsigned Part)
Returns correct remaining number of elements, considering total amount Size, (power-of-2 number) of e...
Definition SLPUtils.cpp:130
constexpr int UsesLimit
Limit of the number of uses for potentially transformed instructions/values, used in checks to avoid ...
Definition SLPUtils.h:61
bool isFirstInsertElement(const InsertElementInst *IE1, const InsertElementInst *IE2)
void collectNarrowedLeaves(Value *V, unsigned RdxOpcode, unsigned WideBW, unsigned MaxDepth, SmallVectorImpl< NarrowedLeafInfo > &Leaves, SmallVectorImpl< Instruction * > &ChainInsts)
Recursively collects the narrow leaves of the widened reduction value V.
bool isRepeatedNonIdentityClusteredMask(ArrayRef< int > Mask, unsigned Sz)
Checks if the given mask is a "clustered" mask with the same clusters of size Sz, which are not ident...
Definition SLPUtils.cpp:405
bool isConstant(Value *V)
Definition SLPUtils.cpp:48
static bool isNonProfitableIndex(const Instruction *I)
Returns true if I is a part of a single-use chain, computing an address, which does not pay off the v...
Value * createExtractVector(IRBuilderBase &Builder, Value *Vec, unsigned SubVecVF, unsigned Index)
Generates subvector extract.
Definition SLPUtils.cpp:734
template std::optional< unsigned > getInsertExtractIndex< ExtractElementInst >(const Value *, unsigned)
void fixupOrderingIndices(MutableArrayRef< unsigned > Order)
Order may have elements assigned special value (size) which is out of bounds.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
constexpr auto not_equal_to(T &&Arg)
Functor variant of std::not_equal_to that can be used as a UnaryPredicate in functional algorithms li...
Definition STLExtras.h:2196
LLVM_ABI std::optional< unsigned > getLoopEstimatedTripCount(Loop *L, unsigned *EstimatedLoopInvocationWeight=nullptr)
Return either:
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI Intrinsic::ID getVectorIntrinsicIDForCall(const CallInst *CI, const TargetLibraryInfo *TLI)
Returns intrinsic ID for call.
LLVM_ABI void findDbgValues(Value *V, SmallVectorImpl< DbgVariableRecord * > &DbgVariableRecords)
Finds the dbg.values describing a value.
@ Unknown
Not known to have no common set bits.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr from_range_t from_range
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool isVectorizedTy(Type *Ty)
Returns true if Ty is a vector type or a struct of vector types where all vector types share the same...
T bit_ceil(T Value)
Returns the smallest integral power of two no smaller than Value if Value is nonzero.
Definition bit.h:362
auto make_isa_range(RangeT &&Range)
Return a range over Range containing only elements for which isa<T> holds, casting each of them to T.
Definition STLExtras.h:567
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
constexpr unsigned MaxAnalysisRecursionDepth
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
ElementCount getVectorizedTypeVF(Type *Ty)
Returns the number of vector elements for a vectorized type.
auto find_if_not(R &&Range, UnaryPredicate P)
Definition STLExtras.h:1793
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1769
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
constexpr int PoisonMaskElem
iterator_range(Container &&) -> iterator_range< llvm::detail::IterOfRange< Container > >
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
Definition MathExtras.h:389
@ Other
Any other memory.
Definition ModRef.h:68
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
Definition ModRef.h:74
TargetTransformInfo TTI
DWARFExpression::Operation Op
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
bool equal(L &&LRange, R &&RRange)
Wrapper function around std::equal to detect if pair-wise elements between two ranges are the same.
Definition STLExtras.h:2162
static auto filterDbgVars(iterator_range< simple_ilist< DbgRecord >::iterator > R)
Filter the DbgRecord range to DbgVariableRecord types only and downcast.
LLVM_ABI bool mayHaveNonDefUseDependency(const Instruction &I)
Returns true if the result or effects of the given instructions I depend values not reachable through...
constexpr detail::IsaCheckPredicate< Types... > IsaPred
Function object wrapper for the llvm::isa type check.
Definition Casting.h:866
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
Description of a bitfield packing of vector lanes into a scalar value: every lane contributes a disjo...
Definition SLPUtils.h:514
static constexpr unsigned NoLane
Definition SLPUtils.h:515
SmallVector< uint64_t, 8 > LShrAmts
Per-lane right-shift amounts bringing the field content to the low bits.
Definition SLPUtils.h:520