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/IRBuilder.h"
35
36#include <algorithm>
37#include <numeric>
38#include <optional>
39#include <string>
40#include <type_traits>
41
42using namespace llvm;
43using namespace llvm::PatternMatch;
44
45namespace llvm::slpvectorizer {
46
50
51Constant *getReassocIdentity(unsigned Opcode, Type *Ty, bool Negated) {
52 // Subtracting -0.0 turns a -0.0 total into +0.0.
53 if (Negated && Opcode == Instruction::FAdd)
54 Opcode = Instruction::FSub;
55 return ConstantExpr::getBinOpIdentity(Opcode, Ty, /*AllowRHSConstant=*/true);
56}
57
58bool isBinOpIdentityConstant(const Value *V, unsigned Opcode, bool Negated) {
60 V == getReassocIdentity(Opcode, V->getType(), Negated);
61}
62
64 const BinaryOperator *BO;
65 return match(V, m_BinOp(BO)) && BO->getType()->isIntOrIntVectorTy() &&
66 !BO->isShift() && !BO->isIntDivRem();
67}
68
71 return nullptr;
72 for (const Value *Op : cast<BinaryOperator>(V)->operands())
73 if (const auto *LI = dyn_cast<LoadInst>(Op))
74 return LI;
75 return nullptr;
76}
77
78unsigned getReassocCombineOpcode(unsigned Opcode) {
79 switch (Opcode) {
80 case Instruction::Sub:
81 return Instruction::Add;
82 case Instruction::FSub:
83 return Instruction::FAdd;
84 default:
85 return Opcode;
86 }
87}
88
90 if (I->getOpcode() == Instruction::Sub)
91 return true;
92 if (I->getOpcode() == Instruction::FSub)
93 return I->hasAllowReassoc();
94 return I->isAssociative();
95}
96
98 auto *I = dyn_cast<Instruction>(V);
99 // Non-instructions are vector-like only if they are undef.
100 if (!I)
101 return isa<UndefValue>(V);
102 switch (I->getOpcode()) {
103 case Instruction::ExtractValue:
104 case Instruction::InsertValue:
105 return true;
106 case Instruction::ExtractElement:
107 return isa<FixedVectorType>(I->getOperand(0)->getType()) &&
108 isConstant(I->getOperand(1));
109 case Instruction::InsertElement:
110 return isa<FixedVectorType>(I->getOperand(0)->getType()) &&
111 isConstant(I->getOperand(2));
112 default:
113 return false;
114 }
115}
116
117unsigned getNumElements(Type *Ty) {
119 "ScalableVectorType is not supported.");
120 if (isVectorizedTy(Ty))
122 return 1;
123}
124
125unsigned getPartNumElems(unsigned Size, unsigned NumParts) {
126 return std::min<unsigned>(Size, bit_ceil(divideCeil(Size, NumParts)));
127}
128
129unsigned getNumElems(unsigned Size, unsigned PartNumElems, unsigned Part) {
130 return std::min<unsigned>(PartNumElems, Size - Part * PartNumElems);
131}
132
133#if !defined(NDEBUG)
134std::string shortBundleName(ArrayRef<Value *> VL, int Idx) {
135 std::string Result;
136 raw_string_ostream OS(Result);
137 if (Idx >= 0)
138 OS << "Idx: " << Idx << ", ";
139 OS << "n=" << VL.size() << " [" << *VL.front() << ", ..]";
140 return Result;
141}
142#endif
143
145 auto *It = find_if(VL, IsaPred<Instruction>);
146 if (It == VL.end())
147 return false;
150 return true;
151
152 BasicBlock *BB = I0->getParent();
153 for (Value *V : make_filter_range(iterator_range(It, VL.end()), [](Value *V) {
154 return !isa<PoisonValue>(V);
155 })) {
156 auto *II = dyn_cast<Instruction>(V);
157 if (!II)
158 return false;
159
160 if (BB != II->getParent())
161 return false;
162 }
163 return true;
164}
165
167 // Constant expressions and globals can't be vectorized like normal integer/FP
168 // constants.
169 return all_of(VL, isConstant);
170}
171
173 Value *FirstNonUndef = nullptr;
174 for (Value *V :
175 make_filter_range(VL, [](Value *V) { return !isa<UndefValue>(V); })) {
176 if (!FirstNonUndef) {
177 FirstNonUndef = V;
178 continue;
179 }
180 if (V != FirstNonUndef)
181 return false;
182 }
183 return FirstNonUndef != nullptr;
184}
185
187 if (LHS == RHS)
188 return RHS;
189 if ((LHS == Intrinsic::fma || LHS == Intrinsic::fmuladd) &&
190 (RHS == Intrinsic::fma || RHS == Intrinsic::fmuladd))
191 return Intrinsic::fma;
193}
194
195bool isCommutative(const Instruction *I, const Value *ValWithUses,
196 bool IsCopyable) {
197 // The trunc X to i1 lanes of a compare have the single operand X.
198 if (auto *Cmp = dyn_cast<CmpInst>(I))
199 return isa<CmpInst>(ValWithUses) && Cmp->isCommutative();
200 if (auto *BO = dyn_cast<BinaryOperator>(I))
201 return BO->isCommutative() ||
202 (BO->getOpcode() == Instruction::Sub && ValWithUses->hasUseList() &&
203 !ValWithUses->hasNUsesOrMore(UsesLimit) &&
204 all_of(
205 ValWithUses->uses(),
206 [&](const Use &U) {
207 // Commutative, if icmp eq/ne sub, 0
208 CmpPredicate Pred;
209 if (match(U.getUser(),
210 m_ICmp(Pred, m_Specific(U.get()), m_Zero())) &&
211 (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE))
212 return true;
213 // Commutative, if abs(sub nsw, true) or abs(sub, false).
214 // A lane without wrap flags, like an or converted to sub,
215 // does not clear nsw of the vector sub.
216 ConstantInt *Flag;
217 auto *I = dyn_cast<OverflowingBinaryOperator>(U.get());
218 return match(U.getUser(),
219 m_Intrinsic<Intrinsic::abs>(
220 m_Specific(U.get()), m_ConstantInt(Flag))) &&
221 ((!IsCopyable && I && !I->hasNoSignedWrap()) ||
222 Flag->isOne());
223 })) ||
224 (BO->getOpcode() == Instruction::FSub && ValWithUses->hasUseList() &&
225 !ValWithUses->hasNUsesOrMore(UsesLimit) &&
226 all_of(ValWithUses->uses(), [](const Use &U) {
227 return match(U.getUser(),
228 m_Intrinsic<Intrinsic::fabs>(m_Specific(U.get())));
229 }));
230 return I->isCommutative();
231}
232
233bool isCommutative(const Instruction *I) { return isCommutative(I, I); }
234
235bool isCommutableOperand(const Instruction *I, Value *ValWithUses, unsigned Op,
236 bool IsCopyable) {
237 assert(isCommutative(I, ValWithUses, IsCopyable) &&
238 "The instruction is not commutative.");
239 if (isa<CmpInst>(I))
240 return true;
241 if (auto *BO = dyn_cast<BinaryOperator>(I)) {
242 switch (BO->getOpcode()) {
243 case Instruction::Sub:
244 case Instruction::FSub:
245 return true;
246 default:
247 break;
248 }
249 }
250 return I->isCommutableOperand(Op);
251}
252
255 // IntrinsicInst::isCommutative returns true if swapping the first "two"
256 // arguments to the intrinsic produces the same result.
257 constexpr unsigned IntrinsicNumOperands = 2;
258 return IntrinsicNumOperands;
259 }
260 return I->getNumOperands();
261}
262
263std::optional<unsigned> getElementIndex(const Value *Inst, unsigned Offset) {
264 if (auto Index = getInsertExtractIndex<InsertElementInst>(Inst, Offset))
265 return Index;
267 return Index;
268
269 unsigned Index = Offset;
270
271 const auto *IV = dyn_cast<InsertValueInst>(Inst);
272 if (!IV)
273 return std::nullopt;
274
275 Type *CurrentType = IV->getType();
276 for (unsigned I : IV->indices()) {
277 if (const auto *ST = dyn_cast<StructType>(CurrentType)) {
278 Index *= ST->getNumElements();
279 CurrentType = ST->getElementType(I);
280 } else if (const auto *AT = dyn_cast<ArrayType>(CurrentType)) {
281 Index *= AT->getNumElements();
282 CurrentType = AT->getElementType();
283 } else {
284 return std::nullopt;
285 }
286 Index += I;
287 }
288 return Index;
289}
290
292 auto *It = find_if(VL, IsaPred<Instruction>);
293 if (It == VL.end())
294 return true;
295 Instruction *MainOp = cast<Instruction>(*It);
296 unsigned Opcode = MainOp->getOpcode();
297 bool IsCmpOp = isa<CmpInst>(MainOp);
298 CmpInst::Predicate BasePred = IsCmpOp ? cast<CmpInst>(MainOp)->getPredicate()
300 return all_of(make_range(It, VL.end()), [&](Value *V) {
301 if (auto *CI = dyn_cast<CmpInst>(V))
302 return BasePred == CI->getPredicate();
303 if (auto *I = dyn_cast<Instruction>(V))
304 return I->getOpcode() == Opcode;
305 return isa<PoisonValue>(V);
306 });
307}
308
309std::optional<unsigned> getExtractIndex(const Instruction *E) {
310 unsigned Opcode = E->getOpcode();
311 assert((Opcode == Instruction::ExtractElement ||
312 Opcode == Instruction::ExtractValue) &&
313 "Expected extractelement or extractvalue instruction.");
314 if (Opcode == Instruction::ExtractElement)
315 return getInsertExtractIndex<ExtractElementInst>(E, /*Offset=*/0);
316 auto *EI = cast<ExtractValueInst>(E);
317 if (EI->getNumIndices() != 1)
318 return std::nullopt;
319 return *EI->idx_begin();
320}
321
323 SmallVectorImpl<int> &Mask) {
324 Mask.clear();
325 const unsigned E = Indices.size();
326 Mask.resize(E, PoisonMaskElem);
327 for (unsigned I = 0; I < E; ++I)
328 Mask[Indices[I]] = I;
329}
330
332 assert(!Mask.empty() && "Expected non-empty mask.");
333 SmallVector<Value *> Prev(Scalars.size(),
334 PoisonValue::get(Scalars.front()->getType()));
335 Prev.swap(Scalars);
336 for (unsigned I = 0, E = Prev.size(); I < E; ++I)
337 if (Mask[I] != PoisonMaskElem)
338 Scalars[Mask[I]] = Prev[I];
339}
340
342 assert(!Mask.empty() && Reuses.size() == Mask.size() &&
343 "Expected non-empty mask.");
344 SmallVector<int> Prev(Reuses.begin(), Reuses.end());
345 Prev.swap(Reuses);
346 for (unsigned I = 0, E = Prev.size(); I < E; ++I)
347 if (Mask[I] != PoisonMaskElem)
348 Reuses[Mask[I]] = Prev[I];
349}
350
352 bool BottomOrder) {
353 assert(!Mask.empty() && "Expected non-empty mask.");
354 unsigned Sz = Mask.size();
355 if (BottomOrder) {
356 SmallVector<unsigned> PrevOrder;
357 if (Order.empty()) {
358 PrevOrder.resize(Sz);
359 std::iota(PrevOrder.begin(), PrevOrder.end(), 0);
360 } else {
361 PrevOrder.swap(Order);
362 }
363 Order.assign(Sz, Sz);
364 for (unsigned I = 0; I < Sz; ++I)
365 if (Mask[I] != PoisonMaskElem)
366 Order[I] = PrevOrder[Mask[I]];
367 if (all_of(enumerate(Order), [&](const auto &Data) {
368 return Data.value() == Sz || Data.index() == Data.value();
369 })) {
370 Order.clear();
371 return;
372 }
374 return;
375 }
376 SmallVector<int> MaskOrder;
377 if (Order.empty()) {
378 MaskOrder.resize(Sz);
379 std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
380 } else {
381 inversePermutation(Order, MaskOrder);
382 }
383 reorderReuses(MaskOrder, Mask);
384 if (ShuffleVectorInst::isIdentityMask(MaskOrder, Sz)) {
385 Order.clear();
386 return;
387 }
388 Order.assign(Sz, Sz);
389 for (unsigned I = 0; I < Sz; ++I)
390 if (MaskOrder[I] != PoisonMaskElem)
391 Order[MaskOrder[I]] = I;
393}
394
396 assert(!Order.empty() &&
397 "Order is empty. Please check it before using isReverseOrder.");
398 unsigned Sz = Order.size();
399 return all_of(enumerate(Order), [&](const auto &Pair) {
400 return Pair.value() == Sz || Sz - Pair.index() - 1 == Pair.value();
401 });
402}
403
405 ArrayRef<int> FirstCluster = Mask.slice(0, Sz);
406 if (ShuffleVectorInst::isIdentityMask(FirstCluster, Sz))
407 return false;
408 for (unsigned I = Sz, E = Mask.size(); I < E; I += Sz) {
409 ArrayRef<int> Cluster = Mask.slice(I, Sz);
410 if (Cluster != FirstCluster)
411 return false;
412 }
413 return true;
414}
415
417 ArrayRef<unsigned> SecondaryOrder) {
418 assert((SecondaryOrder.empty() || Order.size() == SecondaryOrder.size()) &&
419 "Expected same size of orders");
420 size_t Sz = Order.size();
421 SmallBitVector UsedIndices(Sz);
422 for (unsigned Idx : seq<unsigned>(0, Sz)) {
423 if (Order[Idx] != Sz)
424 UsedIndices.set(Order[Idx]);
425 }
426 if (SecondaryOrder.empty()) {
427 for (unsigned Idx : seq<unsigned>(0, Sz))
428 if (Order[Idx] == Sz && !UsedIndices.test(Idx))
429 Order[Idx] = Idx;
430 } else {
431 for (unsigned Idx : seq<unsigned>(0, Sz))
432 if (SecondaryOrder[Idx] != Sz && Order[Idx] == Sz &&
433 !UsedIndices.test(SecondaryOrder[Idx]))
434 Order[Idx] = SecondaryOrder[Idx];
435 }
436}
437
439 assert(!VL.empty() && "Expected non-empty list of values.");
440 Type *Ty = VL.consume_front()->getType();
441 return all_of(VL, [&](Value *V) { return V->getType() == Ty; });
442}
443
444template <typename T>
445std::optional<unsigned> getInsertExtractIndex(const Value *Inst,
446 unsigned Offset) {
447 static_assert(std::is_same_v<T, InsertElementInst> ||
448 std::is_same_v<T, ExtractElementInst>,
449 "unsupported T");
450 const auto *IE = dyn_cast<T>(Inst);
451 if (!IE)
452 return std::nullopt;
453 // InsertElement: result is the vector, index is op 2.
454 // ExtractElement: result is scalar, vector is op 0, index is op 1.
455 constexpr bool IsInsert = std::is_same_v<T, InsertElementInst>;
456 Type *VecTy = IsInsert ? IE->getType() : IE->getOperand(0)->getType();
457 const auto *VT = dyn_cast<FixedVectorType>(VecTy);
458 if (!VT)
459 return std::nullopt;
460 const auto *CI = dyn_cast<ConstantInt>(IE->getOperand(IsInsert ? 2 : 1));
461 if (!CI)
462 return std::nullopt;
463 if (CI->getValue().uge(VT->getNumElements()))
464 return std::nullopt;
465 unsigned Index = Offset;
466 Index *= VT->getNumElements();
467 Index += CI->getZExtValue();
468 return Index;
469}
470
471// Only these two specializations are used; instantiate them here so the
472// definition can stay out of the header.
473template std::optional<unsigned>
475template std::optional<unsigned>
477
479 auto *I = dyn_cast<Instruction>(V);
480 if (!I)
481 return true;
482 return all_of(make_isa_range<Instruction>(I->operands()),
483 [I](Instruction *IO) {
484 return isa<PHINode>(IO) || IO->getParent() != I->getParent();
485 }) &&
487}
488
490 auto *I = dyn_cast<Instruction>(V);
491 if (!I)
492 return true;
493 // Limits the number of uses to save compile time.
494 return !I->hasNUsesOrMore(UsesLimit) && all_of(I->users(), [I](User *U) {
495 auto *IU = dyn_cast<Instruction>(U);
496 if (!IU)
497 return true;
498 return IU->getParent() != I->getParent() || isa<PHINode>(IU);
499 }) && !I->mayReadOrWriteMemory();
500}
501
505
510
511void transformScalarShuffleIndiciesToVector(unsigned VecTyNumElements,
512 SmallVectorImpl<int> &Mask) {
513 // The ShuffleBuilder implementation use shufflevector to splat an "element".
514 // But the element have different meaning for SLP (scalar) and REVEC
515 // (vector). We need to expand Mask into masks which shufflevector can use
516 // directly.
517 SmallVector<int> NewMask(Mask.size() * VecTyNumElements);
518 for (unsigned I : seq<unsigned>(Mask.size()))
519 for (auto [J, MaskV] : enumerate(MutableArrayRef(NewMask).slice(
520 I * VecTyNumElements, VecTyNumElements)))
521 MaskV = Mask[I] == PoisonMaskElem ? PoisonMaskElem
522 : Mask[I] * VecTyNumElements + J;
523 Mask.swap(NewMask);
524}
525
527 if (VL.empty())
528 return 0;
530 return 0;
531 auto *SV = cast<ShuffleVectorInst>(VL.front());
532 unsigned SVNumElements =
533 cast<FixedVectorType>(SV->getOperand(0)->getType())->getNumElements();
534 unsigned ShuffleMaskSize = SV->getShuffleMask().size();
535 if (SVNumElements % ShuffleMaskSize != 0)
536 return 0;
537 unsigned GroupSize = SVNumElements / ShuffleMaskSize;
538 if (GroupSize == 0 || (VL.size() % GroupSize) != 0)
539 return 0;
540 unsigned NumGroup = 0;
541 for (size_t I = 0, E = VL.size(); I != E; I += GroupSize) {
542 auto *SV = cast<ShuffleVectorInst>(VL[I]);
543 Value *Src = SV->getOperand(0);
544 ArrayRef<Value *> Group = VL.slice(I, GroupSize);
545 SmallBitVector ExpectedIndex(GroupSize);
546 if (!all_of(Group, [&](Value *V) {
547 auto *SV = cast<ShuffleVectorInst>(V);
548 // From the same source.
549 if (SV->getOperand(0) != Src)
550 return false;
551 int Index;
552 if (!SV->isExtractSubvectorMask(Index))
553 return false;
554 ExpectedIndex.set(Index / ShuffleMaskSize);
555 return true;
556 }))
557 return 0;
558 if (!ExpectedIndex.all())
559 return 0;
560 ++NumGroup;
561 }
562 assert(NumGroup == (VL.size() / GroupSize) && "Unexpected number of groups");
563 return NumGroup;
564}
565
567 assert(getShufflevectorNumGroups(VL) && "Not supported shufflevector usage.");
568 auto *SV = cast<ShuffleVectorInst>(VL.front());
569 unsigned SVNumElements =
570 cast<FixedVectorType>(SV->getOperand(0)->getType())->getNumElements();
571 SmallVector<int> Mask;
572 unsigned AccumulateLength = 0;
573 for (Value *V : VL) {
574 auto *SV = cast<ShuffleVectorInst>(V);
575 for (int M : SV->getShuffleMask())
576 Mask.push_back(M == PoisonMaskElem ? PoisonMaskElem
577 : AccumulateLength + M);
578 AccumulateLength += SVNumElements;
579 }
580 return Mask;
581}
582
583/// Checks if the vector of instructions can be represented as a shuffle, like:
584/// %x0 = extractelement <4 x i8> %x, i32 0
585/// %x3 = extractelement <4 x i8> %x, i32 3
586/// %y1 = extractelement <4 x i8> %y, i32 1
587/// %y2 = extractelement <4 x i8> %y, i32 2
588/// %x0x0 = mul i8 %x0, %x0
589/// %x3x3 = mul i8 %x3, %x3
590/// %y1y1 = mul i8 %y1, %y1
591/// %y2y2 = mul i8 %y2, %y2
592/// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
593/// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
594/// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
595/// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
596/// ret <4 x i8> %ins4
597/// can be transformed into:
598/// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
599/// i32 6>
600/// %2 = mul <4 x i8> %1, %1
601/// ret <4 x i8> %2
602/// Mask will return the Shuffle Mask equivalent to the extracted elements.
603/// TODO: Can we split off and reuse the shuffle mask detection from
604/// ShuffleVectorInst/getShuffleCost?
605std::optional<TargetTransformInfo::ShuffleKind>
607 AssumptionCache *AC, SLPAnalysisCache &Cache) {
608 const auto *It = find_if(VL, IsaPred<ExtractElementInst>);
609 if (It == VL.end())
610 return std::nullopt;
611 unsigned Size = 0;
612 Value *Vec1 = nullptr;
613 Value *Vec2 = nullptr;
614 // The poison analysis is expensive, it is required only for the undef
615 // vectors.
616 std::optional<bool> HasNonUndefVec;
617 auto IsNonUndefVecPresent = [&]() {
618 if (!HasNonUndefVec)
619 HasNonUndefVec = any_of(make_isa_range<ExtractElementInst>(VL),
620 [&](ExtractElementInst *EE) {
621 Value *Vec = EE->getVectorOperand();
622 if (isa<UndefValue>(Vec))
623 return false;
624 return Cache.isGuaranteedNotToBePoison(Vec, AC);
625 });
626 return *HasNonUndefVec;
627 };
628 enum ShuffleMode { Unknown, Select, Permute };
629 ShuffleMode CommonShuffleMode = Unknown;
630 Mask.assign(VL.size(), PoisonMaskElem);
631 for (unsigned I = 0, E = VL.size(); I < E; ++I) {
632 // Undef, or a copyable lane modeled on an extract main op, can be
633 // represented as an undef element in a vector.
634 if (isa<UndefValue>(VL[I]))
635 continue;
636 auto *EI = dyn_cast<ExtractElementInst>(VL[I]);
637 if (!EI)
638 continue;
639 if (isa<ScalableVectorType>(EI->getVectorOperandType()))
640 return std::nullopt;
641 auto *Vec = EI->getVectorOperand();
642 // We can extractelement from undef or poison vector.
644 continue;
645 // All vector operands must have the same number of vector elements.
646 if (isa<UndefValue>(Vec)) {
647 Mask[I] = I;
648 } else {
649 if (isa<UndefValue>(EI->getIndexOperand()))
650 continue;
651 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
652 if (!Idx)
653 return std::nullopt;
654 // Undefined behavior if Idx is negative or out of bounds.
655 if (Idx->getValue().uge(getNumElements(Vec->getType())))
656 continue;
657 unsigned IntIdx = Idx->getValue().getZExtValue();
658 Mask[I] = IntIdx;
659 }
660 // The width is defined only by the lanes that are present in the mask.
661 Size = std::max(Size, getNumElements(Vec->getType()));
662 if (isUndefVector(Vec).all() && IsNonUndefVecPresent())
663 continue;
664 // For correct shuffling we have to have at most 2 different vector operands
665 // in all extractelement instructions.
666 if (!Vec1 || Vec1 == Vec) {
667 Vec1 = Vec;
668 } else if (!Vec2 || Vec2 == Vec) {
669 Vec2 = Vec;
670 } else {
671 return std::nullopt;
672 }
673 }
674 if (Vec2 && Size != std::max(getNumElements(Vec1->getType()),
675 getNumElements(Vec2->getType())))
676 return std::nullopt;
677 for (auto [I, Idx] : enumerate(Mask)) {
678 if (Idx == PoisonMaskElem)
679 continue;
680 auto *Vec = cast<ExtractElementInst>(VL[I])->getVectorOperand();
681 if (Vec == Vec2)
682 Idx += Size;
683 else if (Vec != Vec1)
684 continue;
685 if (CommonShuffleMode == Permute)
686 continue;
687 // If the extract index is not the same as the operation number, it is a
688 // permutation.
689 if (Idx % Size != I) {
690 CommonShuffleMode = Permute;
691 continue;
692 }
693 CommonShuffleMode = Select;
694 }
695 // If we're not crossing lanes in different vectors, consider it as blending.
696 if (CommonShuffleMode == Select && Vec2)
698 // If Vec2 was never used, we have a permutation of a single vector, otherwise
699 // we have permutation of 2 vectors.
702}
703
705 IRBuilderBase &Builder, Value *Vec, Value *V, unsigned Index,
706 function_ref<Value *(Value *, Value *, ArrayRef<int>)> Generator) {
707 if (isa<PoisonValue>(Vec) && isa<PoisonValue>(V))
708 return Vec;
709 const unsigned SubVecVF = getNumElements(V->getType());
710 // Create shuffle, insertvector requires that index is multiple of
711 // the subvector length.
712 const unsigned VecVF = getNumElements(Vec->getType());
713 SmallVector<int> Mask(VecVF, PoisonMaskElem);
714 if (isa<PoisonValue>(Vec)) {
715 auto *Begin = std::next(Mask.begin(), Index);
716 std::iota(Begin, std::next(Begin, SubVecVF), 0);
717 Vec = Builder.CreateShuffleVector(V, Mask);
718 return Vec;
719 }
720 std::iota(Mask.begin(), Mask.end(), 0);
721 std::iota(std::next(Mask.begin(), Index),
722 std::next(Mask.begin(), Index + SubVecVF), VecVF);
723 if (Generator)
724 return Generator(Vec, V, Mask);
725 // 1. Resize V to the size of Vec.
726 SmallVector<int> ResizeMask(VecVF, PoisonMaskElem);
727 std::iota(ResizeMask.begin(), std::next(ResizeMask.begin(), SubVecVF), 0);
728 V = Builder.CreateShuffleVector(V, ResizeMask);
729 // 2. Insert V into Vec.
730 return Builder.CreateShuffleVector(Vec, V, Mask);
731}
732
734 unsigned SubVecVF, unsigned Index) {
735 SmallVector<int> Mask(SubVecVF, PoisonMaskElem);
736 std::iota(Mask.begin(), Mask.end(), Index);
737 return Builder.CreateShuffleVector(Vec, Mask);
738}
739
741 SmallBitVector UseMask(VF, true);
742 for (auto [Idx, Value] : enumerate(Mask)) {
743 if (Value == PoisonMaskElem) {
744 if (MaskArg == UseMask::UndefsAsMask)
745 UseMask.reset(Idx);
746 continue;
747 }
748 if (MaskArg == UseMask::FirstArg && Value < VF)
749 UseMask.reset(Value);
750 else if (MaskArg == UseMask::SecondArg && Value >= VF)
751 UseMask.reset(Value - VF);
752 }
753 return UseMask;
754}
755
756template <bool IsPoisonOnly>
758 SmallBitVector Res(UseMask.empty() ? 1 : UseMask.size(), true);
759 using T = std::conditional_t<IsPoisonOnly, PoisonValue, UndefValue>;
760 if (isa<T>(V))
761 return Res;
762 auto *VecTy = dyn_cast<FixedVectorType>(V->getType());
763 if (!VecTy)
764 return Res.reset();
765 auto *C = dyn_cast<Constant>(V);
766 if (!C) {
767 if (!UseMask.empty()) {
768 const Value *Base = V;
769 while (auto *II = dyn_cast<InsertElementInst>(Base)) {
770 Base = II->getOperand(0);
771 if (isa<T>(II->getOperand(1)))
772 continue;
773 std::optional<unsigned> Idx = getElementIndex(II);
774 if (!Idx) {
775 Res.reset();
776 return Res;
777 }
778 if (*Idx < UseMask.size() && !UseMask.test(*Idx))
779 Res.reset(*Idx);
780 }
781 // TODO: Add analysis for shuffles here too.
782 if (V == Base) {
783 Res.reset();
784 } else {
785 SmallBitVector SubMask(UseMask.size(), false);
786 Res &= isUndefVector<IsPoisonOnly>(Base, SubMask);
787 }
788 } else {
789 Res.reset();
790 }
791 return Res;
792 }
793 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
794 if (Constant *Elem = C->getAggregateElement(I))
795 if (!isa<T>(Elem) &&
796 (UseMask.empty() || (I < UseMask.size() && !UseMask.test(I))))
797 Res.reset(I);
798 }
799 return Res;
800}
801
803 const SmallBitVector &);
805 const SmallBitVector &);
806
809 const TargetTransformInfo *TTI) {
810 if (!UserInst)
811 return false;
812 unsigned Opcode = UserInst->getOpcode();
813 switch (Opcode) {
814 case Instruction::Load: {
815 LoadInst *LI = cast<LoadInst>(UserInst);
816 return (LI->getPointerOperand() == Scalar);
817 }
818 case Instruction::Store: {
819 StoreInst *SI = cast<StoreInst>(UserInst);
820 return (SI->getPointerOperand() == Scalar);
821 }
822 case Instruction::Call: {
823 CallInst *CI = cast<CallInst>(UserInst);
825 return any_of(enumerate(CI->args()), [&](auto &&Arg) {
826 return isVectorIntrinsicWithScalarOpAtArg(ID, Arg.index(), TTI) &&
827 Arg.value().get() == Scalar;
828 });
829 }
830 default:
831 return false;
832 }
833}
834
842
844 if (LoadInst *LI = dyn_cast<LoadInst>(I))
845 return LI->isSimple();
847 return SI->isSimple();
849 return !MI->isVolatile();
850 return true;
851}
852
853bool isSelectedBaseLoad(Type *ScalarTy, ArrayRef<Value *> PointerOps,
854 const DataLayout &DL, Value *&TrueBase,
855 Value *&FalseBase,
856 SmallVectorImpl<Value *> &Conditions) {
857 TrueBase = nullptr;
858 FalseBase = nullptr;
859 uint64_t ScalarSize = DL.getTypeStoreSize(ScalarTy);
860 Conditions.assign(PointerOps.size(), nullptr);
861 for (auto [Idx, P] : enumerate(PointerOps)) {
862 Value *Base = P;
863 uint64_t Offset = 0;
864 if (auto *GEP = dyn_cast<GetElementPtrInst>(P)) {
865 APInt OffsetAP(DL.getIndexTypeSizeInBits(GEP->getType()), 0);
866 if (!GEP->accumulateConstantOffset(DL, OffsetAP) || OffsetAP.isNegative())
867 return false;
868 Offset = OffsetAP.getZExtValue();
869 Base = GEP->getPointerOperand();
870 }
871 auto *Sel = dyn_cast<SelectInst>(Base);
872 if (!Sel)
873 return false;
874 Value *T = Sel->getTrueValue();
875 Value *F = Sel->getFalseValue();
876 if (!TrueBase) {
877 if (T == F)
878 return false;
879 TrueBase = T;
880 FalseBase = F;
881 } else if (TrueBase != T || FalseBase != F) {
882 return false;
883 }
884 // Lane Idx must be at exactly Base + Idx * sizeof(ScalarTy); codegen reads
885 // contiguously from TrueBase/FalseBase starting at lane 0.
886 if (Offset != static_cast<uint64_t>(Idx) * ScalarSize)
887 return false;
888 Conditions[Idx] = Sel->getCondition();
889 }
890 return TrueBase != nullptr;
891}
892
894 const DataLayout &DL) {
896 "Expected only load lanes in a blended load.");
897 const uint64_t ScalarSize = DL.getTypeStoreSize(VL.front()->getType());
898 Align BaseAlignment = cast<LoadInst>(VL.front())->getAlign();
899 for (auto [Idx, V] : enumerate(VL))
900 BaseAlignment =
901 std::min(BaseAlignment, commonAlignment(cast<LoadInst>(V)->getAlign(),
902 Idx * ScalarSize));
903 return BaseAlignment;
904}
905
907 Value *Ptr = cast<LoadInst>(VL.front())->getPointerOperand();
908 if (auto *GEP = dyn_cast<GetElementPtrInst>(Ptr))
909 Ptr = GEP->getPointerOperand();
910 return cast<SelectInst>(Ptr);
911}
912
914 function_ref<bool(Value *)> IsGEPLane,
915 const DataLayout &DL) {
916 constexpr unsigned IndexIdx = 1;
917 Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
918 Type *PtrIdxTy =
919 DL.getIndexType(VL0->getOperand(0)->getType()->getScalarType());
920 bool AllSameTy = true;
921 bool HasNonConstIdx = false;
922 bool ConstsFitVL0Ty = true;
923 for (Value *V : make_filter_range(VL, IsGEPLane)) {
924 Value *Op = cast<GetElementPtrInst>(V)->getOperand(IndexIdx);
925 if (Op->getType() != VL0Ty)
926 AllSameTy = false;
927 auto *CI = dyn_cast<ConstantInt>(Op);
928 if (!CI) {
929 // Non-constant indices are not cast, they must have the main op type.
930 if (Op->getType() != VL0Ty)
931 return nullptr;
932 HasNonConstIdx = true;
933 continue;
934 }
935 if (!CI->getValue().isSignedIntN(VL0Ty->getIntegerBitWidth()))
936 ConstsFitVL0Ty = false;
937 }
938 if (AllSameTy)
939 return VL0Ty;
940 if (!HasNonConstIdx || VL0Ty == PtrIdxTy)
941 return PtrIdxTy;
942 return ConstsFitVL0Ty ? VL0Ty : nullptr;
943}
944
946 SmallPtrSet<Value *, 16> UniquePtrs(llvm::from_range, PointerOps);
947 if (UniquePtrs.size() != PointerOps.size())
948 return false;
949 auto IsConstantOffsetPtr = [](Value *P) {
951 return !GEP ||
952 (GEP->getNumOperands() == 2 && isConstant(GEP->getOperand(1)));
953 };
954 auto *RefIt = find_if_not(PointerOps, IsConstantOffsetPtr);
955 if (RefIt == PointerOps.end())
956 return false;
957 auto *RefGEP = dyn_cast<GetElementPtrInst>(*RefIt);
958 if (!RefGEP || RefGEP->getNumOperands() != 2)
959 return false;
960 Value *Base = RefGEP->getPointerOperand();
961 Type *PtrTy = RefGEP->getType();
962 Type *SrcElemTy = RefGEP->getSourceElementType();
963 // The stride and the (optional) cast opcode of the runtime indices.
964 Value *Stride = nullptr;
965 unsigned CastOpcode = 0;
966 for (Value *P : PointerOps) {
967 if (P->getType() != PtrTy)
968 return false;
969 if (P == Base)
970 continue;
972 if (!GEP || GEP->getNumOperands() != 2 ||
973 GEP->getPointerOperand() != Base ||
974 GEP->getSourceElementType() != SrcElemTy)
975 return false;
976 Value *Idx = GEP->getOperand(1);
977 if (isConstant(Idx))
978 continue;
979 unsigned LaneCastOpcode = 0;
980 if (auto *Cast = dyn_cast<CastInst>(Idx)) {
981 LaneCastOpcode = Cast->getOpcode();
982 Idx = Cast->getOperand(0);
983 }
984 Value *LaneStride = Idx;
985 if (auto *BO = dyn_cast<BinaryOperator>(Idx)) {
986 if (isa<Constant>(BO->getOperand(1)))
987 LaneStride = BO->getOperand(0);
988 else if (isa<Constant>(BO->getOperand(0)))
989 LaneStride = BO->getOperand(1);
990 }
991 if (!Stride) {
992 Stride = LaneStride;
993 CastOpcode = LaneCastOpcode;
994 continue;
995 }
996 if (LaneStride != Stride || LaneCastOpcode != CastOpcode)
997 return false;
998 }
999 return Stride != nullptr;
1000}
1001
1003 bool ExtendingManyInputs) {
1004 if (SubMask.empty())
1005 return;
1006 assert(
1007 (!ExtendingManyInputs || SubMask.size() > Mask.size() ||
1008 // Check if input scalars were extended to match the size of other node.
1009 (SubMask.size() == Mask.size() && Mask.back() == PoisonMaskElem)) &&
1010 "SubMask with many inputs support must be larger than the mask.");
1011 if (Mask.empty()) {
1012 Mask.append(SubMask.begin(), SubMask.end());
1013 return;
1014 }
1015 SmallVector<int> NewMask(SubMask.size(), PoisonMaskElem);
1016 int TermValue = std::min(Mask.size(), SubMask.size());
1017 for (int I = 0, E = SubMask.size(); I < E; ++I) {
1018 if (SubMask[I] == PoisonMaskElem ||
1019 (!ExtendingManyInputs &&
1020 (SubMask[I] >= TermValue || Mask[SubMask[I]] >= TermValue)))
1021 continue;
1022 NewMask[I] = Mask[SubMask[I]];
1023 }
1024 Mask.swap(NewMask);
1025}
1026
1028 const size_t Sz = Order.size();
1029 SmallBitVector UnusedIndices(Sz, /*t=*/true);
1030 SmallBitVector MaskedIndices(Sz);
1031 for (unsigned I = 0; I < Sz; ++I) {
1032 if (Order[I] < Sz)
1033 UnusedIndices.reset(Order[I]);
1034 else
1035 MaskedIndices.set(I);
1036 }
1037 if (MaskedIndices.none())
1038 return;
1039 assert(UnusedIndices.count() == MaskedIndices.count() &&
1040 "Non-synced masked/available indices.");
1041 int Idx = UnusedIndices.find_first();
1042 int MIdx = MaskedIndices.find_first();
1043 while (MIdx >= 0) {
1044 assert(Idx >= 0 && "Indices must be synced.");
1045 Order[MIdx] = Idx;
1046 Idx = UnusedIndices.find_next(Idx);
1047 MIdx = MaskedIndices.find_next(MIdx);
1048 }
1049}
1050
1052 unsigned Opcode0, unsigned Opcode1) {
1053 unsigned ScalarTyNumElements = getNumElements(ScalarTy);
1054 SmallBitVector OpcodeMask(VL.size() * ScalarTyNumElements, false);
1055 for (unsigned Lane : seq<unsigned>(VL.size())) {
1056 if (isa<PoisonValue>(VL[Lane]))
1057 continue;
1058 if (cast<Instruction>(VL[Lane])->getOpcode() == Opcode1)
1059 OpcodeMask.set(Lane * ScalarTyNumElements,
1060 Lane * ScalarTyNumElements + ScalarTyNumElements);
1061 }
1062 return OpcodeMask;
1063}
1064
1066 assert(none_of(Val, [](Constant *C) { return C->getType()->isVectorTy(); }) &&
1067 "Expected scalar constants.");
1068 SmallVector<Constant *> NewVal(Val.size() * VF);
1069 for (auto [I, V] : enumerate(Val))
1070 std::fill_n(NewVal.begin() + I * VF, VF, V);
1071 return NewVal;
1072}
1073
1075 switch (Opcode) {
1076 case Instruction::UDiv:
1077 return Intrinsic::masked_udiv;
1078 case Instruction::SDiv:
1079 return Intrinsic::masked_sdiv;
1080 case Instruction::URem:
1081 return Intrinsic::masked_urem;
1082 case Instruction::SRem:
1083 return Intrinsic::masked_srem;
1084 default:
1085 llvm_unreachable("Unexpected opcode");
1086 }
1087}
1088
1089/// Returns true if \p I is a part of a single-use chain, computing an address,
1090/// which does not pay off the vectorization: all the lanes are extracted for
1091/// the scalar addresses, the extracts delay the memory accesses.
1093 constexpr unsigned MaxIndexChainLength = 3;
1094 const User *U = I->user_back();
1095 for ([[maybe_unused]] unsigned _ : seq<unsigned>(MaxIndexChainLength)) {
1097 return true;
1098 if (!isa<Instruction>(U) || !U->hasOneUse())
1099 return false;
1100 U = U->user_back();
1101 }
1102 return false;
1103}
1104
1106 if (!I->hasOneUse() || isNonProfitableIndex(I))
1107 return false;
1108 // The operation with the identity or the absorbing constant is folded away
1109 // before the codegen, the vector node only repacks the lanes.
1110 if (const auto *BO = dyn_cast<BinaryOperator>(I)) {
1111 unsigned Opcode = BO->getOpcode();
1112 Type *Ty = BO->getType();
1113 for (unsigned Idx : seq<unsigned>(2)) {
1114 const auto *C = dyn_cast<Constant>(BO->getOperand(Idx));
1116 Opcode, Ty, /*AllowRHSConstant=*/Idx == 1) ||
1118 Opcode, Ty, /*AllowLHSConstant=*/Idx == 0)))
1119 return false;
1120 }
1121 }
1122 const User *U = I->user_back();
1125 if (isa<CastInst>(I))
1126 return !isa<FPToSIInst, FPToUIInst>(I) &&
1127 (!isa<CastInst>(U) || U->hasOneUse());
1129 I);
1130}
1131
1132Instruction *lookThroughCastRoundTrip(Value *V, bool MustBeElidable) {
1133 auto *Wide = dyn_cast<FPExtInst>(V);
1134 if (!Wide || !Wide->hasOneUse())
1135 return nullptr;
1136 auto *Narrow = dyn_cast<FPTruncInst>(Wide->getOperand(0));
1137 if (!Narrow || !Narrow->hasOneUse())
1138 return nullptr;
1139 Value *Src = Narrow->getOperand(0);
1140 if (!isa<Instruction>(Src) || Src->getType() != Wide->getType())
1141 return nullptr;
1142 if (MustBeElidable && !(Wide->hasAllowContract() && Wide->hasNoNaNs() &&
1143 Wide->hasNoInfs() && Narrow->hasAllowContract()))
1144 return nullptr;
1145 return Narrow;
1146}
1147
1148namespace {
1149
1150/// Shifts and the mask accumulated from the narrow ops on the current path:
1151/// the shifts above and at the narrow level, the bitwidth of the narrow ops
1152/// (0 if none) and the mask from the absorbed narrow ands.
1153struct NarrowedChainState {
1154 unsigned Shift = 0;
1155 unsigned NarrowShift = 0;
1156 unsigned NarrowBW = 0;
1157 APInt NarrowMask = APInt(1, 0);
1158
1159 /// The mask for the absorbed narrow ops in the leaf type, applied before
1160 /// widening and shifting; all-ones if nothing was absorbed.
1161 APInt getMask(unsigned LeafBW) const {
1162 if (NarrowBW == 0)
1163 return APInt::getAllOnes(LeafBW);
1164 return (NarrowMask & (APInt::getAllOnes(NarrowBW) << NarrowShift))
1165 .lshr(NarrowShift)
1166 .trunc(LeafBW);
1167 }
1168};
1169
1170} // namespace
1171
1172static void
1173collectNarrowedLeavesImpl(Value *V, unsigned RdxOpcode, unsigned WideBW,
1174 NarrowedChainState S, unsigned Depth,
1175 unsigned MaxDepth,
1177 SmallVectorImpl<Instruction *> &ChainInsts) {
1178 if (Depth < MaxDepth) {
1179 if (auto *Z = dyn_cast<ZExtInst>(V);
1180 Z && Z->getSrcTy()->isIntegerTy() && !Z->getSrcTy()->isIntegerTy(1)) {
1181 ChainInsts.push_back(Z);
1182 return collectNarrowedLeavesImpl(Z->getOperand(0), RdxOpcode, WideBW, S,
1183 Depth + 1, MaxDepth, Leaves, ChainInsts);
1184 }
1185 if (auto *BO = dyn_cast<BinaryOperator>(V)) {
1186 if (BO->getOpcode() == RdxOpcode) {
1187 ChainInsts.push_back(BO);
1188 collectNarrowedLeavesImpl(BO->getOperand(0), RdxOpcode, WideBW, S,
1189 Depth + 1, MaxDepth, Leaves, ChainInsts);
1190 collectNarrowedLeavesImpl(BO->getOperand(1), RdxOpcode, WideBW, S,
1191 Depth + 1, MaxDepth, Leaves, ChainInsts);
1192 return;
1193 }
1194 const APInt *Amt;
1195 unsigned BW = V->getType()->getScalarSizeInBits();
1196 auto *Z = dyn_cast<ZExtInst>(BO->getOperand(0));
1197 if (BO->getOpcode() == Instruction::Shl && Z && S.NarrowBW == 0 &&
1198 match(BO->getOperand(1), m_APInt(Amt)) && Amt->ult(BW) &&
1199 Z->getSrcTy()->isIntegerTy() && !Z->getSrcTy()->isIntegerTy(1) &&
1200 (BW == WideBW ||
1201 Z->getSrcTy()->getIntegerBitWidth() + Amt->getZExtValue() <= BW) &&
1202 S.Shift + Amt->getZExtValue() < WideBW) {
1203 ChainInsts.push_back(BO);
1204 ChainInsts.push_back(Z);
1205 S.Shift += Amt->getZExtValue();
1206 return collectNarrowedLeavesImpl(Z->getOperand(0), RdxOpcode, WideBW, S,
1207 Depth + 1, MaxDepth, Leaves,
1208 ChainInsts);
1209 }
1210 // Narrow shls fold into the shift and narrow ands into the mask; the
1211 // mask clears the bits the shls shift out. Only same-width ops compose
1212 // on one path, and the combined shift must stay a valid shift amount in
1213 // both types.
1214 if (BW < WideBW && (S.NarrowBW == 0 || BW == S.NarrowBW)) {
1215 if (BO->getOpcode() == Instruction::Shl &&
1216 match(BO->getOperand(1), m_APInt(Amt)) && Amt->ult(BW) &&
1217 S.NarrowShift + Amt->getZExtValue() < BW &&
1218 S.Shift + S.NarrowShift + Amt->getZExtValue() < WideBW) {
1219 ChainInsts.push_back(BO);
1220 if (BO->hasNoUnsignedWrap() && S.NarrowBW == 0) {
1221 S.Shift += Amt->getZExtValue();
1222 // Lossless shls shift out only known-zero bits; record them as
1223 // the mask so matching lanes can form a splat.
1224 S.NarrowBW = BW;
1225 S.NarrowMask = APInt::getLowBitsSet(BW, BW - Amt->getZExtValue());
1226 } else {
1227 if (S.NarrowBW == 0) {
1228 S.NarrowBW = BW;
1229 S.NarrowMask = APInt::getAllOnes(BW);
1230 }
1231 S.NarrowShift += Amt->getZExtValue();
1232 }
1233 return collectNarrowedLeavesImpl(BO->getOperand(0), RdxOpcode, WideBW,
1234 S, Depth + 1, MaxDepth, Leaves,
1235 ChainInsts);
1236 }
1237 Value *X;
1238 if (match(BO, m_c_And(m_Value(X), m_APInt(Amt)))) {
1239 ChainInsts.push_back(BO);
1240 if (S.NarrowBW == 0) {
1241 S.NarrowBW = BW;
1242 S.NarrowMask = APInt::getAllOnes(BW);
1243 }
1244 S.NarrowMask &= *Amt << S.NarrowShift;
1245 return collectNarrowedLeavesImpl(X, RdxOpcode, WideBW, S, Depth + 1,
1246 MaxDepth, Leaves, ChainInsts);
1247 }
1248 }
1249 }
1250 }
1251 Leaves.emplace_back(V, S.Shift + S.NarrowShift,
1252 S.getMask(V->getType()->getScalarSizeInBits()));
1253}
1254
1255void collectNarrowedLeaves(Value *V, unsigned RdxOpcode, unsigned WideBW,
1256 unsigned MaxDepth,
1258 SmallVectorImpl<Instruction *> &ChainInsts) {
1259 collectNarrowedLeavesImpl(V, RdxOpcode, WideBW, NarrowedChainState(),
1260 /*Depth=*/0, MaxDepth, Leaves, ChainInsts);
1261}
1262
1264 assert(F && "Expected function.");
1265 return F->hasOptSize() ? TTI::TCK_CodeSize : TTI::TCK_RecipThroughput;
1266}
1267
1268/// Checks if \p V is a zero-extended sub-field of a wider integer scalar.
1269/// Returns the source scalar, the field width and the field offset.
1270static std::optional<std::tuple<Value *, unsigned, unsigned>>
1272 if (!V->getType()->isIntegerTy())
1273 return std::nullopt;
1274 // Field offset for the field-aligned shift amount, if the shifted value of
1275 // the given bit width keeps at least one full field.
1276 auto GetFieldOffset = [](const APInt *Amt, unsigned BitWidth,
1277 unsigned FieldWidth) -> std::optional<unsigned> {
1278 uint64_t ShAmt = Amt->getLimitedValue(BitWidth);
1279 if (ShAmt % FieldWidth != 0 || ShAmt + FieldWidth > BitWidth)
1280 return std::nullopt;
1281 return ShAmt / FieldWidth;
1282 };
1283 // Checks if the low bits of Val are a sub-field of the given width of a
1284 // wider integer scalar. Val is a scalar integer, since V is one, and so is
1285 // the matched source.
1286 auto MatchLowField =
1287 [&](Value *Val,
1288 unsigned FieldWidth) -> std::optional<std::pair<Value *, unsigned>> {
1289 Value *Src;
1290 const APInt *Amt;
1291 // Only the low bits of Val are observed, so lshr and ashr are equivalent.
1292 if (match(Val, m_Trunc(m_Shr(m_Value(Src), m_APInt(Amt)))) ||
1293 match(Val, m_Shr(m_Value(Src), m_APInt(Amt)))) {
1294 if (std::optional<unsigned> Offset = GetFieldOffset(
1295 Amt, Src->getType()->getIntegerBitWidth(), FieldWidth)) {
1296 // The truncation of the shifted value keeps the field, look through it.
1297 match(Src, m_Trunc(m_Value(Src)));
1298 return std::make_pair(Src, *Offset);
1299 }
1300 return std::nullopt;
1301 }
1302 if (match(Val, m_Trunc(m_Value(Src))) &&
1303 Src->getType()->getIntegerBitWidth() >= FieldWidth)
1304 return std::make_pair(Src, 0u);
1305 // Val itself is the source of its low field.
1306 if (Val->getType()->getIntegerBitWidth() > FieldWidth)
1307 return std::make_pair(Val, 0u);
1308 return std::nullopt;
1309 };
1310 Value *Val;
1311 const APInt *Mask;
1312 // and Val, (1 << FieldWidth) - 1 or zext i<FieldWidth> Val - the low bits of
1313 // Val.
1314 unsigned FieldWidth = 0;
1315 if (match(V, m_c_And(m_Value(Val), m_APInt(Mask))) && Mask->isMask())
1316 FieldWidth = Mask->popcount();
1317 else if (match(V, m_ZExt(m_Value(Val))))
1318 FieldWidth = Val->getType()->getIntegerBitWidth();
1319 if (FieldWidth != 0) {
1320 if (std::optional<std::pair<Value *, unsigned>> Field =
1321 MatchLowField(Val, FieldWidth))
1322 return std::make_tuple(Field->first, FieldWidth, Field->second);
1323 return std::nullopt;
1324 }
1325 unsigned LaneWidth = V->getType()->getIntegerBitWidth();
1326 Value *Src;
1327 const APInt *Amt;
1328 if (match(V, m_Trunc(m_LShr(m_Value(Src), m_APInt(Amt))))) {
1329 unsigned SrcWidth = Src->getType()->getIntegerBitWidth();
1330 uint64_t ShAmt = Amt->getLimitedValue(SrcWidth);
1331 // The field itself, if the lane width is the field width.
1332 if (std::optional<unsigned> Offset =
1333 GetFieldOffset(Amt, SrcWidth, LaneWidth))
1334 return std::make_tuple(Src, LaneWidth, *Offset);
1335 // The zero-extended top field of the source.
1336 unsigned FieldWidth = SrcWidth - ShAmt;
1337 if (FieldWidth > 0 && FieldWidth < LaneWidth && ShAmt % FieldWidth == 0)
1338 return std::make_tuple(Src, FieldWidth, ShAmt / FieldWidth);
1339 return std::nullopt;
1340 }
1341 if (match(V, m_LShr(m_Value(Src), m_APInt(Amt)))) {
1342 // The zero-extended top field of the source, if the result keeps exactly
1343 // one field. Look through a truncation of the shifted value.
1344 unsigned ShfWidth = Src->getType()->getIntegerBitWidth();
1345 uint64_t ShAmt = Amt->getLimitedValue(ShfWidth);
1346 unsigned FieldWidth = ShfWidth - ShAmt;
1347 if (FieldWidth > 0 && ShAmt % FieldWidth == 0) {
1348 match(Src, m_Trunc(m_Value(Src)));
1349 return std::make_tuple(Src, FieldWidth, ShAmt / FieldWidth);
1350 }
1351 return std::nullopt;
1352 }
1353 if (match(V, m_Trunc(m_Value(Src))))
1354 return std::make_tuple(Src, LaneWidth, 0u);
1355 return std::nullopt;
1356}
1357
1358std::optional<std::tuple<Value *, unsigned, SmallVector<int>>>
1360 // Splats are emitted as broadcasts, sub-fields of a constant are folded.
1361 // The bitcast to the field vector maps lane 0 to the least significant
1362 // field on little-endian targets only.
1363 if (VL.size() < 2 || !VL.front()->getType()->isIntegerTy() || isSplat(VL) ||
1364 DL.isBigEndian())
1365 return std::nullopt;
1366 Value *Src = nullptr;
1367 unsigned FieldWidth = 0;
1369 for (auto [Idx, V] : make_filter_range(enumerate(VL), [](const auto &P) {
1370 return !isa<UndefValue>(P.value());
1371 })) {
1372 if (V->getType() != VL.front()->getType())
1373 return std::nullopt;
1374 std::optional<std::tuple<Value *, unsigned, unsigned>> Field =
1376 if (!Field || (Src && (Src != std::get<0>(*Field) ||
1377 FieldWidth != std::get<1>(*Field))))
1378 return std::nullopt;
1379 Src = std::get<0>(*Field);
1380 FieldWidth = std::get<1>(*Field);
1381 Mask[Idx] = std::get<2>(*Field);
1382 }
1383 // The field width is a whole number of bytes and divides the source
1384 // exactly, same as for the packing layout, so the source bitcasts to the
1385 // field vector.
1386 if (!Src || isa<Constant>(Src) || FieldWidth % 8 != 0 ||
1387 Src->getType()->getIntegerBitWidth() % FieldWidth != 0)
1388 return std::nullopt;
1389 // The same field in every lane is a splat, emitted as a broadcast.
1390 if (all_of(Mask, [First = *find_if(Mask, not_equal_to(PoisonMaskElem))](
1391 int MaskElt) {
1392 return MaskElt == PoisonMaskElem || MaskElt == First;
1393 }))
1394 return std::nullopt;
1395 return std::make_tuple(Src, FieldWidth, std::move(Mask));
1396}
1397
1398/// Deeper than the standard analysis recursion depth to keep the numeric
1399/// bound precise through arithmetic carry chains.
1401
1402APInt getScalarMaxValue(const Value *V, unsigned Depth) {
1403 unsigned BitWidth = V->getType()->getScalarSizeInBits();
1405 if (Depth > MaxBitPackAnalysisDepth || !V->getType()->isIntegerTy())
1406 return Unknown;
1407 const APInt *C, *Amt;
1408 if (match(V, m_APInt(C)))
1409 return *C;
1410 Value *L, *R;
1411 if (match(V, m_Add(m_Value(L), m_Value(R))) ||
1412 match(V, m_Or(m_Value(L), m_Value(R))) ||
1413 match(V, m_Xor(m_Value(L), m_Value(R))))
1414 return getScalarMaxValue(L, Depth + 1)
1416 if (match(V, m_NUWSub(m_Value(L), m_Value(R))))
1417 return getScalarMaxValue(L, Depth + 1);
1418 if (match(V, m_Mul(m_Value(L), m_Value(R))))
1419 return getScalarMaxValue(L, Depth + 1)
1421 if (match(V, m_And(m_Value(L), m_Value(R))))
1422 return APIntOps::umin(getScalarMaxValue(L, Depth + 1),
1423 getScalarMaxValue(R, Depth + 1));
1424 if (match(V, m_LShr(m_Value(L), m_APInt(Amt))) && Amt->ult(BitWidth))
1425 return getScalarMaxValue(L, Depth + 1).lshr(*Amt);
1426 if (match(V, m_Shl(m_Value(L), m_APInt(Amt))) && Amt->ult(BitWidth)) {
1427 APInt LMax = getScalarMaxValue(L, Depth + 1);
1428 return LMax.getActiveBits() + Amt->getZExtValue() <= BitWidth
1429 ? LMax.shl(*Amt)
1430 : Unknown;
1431 }
1432 if (match(V, m_ZExt(m_Value(L))))
1433 return getScalarMaxValue(L, Depth + 1).zext(BitWidth);
1434 if (match(V, m_Trunc(m_Value(L)))) {
1435 APInt Max = getScalarMaxValue(L, Depth + 1);
1436 return Max.getActiveBits() <= BitWidth ? Max.trunc(BitWidth) : Unknown;
1437 }
1438 if (match(V, m_SExt(m_Value(L)))) {
1439 APInt Max = getScalarMaxValue(L, Depth + 1);
1440 return Max.isNonNegative() ? Max.zext(BitWidth) : Unknown;
1441 }
1442 Value *F;
1443 if (match(V, m_Select(m_Value(), m_Value(L), m_Value(F))))
1444 return APIntOps::umax(getScalarMaxValue(L, Depth + 1),
1445 getScalarMaxValue(F, Depth + 1));
1446 return Unknown;
1447}
1448
1449std::optional<BitPackInfo> computeBitPackInfo(unsigned BitWidth,
1450 ArrayRef<APInt> PossibleBits,
1451 ArrayRef<uint64_t> ShlAmts,
1452 ArrayRef<APInt> Masks) {
1453 unsigned NumElts = PossibleBits.size();
1454 BitPackInfo Info;
1455 Info.LShrAmts.assign(NumElts, 0);
1456 for (unsigned Idx : seq(NumElts)) {
1457 APInt Possible = PossibleBits[Idx].shl(ShlAmts[Idx]) & Masks[Idx];
1458 if (Possible.isZero())
1459 continue;
1460 unsigned Lo, W;
1461 if (!Possible.isShiftedMask(Lo, W))
1462 return std::nullopt;
1463 if (Info.FieldWidth == 0) {
1464 if (W % 8 != 0 || BitWidth % W != 0)
1465 return std::nullopt;
1466 Info.FieldWidth = W;
1467 Info.LaneOfField.assign(BitWidth / W, BitPackInfo::NoLane);
1468 }
1469 if (W != Info.FieldWidth || Lo % W != 0)
1470 return std::nullopt;
1471 unsigned Field = Lo / W;
1472 if (Info.LaneOfField[Field] != BitPackInfo::NoLane)
1473 return std::nullopt;
1474 Info.LaneOfField[Field] = Idx;
1475 Info.LShrAmts[Idx] = Lo - ShlAmts[Idx];
1476 }
1477 if (Info.FieldWidth == 0)
1478 return std::nullopt;
1479 return Info;
1480}
1481
1482SmallVector<int> getBitPackMask(const BitPackInfo &Info, unsigned NumBytes,
1483 unsigned NumElts, unsigned BytesPerLane) {
1484 unsigned BytesPerField = Info.FieldWidth / 8;
1485 SmallVector<int> Mask;
1486 for (unsigned J : seq(NumBytes)) {
1487 unsigned Lane = Info.LaneOfField[J / BytesPerField];
1488 Mask.push_back(Lane == BitPackInfo::NoLane
1489 ? (int)(NumElts * BytesPerLane)
1490 : (int)(Lane * BytesPerLane + J % BytesPerField));
1491 }
1492 return Mask;
1493}
1494
1496 Type *ResultTy, unsigned ShiftWidth, unsigned &NumInsts) {
1497 NumInsts = 0;
1498 auto *VecTy = cast<FixedVectorType>(X->getType());
1499 unsigned BitWidth = VecTy->getScalarSizeInBits();
1500 assert(BitWidth % 8 == 0 &&
1501 "The byte-multiple field width divides the result bit width.");
1502 unsigned NumElts = VecTy->getNumElements();
1503 Value *Y = X;
1504 if (ShiftWidth != BitWidth) {
1505 // Compacting a zext back to its source is free, use it directly.
1506 if (auto *Z = dyn_cast<ZExtInst>(X);
1507 Z && Z->getSrcTy()->getScalarSizeInBits() == ShiftWidth)
1508 Y = Z->getOperand(0);
1509 else {
1510 Y = Builder.CreateTrunc(
1511 Y, FixedVectorType::get(IntegerType::get(X->getContext(), ShiftWidth),
1512 NumElts));
1513 ++NumInsts;
1514 }
1515 }
1516 if (Info.needsShift()) {
1518 for (uint64_t A : Info.LShrAmts)
1519 Amts.push_back(
1520 ConstantInt::get(IntegerType::get(X->getContext(), ShiftWidth), A));
1521 Y = Builder.CreateLShr(Y, ConstantVector::get(Amts));
1522 ++NumInsts;
1523 }
1524 unsigned InBytes = NumElts * (ShiftWidth / 8);
1525 auto *ByteTy = FixedVectorType::get(Builder.getInt8Ty(), InBytes);
1527 Info, ResultTy->getScalarSizeInBits() / 8, NumElts, ShiftWidth / 8);
1528 // Fields in lane order, possibly reversed, are a truncation of the shifted
1529 // lanes. A reversal of byte fields is a bswap.
1530 bool IsReversed = equal(Info.LaneOfField, reverse(seq<unsigned>(NumElts)));
1531 if (IsReversed || equal(Info.LaneOfField, seq<unsigned>(NumElts))) {
1532 Value *Fields = Builder.CreateTrunc(
1533 Y, Y->getType()->getWithNewBitWidth(Info.FieldWidth));
1534 NumInsts += 1 + (Info.FieldWidth != ShiftWidth) + IsReversed;
1535 if (IsReversed && Info.FieldWidth == 8)
1536 return Builder.CreateUnaryIntrinsic(
1537 Intrinsic::bswap, Builder.CreateBitCast(Fields, ResultTy));
1538 if (IsReversed)
1539 Fields = Builder.CreateVectorReverse(Fields);
1540 return Builder.CreateBitCast(Fields, ResultTy);
1541 }
1542 Value *Packed = Builder.CreateShuffleVector(
1543 Builder.CreateBitCast(Y, ByteTy),
1544 is_contained(Info.LaneOfField, BitPackInfo::NoLane)
1545 ? Constant::getNullValue(ByteTy)
1546 : PoisonValue::get(ByteTy),
1547 Mask);
1548 NumInsts += 3;
1549 return Builder.CreateBitCast(Packed, ResultTy);
1550}
1551
1554 findDbgValues(&From, DVRs);
1555 auto *ExI = dyn_cast<Instruction>(&To);
1556 for (DbgVariableRecord *DVR : DVRs) {
1557 if (!DVR->isDbgValue())
1558 continue;
1559 Instruction *MarkedI = DVR->getInstruction();
1560 if (ExI && MarkedI->getParent() != ExI->getParent())
1561 continue;
1562 if (!ExI || ExI->comesBefore(MarkedI)) {
1563 DVR->replaceVariableLocationOp(&From, &To);
1564 continue;
1565 }
1566 DebugVariableAggregate Var(DVR);
1567 auto HasSameVar = [&](auto Records) {
1568 return any_of(filterDbgVars(Records),
1569 [&](const DbgVariableRecord &Other) {
1570 return DebugVariableAggregate(&Other) == Var;
1571 });
1572 };
1573 if (HasSameVar(make_range(std::next(DVR->getIterator()),
1574 MarkedI->getDbgRecordRange().end())) ||
1575 any_of(make_range(std::next(MarkedI->getIterator()),
1576 std::next(ExI->getIterator())),
1577 [&](const Instruction &I) {
1578 return HasSameVar(I.getDbgRecordRange());
1579 }))
1580 continue;
1581 DbgVariableRecord *NewDVR = DVR->clone();
1582 NewDVR->replaceVariableLocationOp(&From, &To);
1583 ExI->getParent()->insertDbgRecordAfter(NewDVR, ExI);
1584 }
1585}
1586
1588 const InsertElementInst *IE2) {
1589 if (IE1 == IE2)
1590 return false;
1591 const auto *I1 = IE1;
1592 const auto *I2 = IE2;
1593 const InsertElementInst *PrevI1;
1594 const InsertElementInst *PrevI2;
1595 unsigned Idx1 = *getElementIndex(IE1);
1596 unsigned Idx2 = *getElementIndex(IE2);
1597 do {
1598 if (I2 == IE1)
1599 return true;
1600 if (I1 == IE2)
1601 return false;
1602 PrevI1 = I1;
1603 PrevI2 = I2;
1604 if (I1 && (I1 == IE1 || I1->hasOneUse()) &&
1605 getElementIndex(I1).value_or(Idx2) != Idx2)
1606 I1 = dyn_cast<InsertElementInst>(I1->getOperand(0));
1607 if (I2 && ((I2 == IE2 || I2->hasOneUse())) &&
1608 getElementIndex(I2).value_or(Idx1) != Idx1)
1609 I2 = dyn_cast<InsertElementInst>(I2->getOperand(0));
1610 } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2));
1611 llvm_unreachable("Two different buildvectors not expected.");
1612}
1613
1615 if (DebugLoc DL = PN.getDebugLoc())
1616 return DL;
1617 return DebugLoc::getUnknown();
1618}
1619
1620std::optional<unsigned> getAggregateSize(Instruction *InsertInst) {
1621 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
1622 return cast<FixedVectorType>(IE->getType())->getNumElements();
1623
1624 unsigned AggregateSize = 1;
1625 auto *IV = cast<InsertValueInst>(InsertInst);
1626 Type *CurrentType = IV->getType();
1627 do {
1628 if (auto *ST = dyn_cast<StructType>(CurrentType)) {
1629 for (auto *Elt : ST->elements())
1630 if (Elt != ST->getElementType(0)) // check homogeneity
1631 return std::nullopt;
1632 AggregateSize *= ST->getNumElements();
1633 CurrentType = ST->getElementType(0);
1634 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
1635 AggregateSize *= AT->getNumElements();
1636 CurrentType = AT->getElementType();
1637 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
1638 AggregateSize *= VT->getNumElements();
1639 return AggregateSize;
1640 } else if (CurrentType->isSingleValueType()) {
1641 return AggregateSize;
1642 } else {
1643 return std::nullopt;
1644 }
1645 } while (true);
1646}
1647
1649 assert(L && "Expected valid loop");
1650 auto IsLoopInvariant = [&](const Loop *L, ArrayRef<Value *> VL) {
1652 [L](Instruction *I) { return L->isLoopInvariant(I); });
1653 };
1654 while (L && IsLoopInvariant(L, VL))
1655 L = L->getParentLoop();
1656 return L;
1657}
1658
1660 unsigned LoopAwareTripCount) {
1661 if (LoopAwareTripCount == 0)
1662 return 1;
1663 unsigned Scale = SE.getSmallConstantTripCount(L);
1664 if (Scale == 0)
1665 Scale = getLoopEstimatedTripCount(const_cast<Loop *>(L)).value_or(0);
1666 if (Scale != 0) {
1667 // Multiple exiting blocks - choose the minimum between trip count (scale)
1668 // and LoopAwareTripCount, since the multiple exit loops can be terminated
1669 // early.
1670 if (!L->getExitingBlock())
1671 return std::min<unsigned>(LoopAwareTripCount, Scale);
1672 return Scale;
1673 }
1674 return LoopAwareTripCount;
1675}
1676
1679 function_ref<Value *(InsertElementInst *)> GetBaseOperand) {
1680 // Instructions must be from the same basic blocks.
1681 if (VU->getParent() != V->getParent())
1682 return false;
1683 // Checks if 2 insertelements are from the same buildvector.
1684 if (VU->getType() != V->getType())
1685 return false;
1686 // Multiple used inserts are separate nodes.
1687 if (!VU->hasOneUse() && !V->hasOneUse())
1688 return false;
1689 auto *IE1 = VU;
1690 auto *IE2 = V;
1691 std::optional<unsigned> Idx1 = getElementIndex(IE1);
1692 std::optional<unsigned> Idx2 = getElementIndex(IE2);
1693 if (Idx1 == std::nullopt || Idx2 == std::nullopt)
1694 return false;
1695 // Go through the vector operand of insertelement instructions trying to find
1696 // either VU as the original vector for IE2 or V as the original vector for
1697 // IE1.
1699 bool IsReusedIdx = false;
1700 do {
1701 if (IE2 == VU && !IE1)
1702 return VU->hasOneUse();
1703 if (IE1 == V && !IE2)
1704 return V->hasOneUse();
1705 if (IE1 && IE1 != V) {
1706 unsigned Idx1 = getElementIndex(IE1).value_or(*Idx2);
1707 IsReusedIdx |= ReusedIdx.test(Idx1);
1708 ReusedIdx.set(Idx1);
1709 if ((IE1 != VU && !IE1->hasOneUse()) || IsReusedIdx)
1710 IE1 = nullptr;
1711 else
1712 IE1 = dyn_cast_if_present<InsertElementInst>(GetBaseOperand(IE1));
1713 }
1714 if (IE2 && IE2 != VU) {
1715 unsigned Idx2 = getElementIndex(IE2).value_or(*Idx1);
1716 IsReusedIdx |= ReusedIdx.test(Idx2);
1717 ReusedIdx.set(Idx2);
1718 if ((IE2 != V && !IE2->hasOneUse()) || IsReusedIdx)
1719 IE2 = nullptr;
1720 else
1721 IE2 = dyn_cast_if_present<InsertElementInst>(GetBaseOperand(IE2));
1722 }
1723 } while (!IsReusedIdx && (IE1 || IE2));
1724 return false;
1725}
1726
1727} // 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).
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.
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)
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:309
template SmallBitVector isUndefVector< true >(const Value *, const SmallBitVector &)
Constant * getReassocIdentity(unsigned Opcode, Type *Ty, bool Negated)
Definition SLPUtils.cpp:51
Value * createInsertVector(IRBuilderBase &Builder, Value *Vec, Value *V, unsigned Index, function_ref< Value *(Value *, Value *, ArrayRef< int >)> Generator)
Creates subvector insert.
Definition SLPUtils.cpp:704
bool areAllOperandsNonInsts(Value *V)
Checks if the provided value does not require scheduling.
Definition SLPUtils.cpp:478
std::optional< unsigned > getElementIndex(const Value *Inst, unsigned Offset)
Definition SLPUtils.cpp:263
DebugLoc getDebugLocFromPHI(const PHINode &PN)
bool isBinOpIdentityConstant(const Value *V, unsigned Opcode, bool Negated)
Definition SLPUtils.cpp:58
bool doesInTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, TargetLibraryInfo *TLI, const TargetTransformInfo *TTI)
Definition SLPUtils.cpp:807
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:945
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:835
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:853
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:757
Intrinsic::ID getMaskedDivRemIntrinsic(unsigned Opcode)
bool isUsedOutsideBlock(Value *V)
Checks if the provided value does not require scheduling.
Definition SLPUtils.cpp:489
bool doesNotNeedToSchedule(ArrayRef< Value * > VL)
Checks if the specified array of instructions does not require scheduling.
Definition SLPUtils.cpp:506
std::optional< unsigned > getInsertExtractIndex(const Value *Inst, unsigned Offset)
Definition SLPUtils.cpp:445
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:331
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:906
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:438
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:416
bool allSameOpcode(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:291
bool isSplat(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:172
unsigned getNumElements(Type *Ty)
Definition SLPUtils.cpp:117
std::string shortBundleName(ArrayRef< Value * > VL, int Idx)
Print a short descriptor of the instruction bundle suitable for debug output.
Definition SLPUtils.cpp:134
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:125
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:235
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:893
TargetTransformInfo::TargetCostKind getSLPCostKind(const Function *F)
bool isReverseOrder(ArrayRef< unsigned > Order)
Check if Order represents reverse order.
Definition SLPUtils.cpp:395
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:913
void transformScalarShuffleIndiciesToVector(unsigned VecTyNumElements, SmallVectorImpl< int > &Mask)
Definition SLPUtils.cpp:511
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:566
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:740
bool isCommutative(const Instruction *I, const Value *ValWithUses, bool IsCopyable)
Definition SLPUtils.cpp:195
template SmallBitVector isUndefVector< false >(const Value *, const SmallBitVector &)
unsigned getNumberOfPotentiallyCommutativeOps(Instruction *I)
Definition SLPUtils.cpp:253
bool allConstant(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:166
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:322
bool allSameBlock(ArrayRef< Value * > VL)
Definition SLPUtils.cpp:144
bool isReassocChainLink(const Instruction *I)
Definition SLPUtils.cpp:89
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:186
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:606
UseMask
Specifies the way the mask should be analyzed for undefs/poisonous elements in the shuffle mask.
Definition SLPUtils.h:313
@ SecondArg
The mask is expected to be for permutation of 2 vectors, check for the mask elements for the second a...
Definition SLPUtils.h:317
@ UndefsAsMask
Consider undef mask elements (-1) as placeholders for future shuffle elements and mark them as ones a...
Definition SLPUtils.h:320
@ FirstArg
The mask is expected to be for permutation of 1-2 vectors, check for the mask elements for the first ...
Definition SLPUtils.h:314
void reorderOrder(SmallVectorImpl< unsigned > &Order, ArrayRef< int > Mask, bool BottomOrder)
Reorders the given Order according to the given Mask.
Definition SLPUtils.cpp:351
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:341
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:843
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:69
bool isUndefTolerantBinOp(const Value *V)
Definition SLPUtils.cpp:63
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:526
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:78
bool isVectorLikeInstWithConstOps(Value *V)
Checks if V is one of vector-like instructions, i.e.
Definition SLPUtils.cpp:97
bool doesNotNeedToBeScheduled(Value *V)
Checks if the specified value does not require scheduling.
Definition SLPUtils.cpp:502
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:129
constexpr int UsesLimit
Limit of the number of uses for potentially transformed instructions/values, used in checks to avoid ...
Definition SLPUtils.h:59
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:404
bool isConstant(Value *V)
Definition SLPUtils.cpp:47
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:733
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:499
static constexpr unsigned NoLane
Definition SLPUtils.h:500
SmallVector< uint64_t, 8 > LShrAmts
Per-lane right-shift amounts bringing the field content to the low bits.
Definition SLPUtils.h:505