LLVM 21.0.0git
VectorCombine.cpp
Go to the documentation of this file.
1//===------- VectorCombine.cpp - Optimize partial vector operations -------===//
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// This pass optimizes scalar/vector interactions using target cost models. The
10// transforms implemented here may not fit in traditional loop-based or SLP
11// vectorization passes.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/ScopeExit.h"
19#include "llvm/ADT/Statistic.h"
23#include "llvm/Analysis/Loads.h"
27#include "llvm/IR/Dominators.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/IRBuilder.h"
34#include <numeric>
35#include <queue>
36
37#define DEBUG_TYPE "vector-combine"
39
40using namespace llvm;
41using namespace llvm::PatternMatch;
42
43STATISTIC(NumVecLoad, "Number of vector loads formed");
44STATISTIC(NumVecCmp, "Number of vector compares formed");
45STATISTIC(NumVecBO, "Number of vector binops formed");
46STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
47STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
48STATISTIC(NumScalarBO, "Number of scalar binops formed");
49STATISTIC(NumScalarCmp, "Number of scalar compares formed");
50
52 "disable-vector-combine", cl::init(false), cl::Hidden,
53 cl::desc("Disable all vector combine transforms"));
54
56 "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
57 cl::desc("Disable binop extract to shuffle transforms"));
58
60 "vector-combine-max-scan-instrs", cl::init(30), cl::Hidden,
61 cl::desc("Max number of instructions to scan for vector combining."));
62
63static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
64
65namespace {
66class VectorCombine {
67public:
68 VectorCombine(Function &F, const TargetTransformInfo &TTI,
69 const DominatorTree &DT, AAResults &AA, AssumptionCache &AC,
70 const DataLayout *DL, TTI::TargetCostKind CostKind,
71 bool TryEarlyFoldsOnly)
72 : F(F), Builder(F.getContext()), TTI(TTI), DT(DT), AA(AA), AC(AC), DL(DL),
73 CostKind(CostKind), TryEarlyFoldsOnly(TryEarlyFoldsOnly) {}
74
75 bool run();
76
77private:
78 Function &F;
79 IRBuilder<> Builder;
81 const DominatorTree &DT;
82 AAResults &AA;
84 const DataLayout *DL;
85 TTI::TargetCostKind CostKind;
86
87 /// If true, only perform beneficial early IR transforms. Do not introduce new
88 /// vector operations.
89 bool TryEarlyFoldsOnly;
90
91 InstructionWorklist Worklist;
92
93 // TODO: Direct calls from the top-level "run" loop use a plain "Instruction"
94 // parameter. That should be updated to specific sub-classes because the
95 // run loop was changed to dispatch on opcode.
96 bool vectorizeLoadInsert(Instruction &I);
97 bool widenSubvectorLoad(Instruction &I);
98 ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
100 unsigned PreferredExtractIndex) const;
101 bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
102 const Instruction &I,
103 ExtractElementInst *&ConvertToShuffle,
104 unsigned PreferredExtractIndex);
105 void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
106 Instruction &I);
107 void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
108 Instruction &I);
109 bool foldExtractExtract(Instruction &I);
110 bool foldInsExtFNeg(Instruction &I);
111 bool foldInsExtBinop(Instruction &I);
112 bool foldInsExtVectorToShuffle(Instruction &I);
113 bool foldBitcastShuffle(Instruction &I);
114 bool scalarizeBinopOrCmp(Instruction &I);
115 bool scalarizeVPIntrinsic(Instruction &I);
116 bool foldExtractedCmps(Instruction &I);
117 bool foldSingleElementStore(Instruction &I);
118 bool scalarizeLoadExtract(Instruction &I);
119 bool foldConcatOfBoolMasks(Instruction &I);
120 bool foldPermuteOfBinops(Instruction &I);
121 bool foldShuffleOfBinops(Instruction &I);
122 bool foldShuffleOfCastops(Instruction &I);
123 bool foldShuffleOfShuffles(Instruction &I);
124 bool foldShuffleOfIntrinsics(Instruction &I);
125 bool foldShuffleToIdentity(Instruction &I);
126 bool foldShuffleFromReductions(Instruction &I);
127 bool foldCastFromReductions(Instruction &I);
128 bool foldSelectShuffle(Instruction &I, bool FromReduction = false);
129 bool shrinkType(Instruction &I);
130
131 void replaceValue(Value &Old, Value &New) {
132 LLVM_DEBUG(dbgs() << "VC: Replacing: " << Old << '\n');
133 LLVM_DEBUG(dbgs() << " With: " << New << '\n');
134 Old.replaceAllUsesWith(&New);
135 if (auto *NewI = dyn_cast<Instruction>(&New)) {
136 New.takeName(&Old);
137 Worklist.pushUsersToWorkList(*NewI);
138 Worklist.pushValue(NewI);
139 }
140 Worklist.pushValue(&Old);
141 }
142
144 LLVM_DEBUG(dbgs() << "VC: Erasing: " << I << '\n');
145 SmallVector<Value *> Ops(I.operands());
146 Worklist.remove(&I);
147 I.eraseFromParent();
148
149 // Push remaining users of the operands and then the operand itself - allows
150 // further folds that were hindered by OneUse limits.
151 for (Value *Op : Ops)
152 if (auto *OpI = dyn_cast<Instruction>(Op)) {
153 Worklist.pushUsersToWorkList(*OpI);
154 Worklist.pushValue(OpI);
155 }
156 }
157};
158} // namespace
159
160/// Return the source operand of a potentially bitcasted value. If there is no
161/// bitcast, return the input value itself.
163 while (auto *BitCast = dyn_cast<BitCastInst>(V))
164 V = BitCast->getOperand(0);
165 return V;
166}
167
168static bool canWidenLoad(LoadInst *Load, const TargetTransformInfo &TTI) {
169 // Do not widen load if atomic/volatile or under asan/hwasan/memtag/tsan.
170 // The widened load may load data from dirty regions or create data races
171 // non-existent in the source.
172 if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
173 Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
175 return false;
176
177 // We are potentially transforming byte-sized (8-bit) memory accesses, so make
178 // sure we have all of our type-based constraints in place for this target.
179 Type *ScalarTy = Load->getType()->getScalarType();
180 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
181 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
182 if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
183 ScalarSize % 8 != 0)
184 return false;
185
186 return true;
187}
188
189bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
190 // Match insert into fixed vector of scalar value.
191 // TODO: Handle non-zero insert index.
192 Value *Scalar;
193 if (!match(&I,
195 return false;
196
197 // Optionally match an extract from another vector.
198 Value *X;
199 bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
200 if (!HasExtract)
201 X = Scalar;
202
203 auto *Load = dyn_cast<LoadInst>(X);
204 if (!canWidenLoad(Load, TTI))
205 return false;
206
207 Type *ScalarTy = Scalar->getType();
208 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
209 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
210
211 // Check safety of replacing the scalar load with a larger vector load.
212 // We use minimal alignment (maximum flexibility) because we only care about
213 // the dereferenceable region. When calculating cost and creating a new op,
214 // we may use a larger value based on alignment attributes.
215 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
216 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
217
218 unsigned MinVecNumElts = MinVectorSize / ScalarSize;
219 auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
220 unsigned OffsetEltIndex = 0;
221 Align Alignment = Load->getAlign();
222 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), *DL, Load, &AC,
223 &DT)) {
224 // It is not safe to load directly from the pointer, but we can still peek
225 // through gep offsets and check if it safe to load from a base address with
226 // updated alignment. If it is, we can shuffle the element(s) into place
227 // after loading.
228 unsigned OffsetBitWidth = DL->getIndexTypeSizeInBits(SrcPtr->getType());
229 APInt Offset(OffsetBitWidth, 0);
231
232 // We want to shuffle the result down from a high element of a vector, so
233 // the offset must be positive.
234 if (Offset.isNegative())
235 return false;
236
237 // The offset must be a multiple of the scalar element to shuffle cleanly
238 // in the element's size.
239 uint64_t ScalarSizeInBytes = ScalarSize / 8;
240 if (Offset.urem(ScalarSizeInBytes) != 0)
241 return false;
242
243 // If we load MinVecNumElts, will our target element still be loaded?
244 OffsetEltIndex = Offset.udiv(ScalarSizeInBytes).getZExtValue();
245 if (OffsetEltIndex >= MinVecNumElts)
246 return false;
247
248 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), *DL, Load, &AC,
249 &DT))
250 return false;
251
252 // Update alignment with offset value. Note that the offset could be negated
253 // to more accurately represent "(new) SrcPtr - Offset = (old) SrcPtr", but
254 // negation does not change the result of the alignment calculation.
255 Alignment = commonAlignment(Alignment, Offset.getZExtValue());
256 }
257
258 // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
259 // Use the greater of the alignment on the load or its source pointer.
260 Alignment = std::max(SrcPtr->getPointerAlignment(*DL), Alignment);
261 Type *LoadTy = Load->getType();
262 unsigned AS = Load->getPointerAddressSpace();
263 InstructionCost OldCost =
264 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS, CostKind);
265 APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
266 OldCost +=
267 TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
268 /* Insert */ true, HasExtract, CostKind);
269
270 // New pattern: load VecPtr
271 InstructionCost NewCost =
272 TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS, CostKind);
273 // Optionally, we are shuffling the loaded vector element(s) into place.
274 // For the mask set everything but element 0 to undef to prevent poison from
275 // propagating from the extra loaded memory. This will also optionally
276 // shrink/grow the vector from the loaded size to the output size.
277 // We assume this operation has no cost in codegen if there was no offset.
278 // Note that we could use freeze to avoid poison problems, but then we might
279 // still need a shuffle to change the vector size.
280 auto *Ty = cast<FixedVectorType>(I.getType());
281 unsigned OutputNumElts = Ty->getNumElements();
283 assert(OffsetEltIndex < MinVecNumElts && "Address offset too big");
284 Mask[0] = OffsetEltIndex;
285 if (OffsetEltIndex)
286 NewCost +=
288
289 // We can aggressively convert to the vector form because the backend can
290 // invert this transform if it does not result in a performance win.
291 if (OldCost < NewCost || !NewCost.isValid())
292 return false;
293
294 // It is safe and potentially profitable to load a vector directly:
295 // inselt undef, load Scalar, 0 --> load VecPtr
296 IRBuilder<> Builder(Load);
297 Value *CastedPtr =
298 Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Builder.getPtrTy(AS));
299 Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
300 VecLd = Builder.CreateShuffleVector(VecLd, Mask);
301
302 replaceValue(I, *VecLd);
303 ++NumVecLoad;
304 return true;
305}
306
307/// If we are loading a vector and then inserting it into a larger vector with
308/// undefined elements, try to load the larger vector and eliminate the insert.
309/// This removes a shuffle in IR and may allow combining of other loaded values.
310bool VectorCombine::widenSubvectorLoad(Instruction &I) {
311 // Match subvector insert of fixed vector.
312 auto *Shuf = cast<ShuffleVectorInst>(&I);
313 if (!Shuf->isIdentityWithPadding())
314 return false;
315
316 // Allow a non-canonical shuffle mask that is choosing elements from op1.
317 unsigned NumOpElts =
318 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
319 unsigned OpIndex = any_of(Shuf->getShuffleMask(), [&NumOpElts](int M) {
320 return M >= (int)(NumOpElts);
321 });
322
323 auto *Load = dyn_cast<LoadInst>(Shuf->getOperand(OpIndex));
324 if (!canWidenLoad(Load, TTI))
325 return false;
326
327 // We use minimal alignment (maximum flexibility) because we only care about
328 // the dereferenceable region. When calculating cost and creating a new op,
329 // we may use a larger value based on alignment attributes.
330 auto *Ty = cast<FixedVectorType>(I.getType());
331 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
332 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
333 Align Alignment = Load->getAlign();
334 if (!isSafeToLoadUnconditionally(SrcPtr, Ty, Align(1), *DL, Load, &AC, &DT))
335 return false;
336
337 Alignment = std::max(SrcPtr->getPointerAlignment(*DL), Alignment);
338 Type *LoadTy = Load->getType();
339 unsigned AS = Load->getPointerAddressSpace();
340
341 // Original pattern: insert_subvector (load PtrOp)
342 // This conservatively assumes that the cost of a subvector insert into an
343 // undef value is 0. We could add that cost if the cost model accurately
344 // reflects the real cost of that operation.
345 InstructionCost OldCost =
346 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS, CostKind);
347
348 // New pattern: load PtrOp
349 InstructionCost NewCost =
350 TTI.getMemoryOpCost(Instruction::Load, Ty, Alignment, AS, CostKind);
351
352 // We can aggressively convert to the vector form because the backend can
353 // invert this transform if it does not result in a performance win.
354 if (OldCost < NewCost || !NewCost.isValid())
355 return false;
356
357 IRBuilder<> Builder(Load);
358 Value *CastedPtr =
359 Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Builder.getPtrTy(AS));
360 Value *VecLd = Builder.CreateAlignedLoad(Ty, CastedPtr, Alignment);
361 replaceValue(I, *VecLd);
362 ++NumVecLoad;
363 return true;
364}
365
366/// Determine which, if any, of the inputs should be replaced by a shuffle
367/// followed by extract from a different index.
368ExtractElementInst *VectorCombine::getShuffleExtract(
370 unsigned PreferredExtractIndex = InvalidIndex) const {
371 auto *Index0C = dyn_cast<ConstantInt>(Ext0->getIndexOperand());
372 auto *Index1C = dyn_cast<ConstantInt>(Ext1->getIndexOperand());
373 assert(Index0C && Index1C && "Expected constant extract indexes");
374
375 unsigned Index0 = Index0C->getZExtValue();
376 unsigned Index1 = Index1C->getZExtValue();
377
378 // If the extract indexes are identical, no shuffle is needed.
379 if (Index0 == Index1)
380 return nullptr;
381
382 Type *VecTy = Ext0->getVectorOperand()->getType();
383 assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
384 InstructionCost Cost0 =
385 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
386 InstructionCost Cost1 =
387 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
388
389 // If both costs are invalid no shuffle is needed
390 if (!Cost0.isValid() && !Cost1.isValid())
391 return nullptr;
392
393 // We are extracting from 2 different indexes, so one operand must be shuffled
394 // before performing a vector operation and/or extract. The more expensive
395 // extract will be replaced by a shuffle.
396 if (Cost0 > Cost1)
397 return Ext0;
398 if (Cost1 > Cost0)
399 return Ext1;
400
401 // If the costs are equal and there is a preferred extract index, shuffle the
402 // opposite operand.
403 if (PreferredExtractIndex == Index0)
404 return Ext1;
405 if (PreferredExtractIndex == Index1)
406 return Ext0;
407
408 // Otherwise, replace the extract with the higher index.
409 return Index0 > Index1 ? Ext0 : Ext1;
410}
411
412/// Compare the relative costs of 2 extracts followed by scalar operation vs.
413/// vector operation(s) followed by extract. Return true if the existing
414/// instructions are cheaper than a vector alternative. Otherwise, return false
415/// and if one of the extracts should be transformed to a shufflevector, set
416/// \p ConvertToShuffle to that extract instruction.
417bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
418 ExtractElementInst *Ext1,
419 const Instruction &I,
420 ExtractElementInst *&ConvertToShuffle,
421 unsigned PreferredExtractIndex) {
422 auto *Ext0IndexC = dyn_cast<ConstantInt>(Ext0->getIndexOperand());
423 auto *Ext1IndexC = dyn_cast<ConstantInt>(Ext1->getIndexOperand());
424 assert(Ext0IndexC && Ext1IndexC && "Expected constant extract indexes");
425
426 unsigned Opcode = I.getOpcode();
427 Value *Ext0Src = Ext0->getVectorOperand();
428 Value *Ext1Src = Ext1->getVectorOperand();
429 Type *ScalarTy = Ext0->getType();
430 auto *VecTy = cast<VectorType>(Ext0Src->getType());
431 InstructionCost ScalarOpCost, VectorOpCost;
432
433 // Get cost estimates for scalar and vector versions of the operation.
434 bool IsBinOp = Instruction::isBinaryOp(Opcode);
435 if (IsBinOp) {
436 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy, CostKind);
437 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy, CostKind);
438 } else {
439 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
440 "Expected a compare");
441 CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
442 ScalarOpCost = TTI.getCmpSelInstrCost(
443 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred, CostKind);
444 VectorOpCost = TTI.getCmpSelInstrCost(
445 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred, CostKind);
446 }
447
448 // Get cost estimates for the extract elements. These costs will factor into
449 // both sequences.
450 unsigned Ext0Index = Ext0IndexC->getZExtValue();
451 unsigned Ext1Index = Ext1IndexC->getZExtValue();
452
453 InstructionCost Extract0Cost =
454 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Ext0Index);
455 InstructionCost Extract1Cost =
456 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Ext1Index);
457
458 // A more expensive extract will always be replaced by a splat shuffle.
459 // For example, if Ext0 is more expensive:
460 // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
461 // extelt (opcode (splat V0, Ext0), V1), Ext1
462 // TODO: Evaluate whether that always results in lowest cost. Alternatively,
463 // check the cost of creating a broadcast shuffle and shuffling both
464 // operands to element 0.
465 unsigned BestExtIndex = Extract0Cost > Extract1Cost ? Ext0Index : Ext1Index;
466 unsigned BestInsIndex = Extract0Cost > Extract1Cost ? Ext1Index : Ext0Index;
467 InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
468
469 // Extra uses of the extracts mean that we include those costs in the
470 // vector total because those instructions will not be eliminated.
471 InstructionCost OldCost, NewCost;
472 if (Ext0Src == Ext1Src && Ext0Index == Ext1Index) {
473 // Handle a special case. If the 2 extracts are identical, adjust the
474 // formulas to account for that. The extra use charge allows for either the
475 // CSE'd pattern or an unoptimized form with identical values:
476 // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
477 bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
478 : !Ext0->hasOneUse() || !Ext1->hasOneUse();
479 OldCost = CheapExtractCost + ScalarOpCost;
480 NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
481 } else {
482 // Handle the general case. Each extract is actually a different value:
483 // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
484 OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
485 NewCost = VectorOpCost + CheapExtractCost +
486 !Ext0->hasOneUse() * Extract0Cost +
487 !Ext1->hasOneUse() * Extract1Cost;
488 }
489
490 ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
491 if (ConvertToShuffle) {
492 if (IsBinOp && DisableBinopExtractShuffle)
493 return true;
494
495 // If we are extracting from 2 different indexes, then one operand must be
496 // shuffled before performing the vector operation. The shuffle mask is
497 // poison except for 1 lane that is being translated to the remaining
498 // extraction lane. Therefore, it is a splat shuffle. Ex:
499 // ShufMask = { poison, poison, 0, poison }
500 // TODO: The cost model has an option for a "broadcast" shuffle
501 // (splat-from-element-0), but no option for a more general splat.
502 if (auto *FixedVecTy = dyn_cast<FixedVectorType>(VecTy)) {
503 SmallVector<int> ShuffleMask(FixedVecTy->getNumElements(),
505 ShuffleMask[BestInsIndex] = BestExtIndex;
507 VecTy, ShuffleMask, CostKind, 0, nullptr,
508 {ConvertToShuffle});
509 } else {
510 NewCost +=
512 {}, CostKind, 0, nullptr, {ConvertToShuffle});
513 }
514 }
515
516 // Aggressively form a vector op if the cost is equal because the transform
517 // may enable further optimization.
518 // Codegen can reverse this transform (scalarize) if it was not profitable.
519 return OldCost < NewCost;
520}
521
522/// Create a shuffle that translates (shifts) 1 element from the input vector
523/// to a new element location.
524static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
525 unsigned NewIndex, IRBuilder<> &Builder) {
526 // The shuffle mask is poison except for 1 lane that is being translated
527 // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
528 // ShufMask = { 2, poison, poison, poison }
529 auto *VecTy = cast<FixedVectorType>(Vec->getType());
530 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem);
531 ShufMask[NewIndex] = OldIndex;
532 return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
533}
534
535/// Given an extract element instruction with constant index operand, shuffle
536/// the source vector (shift the scalar element) to a NewIndex for extraction.
537/// Return null if the input can be constant folded, so that we are not creating
538/// unnecessary instructions.
540 unsigned NewIndex,
541 IRBuilder<> &Builder) {
542 // Shufflevectors can only be created for fixed-width vectors.
543 Value *X = ExtElt->getVectorOperand();
544 if (!isa<FixedVectorType>(X->getType()))
545 return nullptr;
546
547 // If the extract can be constant-folded, this code is unsimplified. Defer
548 // to other passes to handle that.
549 Value *C = ExtElt->getIndexOperand();
550 assert(isa<ConstantInt>(C) && "Expected a constant index operand");
551 if (isa<Constant>(X))
552 return nullptr;
553
554 Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
555 NewIndex, Builder);
556 return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
557}
558
559/// Try to reduce extract element costs by converting scalar compares to vector
560/// compares followed by extract.
561/// cmp (ext0 V0, C), (ext1 V1, C)
562void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
564 assert(isa<CmpInst>(&I) && "Expected a compare");
565 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
566 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
567 "Expected matching constant extract indexes");
568
569 // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
570 ++NumVecCmp;
571 CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
572 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
573 Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
574 Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
575 replaceValue(I, *NewExt);
576}
577
578/// Try to reduce extract element costs by converting scalar binops to vector
579/// binops followed by extract.
580/// bo (ext0 V0, C), (ext1 V1, C)
581void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
583 assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
584 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
585 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
586 "Expected matching constant extract indexes");
587
588 // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
589 ++NumVecBO;
590 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
591 Value *VecBO =
592 Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
593
594 // All IR flags are safe to back-propagate because any potential poison
595 // created in unused vector elements is discarded by the extract.
596 if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
597 VecBOInst->copyIRFlags(&I);
598
599 Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
600 replaceValue(I, *NewExt);
601}
602
603/// Match an instruction with extracted vector operands.
604bool VectorCombine::foldExtractExtract(Instruction &I) {
605 // It is not safe to transform things like div, urem, etc. because we may
606 // create undefined behavior when executing those on unknown vector elements.
608 return false;
609
610 Instruction *I0, *I1;
612 if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
614 return false;
615
616 Value *V0, *V1;
617 uint64_t C0, C1;
618 if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
619 !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
620 V0->getType() != V1->getType())
621 return false;
622
623 // If the scalar value 'I' is going to be re-inserted into a vector, then try
624 // to create an extract to that same element. The extract/insert can be
625 // reduced to a "select shuffle".
626 // TODO: If we add a larger pattern match that starts from an insert, this
627 // probably becomes unnecessary.
628 auto *Ext0 = cast<ExtractElementInst>(I0);
629 auto *Ext1 = cast<ExtractElementInst>(I1);
630 uint64_t InsertIndex = InvalidIndex;
631 if (I.hasOneUse())
632 match(I.user_back(),
633 m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
634
635 ExtractElementInst *ExtractToChange;
636 if (isExtractExtractCheap(Ext0, Ext1, I, ExtractToChange, InsertIndex))
637 return false;
638
639 if (ExtractToChange) {
640 unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
641 ExtractElementInst *NewExtract =
642 translateExtract(ExtractToChange, CheapExtractIdx, Builder);
643 if (!NewExtract)
644 return false;
645 if (ExtractToChange == Ext0)
646 Ext0 = NewExtract;
647 else
648 Ext1 = NewExtract;
649 }
650
651 if (Pred != CmpInst::BAD_ICMP_PREDICATE)
652 foldExtExtCmp(Ext0, Ext1, I);
653 else
654 foldExtExtBinop(Ext0, Ext1, I);
655
656 Worklist.push(Ext0);
657 Worklist.push(Ext1);
658 return true;
659}
660
661/// Try to replace an extract + scalar fneg + insert with a vector fneg +
662/// shuffle.
663bool VectorCombine::foldInsExtFNeg(Instruction &I) {
664 // Match an insert (op (extract)) pattern.
665 Value *DestVec;
667 Instruction *FNeg;
668 if (!match(&I, m_InsertElt(m_Value(DestVec), m_OneUse(m_Instruction(FNeg)),
669 m_ConstantInt(Index))))
670 return false;
671
672 // Note: This handles the canonical fneg instruction and "fsub -0.0, X".
673 Value *SrcVec;
674 Instruction *Extract;
675 if (!match(FNeg, m_FNeg(m_CombineAnd(
676 m_Instruction(Extract),
677 m_ExtractElt(m_Value(SrcVec), m_SpecificInt(Index))))))
678 return false;
679
680 auto *VecTy = cast<FixedVectorType>(I.getType());
681 auto *ScalarTy = VecTy->getScalarType();
682 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcVec->getType());
683 if (!SrcVecTy || ScalarTy != SrcVecTy->getScalarType())
684 return false;
685
686 // Ignore bogus insert/extract index.
687 unsigned NumElts = VecTy->getNumElements();
688 if (Index >= NumElts)
689 return false;
690
691 // We are inserting the negated element into the same lane that we extracted
692 // from. This is equivalent to a select-shuffle that chooses all but the
693 // negated element from the destination vector.
694 SmallVector<int> Mask(NumElts);
695 std::iota(Mask.begin(), Mask.end(), 0);
696 Mask[Index] = Index + NumElts;
697 InstructionCost OldCost =
698 TTI.getArithmeticInstrCost(Instruction::FNeg, ScalarTy, CostKind) +
699 TTI.getVectorInstrCost(I, VecTy, CostKind, Index);
700
701 // If the extract has one use, it will be eliminated, so count it in the
702 // original cost. If it has more than one use, ignore the cost because it will
703 // be the same before/after.
704 if (Extract->hasOneUse())
705 OldCost += TTI.getVectorInstrCost(*Extract, VecTy, CostKind, Index);
706
707 InstructionCost NewCost =
708 TTI.getArithmeticInstrCost(Instruction::FNeg, VecTy, CostKind) +
710 CostKind);
711
712 bool NeedLenChg = SrcVecTy->getNumElements() != NumElts;
713 // If the lengths of the two vectors are not equal,
714 // we need to add a length-change vector. Add this cost.
715 SmallVector<int> SrcMask;
716 if (NeedLenChg) {
717 SrcMask.assign(NumElts, PoisonMaskElem);
718 SrcMask[Index] = Index;
720 SrcVecTy, SrcMask, CostKind);
721 }
722
723 if (NewCost > OldCost)
724 return false;
725
726 Value *NewShuf;
727 // insertelt DestVec, (fneg (extractelt SrcVec, Index)), Index
728 Value *VecFNeg = Builder.CreateFNegFMF(SrcVec, FNeg);
729 if (NeedLenChg) {
730 // shuffle DestVec, (shuffle (fneg SrcVec), poison, SrcMask), Mask
731 Value *LenChgShuf = Builder.CreateShuffleVector(VecFNeg, SrcMask);
732 NewShuf = Builder.CreateShuffleVector(DestVec, LenChgShuf, Mask);
733 } else {
734 // shuffle DestVec, (fneg SrcVec), Mask
735 NewShuf = Builder.CreateShuffleVector(DestVec, VecFNeg, Mask);
736 }
737
738 replaceValue(I, *NewShuf);
739 return true;
740}
741
742/// Try to fold insert(binop(x,y),binop(a,b),idx)
743/// --> binop(insert(x,a,idx),insert(y,b,idx))
744bool VectorCombine::foldInsExtBinop(Instruction &I) {
745 BinaryOperator *VecBinOp, *SclBinOp;
747 if (!match(&I,
748 m_InsertElt(m_OneUse(m_BinOp(VecBinOp)),
749 m_OneUse(m_BinOp(SclBinOp)), m_ConstantInt(Index))))
750 return false;
751
752 // TODO: Add support for addlike etc.
753 Instruction::BinaryOps BinOpcode = VecBinOp->getOpcode();
754 if (BinOpcode != SclBinOp->getOpcode())
755 return false;
756
757 auto *ResultTy = dyn_cast<FixedVectorType>(I.getType());
758 if (!ResultTy)
759 return false;
760
761 // TODO: Attempt to detect m_ExtractElt for scalar operands and convert to
762 // shuffle?
763
765 TTI.getInstructionCost(VecBinOp, CostKind) +
767 InstructionCost NewCost =
768 TTI.getArithmeticInstrCost(BinOpcode, ResultTy, CostKind) +
769 TTI.getVectorInstrCost(Instruction::InsertElement, ResultTy, CostKind,
770 Index, VecBinOp->getOperand(0),
771 SclBinOp->getOperand(0)) +
772 TTI.getVectorInstrCost(Instruction::InsertElement, ResultTy, CostKind,
773 Index, VecBinOp->getOperand(1),
774 SclBinOp->getOperand(1));
775
776 LLVM_DEBUG(dbgs() << "Found an insertion of two binops: " << I
777 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
778 << "\n");
779 if (NewCost > OldCost)
780 return false;
781
782 Value *NewIns0 = Builder.CreateInsertElement(VecBinOp->getOperand(0),
783 SclBinOp->getOperand(0), Index);
784 Value *NewIns1 = Builder.CreateInsertElement(VecBinOp->getOperand(1),
785 SclBinOp->getOperand(1), Index);
786 Value *NewBO = Builder.CreateBinOp(BinOpcode, NewIns0, NewIns1);
787
788 // Intersect flags from the old binops.
789 if (auto *NewInst = dyn_cast<Instruction>(NewBO)) {
790 NewInst->copyIRFlags(VecBinOp);
791 NewInst->andIRFlags(SclBinOp);
792 }
793
794 Worklist.pushValue(NewIns0);
795 Worklist.pushValue(NewIns1);
796 replaceValue(I, *NewBO);
797 return true;
798}
799
800/// If this is a bitcast of a shuffle, try to bitcast the source vector to the
801/// destination type followed by shuffle. This can enable further transforms by
802/// moving bitcasts or shuffles together.
803bool VectorCombine::foldBitcastShuffle(Instruction &I) {
804 Value *V0, *V1;
806 if (!match(&I, m_BitCast(m_OneUse(
807 m_Shuffle(m_Value(V0), m_Value(V1), m_Mask(Mask))))))
808 return false;
809
810 // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
811 // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
812 // mask for scalable type is a splat or not.
813 // 2) Disallow non-vector casts.
814 // TODO: We could allow any shuffle.
815 auto *DestTy = dyn_cast<FixedVectorType>(I.getType());
816 auto *SrcTy = dyn_cast<FixedVectorType>(V0->getType());
817 if (!DestTy || !SrcTy)
818 return false;
819
820 unsigned DestEltSize = DestTy->getScalarSizeInBits();
821 unsigned SrcEltSize = SrcTy->getScalarSizeInBits();
822 if (SrcTy->getPrimitiveSizeInBits() % DestEltSize != 0)
823 return false;
824
825 bool IsUnary = isa<UndefValue>(V1);
826
827 // For binary shuffles, only fold bitcast(shuffle(X,Y))
828 // if it won't increase the number of bitcasts.
829 if (!IsUnary) {
830 auto *BCTy0 = dyn_cast<FixedVectorType>(peekThroughBitcasts(V0)->getType());
831 auto *BCTy1 = dyn_cast<FixedVectorType>(peekThroughBitcasts(V1)->getType());
832 if (!(BCTy0 && BCTy0->getElementType() == DestTy->getElementType()) &&
833 !(BCTy1 && BCTy1->getElementType() == DestTy->getElementType()))
834 return false;
835 }
836
837 SmallVector<int, 16> NewMask;
838 if (DestEltSize <= SrcEltSize) {
839 // The bitcast is from wide to narrow/equal elements. The shuffle mask can
840 // always be expanded to the equivalent form choosing narrower elements.
841 assert(SrcEltSize % DestEltSize == 0 && "Unexpected shuffle mask");
842 unsigned ScaleFactor = SrcEltSize / DestEltSize;
843 narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
844 } else {
845 // The bitcast is from narrow elements to wide elements. The shuffle mask
846 // must choose consecutive elements to allow casting first.
847 assert(DestEltSize % SrcEltSize == 0 && "Unexpected shuffle mask");
848 unsigned ScaleFactor = DestEltSize / SrcEltSize;
849 if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
850 return false;
851 }
852
853 // Bitcast the shuffle src - keep its original width but using the destination
854 // scalar type.
855 unsigned NumSrcElts = SrcTy->getPrimitiveSizeInBits() / DestEltSize;
856 auto *NewShuffleTy =
857 FixedVectorType::get(DestTy->getScalarType(), NumSrcElts);
858 auto *OldShuffleTy =
859 FixedVectorType::get(SrcTy->getScalarType(), Mask.size());
860 unsigned NumOps = IsUnary ? 1 : 2;
861
862 // The new shuffle must not cost more than the old shuffle.
866
867 InstructionCost NewCost =
868 TTI.getShuffleCost(SK, NewShuffleTy, NewMask, CostKind) +
869 (NumOps * TTI.getCastInstrCost(Instruction::BitCast, NewShuffleTy, SrcTy,
870 TargetTransformInfo::CastContextHint::None,
871 CostKind));
872 InstructionCost OldCost =
873 TTI.getShuffleCost(SK, SrcTy, Mask, CostKind) +
874 TTI.getCastInstrCost(Instruction::BitCast, DestTy, OldShuffleTy,
875 TargetTransformInfo::CastContextHint::None,
876 CostKind);
877
878 LLVM_DEBUG(dbgs() << "Found a bitcasted shuffle: " << I << "\n OldCost: "
879 << OldCost << " vs NewCost: " << NewCost << "\n");
880
881 if (NewCost > OldCost || !NewCost.isValid())
882 return false;
883
884 // bitcast (shuf V0, V1, MaskC) --> shuf (bitcast V0), (bitcast V1), MaskC'
885 ++NumShufOfBitcast;
886 Value *CastV0 = Builder.CreateBitCast(peekThroughBitcasts(V0), NewShuffleTy);
887 Value *CastV1 = Builder.CreateBitCast(peekThroughBitcasts(V1), NewShuffleTy);
888 Value *Shuf = Builder.CreateShuffleVector(CastV0, CastV1, NewMask);
889 replaceValue(I, *Shuf);
890 return true;
891}
892
893/// VP Intrinsics whose vector operands are both splat values may be simplified
894/// into the scalar version of the operation and the result splatted. This
895/// can lead to scalarization down the line.
896bool VectorCombine::scalarizeVPIntrinsic(Instruction &I) {
897 if (!isa<VPIntrinsic>(I))
898 return false;
899 VPIntrinsic &VPI = cast<VPIntrinsic>(I);
900 Value *Op0 = VPI.getArgOperand(0);
901 Value *Op1 = VPI.getArgOperand(1);
902
903 if (!isSplatValue(Op0) || !isSplatValue(Op1))
904 return false;
905
906 // Check getSplatValue early in this function, to avoid doing unnecessary
907 // work.
908 Value *ScalarOp0 = getSplatValue(Op0);
909 Value *ScalarOp1 = getSplatValue(Op1);
910 if (!ScalarOp0 || !ScalarOp1)
911 return false;
912
913 // For the binary VP intrinsics supported here, the result on disabled lanes
914 // is a poison value. For now, only do this simplification if all lanes
915 // are active.
916 // TODO: Relax the condition that all lanes are active by using insertelement
917 // on inactive lanes.
918 auto IsAllTrueMask = [](Value *MaskVal) {
919 if (Value *SplattedVal = getSplatValue(MaskVal))
920 if (auto *ConstValue = dyn_cast<Constant>(SplattedVal))
921 return ConstValue->isAllOnesValue();
922 return false;
923 };
924 if (!IsAllTrueMask(VPI.getArgOperand(2)))
925 return false;
926
927 // Check to make sure we support scalarization of the intrinsic
928 Intrinsic::ID IntrID = VPI.getIntrinsicID();
929 if (!VPBinOpIntrinsic::isVPBinOp(IntrID))
930 return false;
931
932 // Calculate cost of splatting both operands into vectors and the vector
933 // intrinsic
934 VectorType *VecTy = cast<VectorType>(VPI.getType());
936 if (auto *FVTy = dyn_cast<FixedVectorType>(VecTy))
937 Mask.resize(FVTy->getNumElements(), 0);
938 InstructionCost SplatCost =
939 TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind, 0) +
941 CostKind);
942
943 // Calculate the cost of the VP Intrinsic
945 for (Value *V : VPI.args())
946 Args.push_back(V->getType());
947 IntrinsicCostAttributes Attrs(IntrID, VecTy, Args);
948 InstructionCost VectorOpCost = TTI.getIntrinsicInstrCost(Attrs, CostKind);
949 InstructionCost OldCost = 2 * SplatCost + VectorOpCost;
950
951 // Determine scalar opcode
952 std::optional<unsigned> FunctionalOpcode =
954 std::optional<Intrinsic::ID> ScalarIntrID = std::nullopt;
955 if (!FunctionalOpcode) {
956 ScalarIntrID = VPI.getFunctionalIntrinsicID();
957 if (!ScalarIntrID)
958 return false;
959 }
960
961 // Calculate cost of scalarizing
962 InstructionCost ScalarOpCost = 0;
963 if (ScalarIntrID) {
964 IntrinsicCostAttributes Attrs(*ScalarIntrID, VecTy->getScalarType(), Args);
965 ScalarOpCost = TTI.getIntrinsicInstrCost(Attrs, CostKind);
966 } else {
967 ScalarOpCost = TTI.getArithmeticInstrCost(*FunctionalOpcode,
968 VecTy->getScalarType(), CostKind);
969 }
970
971 // The existing splats may be kept around if other instructions use them.
972 InstructionCost CostToKeepSplats =
973 (SplatCost * !Op0->hasOneUse()) + (SplatCost * !Op1->hasOneUse());
974 InstructionCost NewCost = ScalarOpCost + SplatCost + CostToKeepSplats;
975
976 LLVM_DEBUG(dbgs() << "Found a VP Intrinsic to scalarize: " << VPI
977 << "\n");
978 LLVM_DEBUG(dbgs() << "Cost of Intrinsic: " << OldCost
979 << ", Cost of scalarizing:" << NewCost << "\n");
980
981 // We want to scalarize unless the vector variant actually has lower cost.
982 if (OldCost < NewCost || !NewCost.isValid())
983 return false;
984
985 // Scalarize the intrinsic
986 ElementCount EC = cast<VectorType>(Op0->getType())->getElementCount();
987 Value *EVL = VPI.getArgOperand(3);
988
989 // If the VP op might introduce UB or poison, we can scalarize it provided
990 // that we know the EVL > 0: If the EVL is zero, then the original VP op
991 // becomes a no-op and thus won't be UB, so make sure we don't introduce UB by
992 // scalarizing it.
993 bool SafeToSpeculate;
994 if (ScalarIntrID)
995 SafeToSpeculate = Intrinsic::getAttributes(I.getContext(), *ScalarIntrID)
996 .hasFnAttr(Attribute::AttrKind::Speculatable);
997 else
999 *FunctionalOpcode, &VPI, nullptr, &AC, &DT);
1000 if (!SafeToSpeculate &&
1001 !isKnownNonZero(EVL, SimplifyQuery(*DL, &DT, &AC, &VPI)))
1002 return false;
1003
1004 Value *ScalarVal =
1005 ScalarIntrID
1006 ? Builder.CreateIntrinsic(VecTy->getScalarType(), *ScalarIntrID,
1007 {ScalarOp0, ScalarOp1})
1008 : Builder.CreateBinOp((Instruction::BinaryOps)(*FunctionalOpcode),
1009 ScalarOp0, ScalarOp1);
1010
1011 replaceValue(VPI, *Builder.CreateVectorSplat(EC, ScalarVal));
1012 return true;
1013}
1014
1015/// Match a vector binop or compare instruction with at least one inserted
1016/// scalar operand and convert to scalar binop/cmp followed by insertelement.
1017bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
1019 Value *Ins0, *Ins1;
1020 if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
1021 !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
1022 return false;
1023
1024 // Do not convert the vector condition of a vector select into a scalar
1025 // condition. That may cause problems for codegen because of differences in
1026 // boolean formats and register-file transfers.
1027 // TODO: Can we account for that in the cost model?
1028 bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
1029 if (IsCmp)
1030 for (User *U : I.users())
1031 if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
1032 return false;
1033
1034 // Match against one or both scalar values being inserted into constant
1035 // vectors:
1036 // vec_op VecC0, (inselt VecC1, V1, Index)
1037 // vec_op (inselt VecC0, V0, Index), VecC1
1038 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
1039 // TODO: Deal with mismatched index constants and variable indexes?
1040 Constant *VecC0 = nullptr, *VecC1 = nullptr;
1041 Value *V0 = nullptr, *V1 = nullptr;
1042 uint64_t Index0 = 0, Index1 = 0;
1043 if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
1044 m_ConstantInt(Index0))) &&
1045 !match(Ins0, m_Constant(VecC0)))
1046 return false;
1047 if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
1048 m_ConstantInt(Index1))) &&
1049 !match(Ins1, m_Constant(VecC1)))
1050 return false;
1051
1052 bool IsConst0 = !V0;
1053 bool IsConst1 = !V1;
1054 if (IsConst0 && IsConst1)
1055 return false;
1056 if (!IsConst0 && !IsConst1 && Index0 != Index1)
1057 return false;
1058
1059 auto *VecTy0 = cast<VectorType>(Ins0->getType());
1060 auto *VecTy1 = cast<VectorType>(Ins1->getType());
1061 if (VecTy0->getElementCount().getKnownMinValue() <= Index0 ||
1062 VecTy1->getElementCount().getKnownMinValue() <= Index1)
1063 return false;
1064
1065 // Bail for single insertion if it is a load.
1066 // TODO: Handle this once getVectorInstrCost can cost for load/stores.
1067 auto *I0 = dyn_cast_or_null<Instruction>(V0);
1068 auto *I1 = dyn_cast_or_null<Instruction>(V1);
1069 if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
1070 (IsConst1 && I0 && I0->mayReadFromMemory()))
1071 return false;
1072
1073 uint64_t Index = IsConst0 ? Index1 : Index0;
1074 Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
1075 Type *VecTy = I.getType();
1076 assert(VecTy->isVectorTy() &&
1077 (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
1078 (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
1079 ScalarTy->isPointerTy()) &&
1080 "Unexpected types for insert element into binop or cmp");
1081
1082 unsigned Opcode = I.getOpcode();
1083 InstructionCost ScalarOpCost, VectorOpCost;
1084 if (IsCmp) {
1085 CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
1086 ScalarOpCost = TTI.getCmpSelInstrCost(
1087 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred, CostKind);
1088 VectorOpCost = TTI.getCmpSelInstrCost(
1089 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred, CostKind);
1090 } else {
1091 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy, CostKind);
1092 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy, CostKind);
1093 }
1094
1095 // Get cost estimate for the insert element. This cost will factor into
1096 // both sequences.
1098 Instruction::InsertElement, VecTy, CostKind, Index);
1099 InstructionCost OldCost =
1100 (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + VectorOpCost;
1101 InstructionCost NewCost = ScalarOpCost + InsertCost +
1102 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
1103 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
1104
1105 // We want to scalarize unless the vector variant actually has lower cost.
1106 if (OldCost < NewCost || !NewCost.isValid())
1107 return false;
1108
1109 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
1110 // inselt NewVecC, (scalar_op V0, V1), Index
1111 if (IsCmp)
1112 ++NumScalarCmp;
1113 else
1114 ++NumScalarBO;
1115
1116 // For constant cases, extract the scalar element, this should constant fold.
1117 if (IsConst0)
1118 V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
1119 if (IsConst1)
1120 V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
1121
1122 Value *Scalar =
1123 IsCmp ? Builder.CreateCmp(Pred, V0, V1)
1124 : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
1125
1126 Scalar->setName(I.getName() + ".scalar");
1127
1128 // All IR flags are safe to back-propagate. There is no potential for extra
1129 // poison to be created by the scalar instruction.
1130 if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
1131 ScalarInst->copyIRFlags(&I);
1132
1133 // Fold the vector constants in the original vectors into a new base vector.
1134 Value *NewVecC =
1135 IsCmp ? Builder.CreateCmp(Pred, VecC0, VecC1)
1136 : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, VecC0, VecC1);
1137 Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
1138 replaceValue(I, *Insert);
1139 return true;
1140}
1141
1142/// Try to combine a scalar binop + 2 scalar compares of extracted elements of
1143/// a vector into vector operations followed by extract. Note: The SLP pass
1144/// may miss this pattern because of implementation problems.
1145bool VectorCombine::foldExtractedCmps(Instruction &I) {
1146 auto *BI = dyn_cast<BinaryOperator>(&I);
1147
1148 // We are looking for a scalar binop of booleans.
1149 // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
1150 if (!BI || !I.getType()->isIntegerTy(1))
1151 return false;
1152
1153 // The compare predicates should match, and each compare should have a
1154 // constant operand.
1155 Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
1156 Instruction *I0, *I1;
1157 Constant *C0, *C1;
1158 CmpPredicate P0, P1;
1159 if (!match(B0, m_Cmp(P0, m_Instruction(I0), m_Constant(C0))) ||
1160 !match(B1, m_Cmp(P1, m_Instruction(I1), m_Constant(C1))))
1161 return false;
1162
1163 auto MatchingPred = CmpPredicate::getMatching(P0, P1);
1164 if (!MatchingPred)
1165 return false;
1166
1167 // The compare operands must be extracts of the same vector with constant
1168 // extract indexes.
1169 Value *X;
1170 uint64_t Index0, Index1;
1171 if (!match(I0, m_ExtractElt(m_Value(X), m_ConstantInt(Index0))) ||
1172 !match(I1, m_ExtractElt(m_Specific(X), m_ConstantInt(Index1))))
1173 return false;
1174
1175 auto *Ext0 = cast<ExtractElementInst>(I0);
1176 auto *Ext1 = cast<ExtractElementInst>(I1);
1177 ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1, CostKind);
1178 if (!ConvertToShuf)
1179 return false;
1180 assert((ConvertToShuf == Ext0 || ConvertToShuf == Ext1) &&
1181 "Unknown ExtractElementInst");
1182
1183 // The original scalar pattern is:
1184 // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
1185 CmpInst::Predicate Pred = *MatchingPred;
1186 unsigned CmpOpcode =
1187 CmpInst::isFPPredicate(Pred) ? Instruction::FCmp : Instruction::ICmp;
1188 auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
1189 if (!VecTy)
1190 return false;
1191
1192 InstructionCost Ext0Cost =
1193 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
1194 InstructionCost Ext1Cost =
1195 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
1197 CmpOpcode, I0->getType(), CmpInst::makeCmpResultType(I0->getType()), Pred,
1198 CostKind);
1199
1200 InstructionCost OldCost =
1201 Ext0Cost + Ext1Cost + CmpCost * 2 +
1202 TTI.getArithmeticInstrCost(I.getOpcode(), I.getType(), CostKind);
1203
1204 // The proposed vector pattern is:
1205 // vcmp = cmp Pred X, VecC
1206 // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
1207 int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
1208 int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
1209 auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
1211 CmpOpcode, X->getType(), CmpInst::makeCmpResultType(X->getType()), Pred,
1212 CostKind);
1213 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem);
1214 ShufMask[CheapIndex] = ExpensiveIndex;
1216 ShufMask, CostKind);
1217 NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy, CostKind);
1218 NewCost += TTI.getVectorInstrCost(*Ext0, CmpTy, CostKind, CheapIndex);
1219 NewCost += Ext0->hasOneUse() ? 0 : Ext0Cost;
1220 NewCost += Ext1->hasOneUse() ? 0 : Ext1Cost;
1221
1222 // Aggressively form vector ops if the cost is equal because the transform
1223 // may enable further optimization.
1224 // Codegen can reverse this transform (scalarize) if it was not profitable.
1225 if (OldCost < NewCost || !NewCost.isValid())
1226 return false;
1227
1228 // Create a vector constant from the 2 scalar constants.
1229 SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
1230 PoisonValue::get(VecTy->getElementType()));
1231 CmpC[Index0] = C0;
1232 CmpC[Index1] = C1;
1233 Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
1234 Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
1235 Value *LHS = ConvertToShuf == Ext0 ? Shuf : VCmp;
1236 Value *RHS = ConvertToShuf == Ext0 ? VCmp : Shuf;
1237 Value *VecLogic = Builder.CreateBinOp(BI->getOpcode(), LHS, RHS);
1238 Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
1239 replaceValue(I, *NewExt);
1240 ++NumVecCmpBO;
1241 return true;
1242}
1243
1244// Check if memory loc modified between two instrs in the same BB
1247 const MemoryLocation &Loc, AAResults &AA) {
1248 unsigned NumScanned = 0;
1249 return std::any_of(Begin, End, [&](const Instruction &Instr) {
1250 return isModSet(AA.getModRefInfo(&Instr, Loc)) ||
1251 ++NumScanned > MaxInstrsToScan;
1252 });
1253}
1254
1255namespace {
1256/// Helper class to indicate whether a vector index can be safely scalarized and
1257/// if a freeze needs to be inserted.
1258class ScalarizationResult {
1259 enum class StatusTy { Unsafe, Safe, SafeWithFreeze };
1260
1261 StatusTy Status;
1262 Value *ToFreeze;
1263
1264 ScalarizationResult(StatusTy Status, Value *ToFreeze = nullptr)
1265 : Status(Status), ToFreeze(ToFreeze) {}
1266
1267public:
1268 ScalarizationResult(const ScalarizationResult &Other) = default;
1269 ~ScalarizationResult() {
1270 assert(!ToFreeze && "freeze() not called with ToFreeze being set");
1271 }
1272
1273 static ScalarizationResult unsafe() { return {StatusTy::Unsafe}; }
1274 static ScalarizationResult safe() { return {StatusTy::Safe}; }
1275 static ScalarizationResult safeWithFreeze(Value *ToFreeze) {
1276 return {StatusTy::SafeWithFreeze, ToFreeze};
1277 }
1278
1279 /// Returns true if the index can be scalarize without requiring a freeze.
1280 bool isSafe() const { return Status == StatusTy::Safe; }
1281 /// Returns true if the index cannot be scalarized.
1282 bool isUnsafe() const { return Status == StatusTy::Unsafe; }
1283 /// Returns true if the index can be scalarize, but requires inserting a
1284 /// freeze.
1285 bool isSafeWithFreeze() const { return Status == StatusTy::SafeWithFreeze; }
1286
1287 /// Reset the state of Unsafe and clear ToFreze if set.
1288 void discard() {
1289 ToFreeze = nullptr;
1290 Status = StatusTy::Unsafe;
1291 }
1292
1293 /// Freeze the ToFreeze and update the use in \p User to use it.
1294 void freeze(IRBuilder<> &Builder, Instruction &UserI) {
1295 assert(isSafeWithFreeze() &&
1296 "should only be used when freezing is required");
1297 assert(is_contained(ToFreeze->users(), &UserI) &&
1298 "UserI must be a user of ToFreeze");
1299 IRBuilder<>::InsertPointGuard Guard(Builder);
1300 Builder.SetInsertPoint(cast<Instruction>(&UserI));
1301 Value *Frozen =
1302 Builder.CreateFreeze(ToFreeze, ToFreeze->getName() + ".frozen");
1303 for (Use &U : make_early_inc_range((UserI.operands())))
1304 if (U.get() == ToFreeze)
1305 U.set(Frozen);
1306
1307 ToFreeze = nullptr;
1308 }
1309};
1310} // namespace
1311
1312/// Check if it is legal to scalarize a memory access to \p VecTy at index \p
1313/// Idx. \p Idx must access a valid vector element.
1314static ScalarizationResult canScalarizeAccess(VectorType *VecTy, Value *Idx,
1315 Instruction *CtxI,
1316 AssumptionCache &AC,
1317 const DominatorTree &DT) {
1318 // We do checks for both fixed vector types and scalable vector types.
1319 // This is the number of elements of fixed vector types,
1320 // or the minimum number of elements of scalable vector types.
1321 uint64_t NumElements = VecTy->getElementCount().getKnownMinValue();
1322
1323 if (auto *C = dyn_cast<ConstantInt>(Idx)) {
1324 if (C->getValue().ult(NumElements))
1325 return ScalarizationResult::safe();
1326 return ScalarizationResult::unsafe();
1327 }
1328
1329 unsigned IntWidth = Idx->getType()->getScalarSizeInBits();
1330 APInt Zero(IntWidth, 0);
1331 APInt MaxElts(IntWidth, NumElements);
1332 ConstantRange ValidIndices(Zero, MaxElts);
1333 ConstantRange IdxRange(IntWidth, true);
1334
1335 if (isGuaranteedNotToBePoison(Idx, &AC)) {
1336 if (ValidIndices.contains(computeConstantRange(Idx, /* ForSigned */ false,
1337 true, &AC, CtxI, &DT)))
1338 return ScalarizationResult::safe();
1339 return ScalarizationResult::unsafe();
1340 }
1341
1342 // If the index may be poison, check if we can insert a freeze before the
1343 // range of the index is restricted.
1344 Value *IdxBase;
1345 ConstantInt *CI;
1346 if (match(Idx, m_And(m_Value(IdxBase), m_ConstantInt(CI)))) {
1347 IdxRange = IdxRange.binaryAnd(CI->getValue());
1348 } else if (match(Idx, m_URem(m_Value(IdxBase), m_ConstantInt(CI)))) {
1349 IdxRange = IdxRange.urem(CI->getValue());
1350 }
1351
1352 if (ValidIndices.contains(IdxRange))
1353 return ScalarizationResult::safeWithFreeze(IdxBase);
1354 return ScalarizationResult::unsafe();
1355}
1356
1357/// The memory operation on a vector of \p ScalarType had alignment of
1358/// \p VectorAlignment. Compute the maximal, but conservatively correct,
1359/// alignment that will be valid for the memory operation on a single scalar
1360/// element of the same type with index \p Idx.
1362 Type *ScalarType, Value *Idx,
1363 const DataLayout &DL) {
1364 if (auto *C = dyn_cast<ConstantInt>(Idx))
1365 return commonAlignment(VectorAlignment,
1366 C->getZExtValue() * DL.getTypeStoreSize(ScalarType));
1367 return commonAlignment(VectorAlignment, DL.getTypeStoreSize(ScalarType));
1368}
1369
1370// Combine patterns like:
1371// %0 = load <4 x i32>, <4 x i32>* %a
1372// %1 = insertelement <4 x i32> %0, i32 %b, i32 1
1373// store <4 x i32> %1, <4 x i32>* %a
1374// to:
1375// %0 = bitcast <4 x i32>* %a to i32*
1376// %1 = getelementptr inbounds i32, i32* %0, i64 0, i64 1
1377// store i32 %b, i32* %1
1378bool VectorCombine::foldSingleElementStore(Instruction &I) {
1379 auto *SI = cast<StoreInst>(&I);
1380 if (!SI->isSimple() || !isa<VectorType>(SI->getValueOperand()->getType()))
1381 return false;
1382
1383 // TODO: Combine more complicated patterns (multiple insert) by referencing
1384 // TargetTransformInfo.
1386 Value *NewElement;
1387 Value *Idx;
1388 if (!match(SI->getValueOperand(),
1389 m_InsertElt(m_Instruction(Source), m_Value(NewElement),
1390 m_Value(Idx))))
1391 return false;
1392
1393 if (auto *Load = dyn_cast<LoadInst>(Source)) {
1394 auto VecTy = cast<VectorType>(SI->getValueOperand()->getType());
1395 Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts();
1396 // Don't optimize for atomic/volatile load or store. Ensure memory is not
1397 // modified between, vector type matches store size, and index is inbounds.
1398 if (!Load->isSimple() || Load->getParent() != SI->getParent() ||
1399 !DL->typeSizeEqualsStoreSize(Load->getType()->getScalarType()) ||
1400 SrcAddr != SI->getPointerOperand()->stripPointerCasts())
1401 return false;
1402
1403 auto ScalarizableIdx = canScalarizeAccess(VecTy, Idx, Load, AC, DT);
1404 if (ScalarizableIdx.isUnsafe() ||
1405 isMemModifiedBetween(Load->getIterator(), SI->getIterator(),
1406 MemoryLocation::get(SI), AA))
1407 return false;
1408
1409 // Ensure we add the load back to the worklist BEFORE its users so they can
1410 // erased in the correct order.
1411 Worklist.push(Load);
1412
1413 if (ScalarizableIdx.isSafeWithFreeze())
1414 ScalarizableIdx.freeze(Builder, *cast<Instruction>(Idx));
1415 Value *GEP = Builder.CreateInBoundsGEP(
1416 SI->getValueOperand()->getType(), SI->getPointerOperand(),
1417 {ConstantInt::get(Idx->getType(), 0), Idx});
1418 StoreInst *NSI = Builder.CreateStore(NewElement, GEP);
1419 NSI->copyMetadata(*SI);
1420 Align ScalarOpAlignment = computeAlignmentAfterScalarization(
1421 std::max(SI->getAlign(), Load->getAlign()), NewElement->getType(), Idx,
1422 *DL);
1423 NSI->setAlignment(ScalarOpAlignment);
1424 replaceValue(I, *NSI);
1426 return true;
1427 }
1428
1429 return false;
1430}
1431
1432/// Try to scalarize vector loads feeding extractelement instructions.
1433bool VectorCombine::scalarizeLoadExtract(Instruction &I) {
1434 Value *Ptr;
1435 if (!match(&I, m_Load(m_Value(Ptr))))
1436 return false;
1437
1438 auto *LI = cast<LoadInst>(&I);
1439 auto *VecTy = cast<VectorType>(LI->getType());
1440 if (LI->isVolatile() || !DL->typeSizeEqualsStoreSize(VecTy->getScalarType()))
1441 return false;
1442
1443 InstructionCost OriginalCost =
1444 TTI.getMemoryOpCost(Instruction::Load, VecTy, LI->getAlign(),
1445 LI->getPointerAddressSpace(), CostKind);
1446 InstructionCost ScalarizedCost = 0;
1447
1448 Instruction *LastCheckedInst = LI;
1449 unsigned NumInstChecked = 0;
1451 auto FailureGuard = make_scope_exit([&]() {
1452 // If the transform is aborted, discard the ScalarizationResults.
1453 for (auto &Pair : NeedFreeze)
1454 Pair.second.discard();
1455 });
1456
1457 // Check if all users of the load are extracts with no memory modifications
1458 // between the load and the extract. Compute the cost of both the original
1459 // code and the scalarized version.
1460 for (User *U : LI->users()) {
1461 auto *UI = dyn_cast<ExtractElementInst>(U);
1462 if (!UI || UI->getParent() != LI->getParent())
1463 return false;
1464
1465 // Check if any instruction between the load and the extract may modify
1466 // memory.
1467 if (LastCheckedInst->comesBefore(UI)) {
1468 for (Instruction &I :
1469 make_range(std::next(LI->getIterator()), UI->getIterator())) {
1470 // Bail out if we reached the check limit or the instruction may write
1471 // to memory.
1472 if (NumInstChecked == MaxInstrsToScan || I.mayWriteToMemory())
1473 return false;
1474 NumInstChecked++;
1475 }
1476 LastCheckedInst = UI;
1477 }
1478
1479 auto ScalarIdx =
1480 canScalarizeAccess(VecTy, UI->getIndexOperand(), LI, AC, DT);
1481 if (ScalarIdx.isUnsafe())
1482 return false;
1483 if (ScalarIdx.isSafeWithFreeze()) {
1484 NeedFreeze.try_emplace(UI, ScalarIdx);
1485 ScalarIdx.discard();
1486 }
1487
1488 auto *Index = dyn_cast<ConstantInt>(UI->getIndexOperand());
1489 OriginalCost +=
1490 TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, CostKind,
1491 Index ? Index->getZExtValue() : -1);
1492 ScalarizedCost +=
1493 TTI.getMemoryOpCost(Instruction::Load, VecTy->getElementType(),
1494 Align(1), LI->getPointerAddressSpace(), CostKind);
1495 ScalarizedCost += TTI.getAddressComputationCost(VecTy->getElementType());
1496 }
1497
1498 if (ScalarizedCost >= OriginalCost)
1499 return false;
1500
1501 // Ensure we add the load back to the worklist BEFORE its users so they can
1502 // erased in the correct order.
1503 Worklist.push(LI);
1504
1505 // Replace extracts with narrow scalar loads.
1506 for (User *U : LI->users()) {
1507 auto *EI = cast<ExtractElementInst>(U);
1508 Value *Idx = EI->getIndexOperand();
1509
1510 // Insert 'freeze' for poison indexes.
1511 auto It = NeedFreeze.find(EI);
1512 if (It != NeedFreeze.end())
1513 It->second.freeze(Builder, *cast<Instruction>(Idx));
1514
1515 Builder.SetInsertPoint(EI);
1516 Value *GEP =
1517 Builder.CreateInBoundsGEP(VecTy, Ptr, {Builder.getInt32(0), Idx});
1518 auto *NewLoad = cast<LoadInst>(Builder.CreateLoad(
1519 VecTy->getElementType(), GEP, EI->getName() + ".scalar"));
1520
1521 Align ScalarOpAlignment = computeAlignmentAfterScalarization(
1522 LI->getAlign(), VecTy->getElementType(), Idx, *DL);
1523 NewLoad->setAlignment(ScalarOpAlignment);
1524
1525 replaceValue(*EI, *NewLoad);
1526 }
1527
1528 FailureGuard.release();
1529 return true;
1530}
1531
1532/// Try to fold "(or (zext (bitcast X)), (shl (zext (bitcast Y)), C))"
1533/// to "(bitcast (concat X, Y))"
1534/// where X/Y are bitcasted from i1 mask vectors.
1535bool VectorCombine::foldConcatOfBoolMasks(Instruction &I) {
1536 Type *Ty = I.getType();
1537 if (!Ty->isIntegerTy())
1538 return false;
1539
1540 // TODO: Add big endian test coverage
1541 if (DL->isBigEndian())
1542 return false;
1543
1544 // Restrict to disjoint cases so the mask vectors aren't overlapping.
1545 Instruction *X, *Y;
1547 return false;
1548
1549 // Allow both sources to contain shl, to handle more generic pattern:
1550 // "(or (shl (zext (bitcast X)), C1), (shl (zext (bitcast Y)), C2))"
1551 Value *SrcX;
1552 uint64_t ShAmtX = 0;
1553 if (!match(X, m_OneUse(m_ZExt(m_OneUse(m_BitCast(m_Value(SrcX)))))) &&
1554 !match(X, m_OneUse(
1556 m_ConstantInt(ShAmtX)))))
1557 return false;
1558
1559 Value *SrcY;
1560 uint64_t ShAmtY = 0;
1561 if (!match(Y, m_OneUse(m_ZExt(m_OneUse(m_BitCast(m_Value(SrcY)))))) &&
1562 !match(Y, m_OneUse(
1564 m_ConstantInt(ShAmtY)))))
1565 return false;
1566
1567 // Canonicalize larger shift to the RHS.
1568 if (ShAmtX > ShAmtY) {
1569 std::swap(X, Y);
1570 std::swap(SrcX, SrcY);
1571 std::swap(ShAmtX, ShAmtY);
1572 }
1573
1574 // Ensure both sources are matching vXi1 bool mask types, and that the shift
1575 // difference is the mask width so they can be easily concatenated together.
1576 uint64_t ShAmtDiff = ShAmtY - ShAmtX;
1577 unsigned NumSHL = (ShAmtX > 0) + (ShAmtY > 0);
1578 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
1579 auto *MaskTy = dyn_cast<FixedVectorType>(SrcX->getType());
1580 if (!MaskTy || SrcX->getType() != SrcY->getType() ||
1581 !MaskTy->getElementType()->isIntegerTy(1) ||
1582 MaskTy->getNumElements() != ShAmtDiff ||
1583 MaskTy->getNumElements() > (BitWidth / 2))
1584 return false;
1585
1586 auto *ConcatTy = FixedVectorType::getDoubleElementsVectorType(MaskTy);
1587 auto *ConcatIntTy =
1588 Type::getIntNTy(Ty->getContext(), ConcatTy->getNumElements());
1589 auto *MaskIntTy = Type::getIntNTy(Ty->getContext(), ShAmtDiff);
1590
1591 SmallVector<int, 32> ConcatMask(ConcatTy->getNumElements());
1592 std::iota(ConcatMask.begin(), ConcatMask.end(), 0);
1593
1594 // TODO: Is it worth supporting multi use cases?
1595 InstructionCost OldCost = 0;
1596 OldCost += TTI.getArithmeticInstrCost(Instruction::Or, Ty, CostKind);
1597 OldCost +=
1598 NumSHL * TTI.getArithmeticInstrCost(Instruction::Shl, Ty, CostKind);
1599 OldCost += 2 * TTI.getCastInstrCost(Instruction::ZExt, Ty, MaskIntTy,
1601 OldCost += 2 * TTI.getCastInstrCost(Instruction::BitCast, MaskIntTy, MaskTy,
1603
1604 InstructionCost NewCost = 0;
1606 ConcatMask, CostKind);
1607 NewCost += TTI.getCastInstrCost(Instruction::BitCast, ConcatIntTy, ConcatTy,
1609 if (Ty != ConcatIntTy)
1610 NewCost += TTI.getCastInstrCost(Instruction::ZExt, Ty, ConcatIntTy,
1612 if (ShAmtX > 0)
1613 NewCost += TTI.getArithmeticInstrCost(Instruction::Shl, Ty, CostKind);
1614
1615 LLVM_DEBUG(dbgs() << "Found a concatenation of bitcasted bool masks: " << I
1616 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
1617 << "\n");
1618
1619 if (NewCost > OldCost)
1620 return false;
1621
1622 // Build bool mask concatenation, bitcast back to scalar integer, and perform
1623 // any residual zero-extension or shifting.
1624 Value *Concat = Builder.CreateShuffleVector(SrcX, SrcY, ConcatMask);
1625 Worklist.pushValue(Concat);
1626
1627 Value *Result = Builder.CreateBitCast(Concat, ConcatIntTy);
1628
1629 if (Ty != ConcatIntTy) {
1630 Worklist.pushValue(Result);
1631 Result = Builder.CreateZExt(Result, Ty);
1632 }
1633
1634 if (ShAmtX > 0) {
1635 Worklist.pushValue(Result);
1636 Result = Builder.CreateShl(Result, ShAmtX);
1637 }
1638
1639 replaceValue(I, *Result);
1640 return true;
1641}
1642
1643/// Try to convert "shuffle (binop (shuffle, shuffle)), undef"
1644/// --> "binop (shuffle), (shuffle)".
1645bool VectorCombine::foldPermuteOfBinops(Instruction &I) {
1646 BinaryOperator *BinOp;
1647 ArrayRef<int> OuterMask;
1648 if (!match(&I,
1649 m_Shuffle(m_OneUse(m_BinOp(BinOp)), m_Undef(), m_Mask(OuterMask))))
1650 return false;
1651
1652 // Don't introduce poison into div/rem.
1653 if (BinOp->isIntDivRem() && llvm::is_contained(OuterMask, PoisonMaskElem))
1654 return false;
1655
1656 Value *Op00, *Op01, *Op10, *Op11;
1657 ArrayRef<int> Mask0, Mask1;
1658 bool Match0 =
1659 match(BinOp->getOperand(0),
1660 m_OneUse(m_Shuffle(m_Value(Op00), m_Value(Op01), m_Mask(Mask0))));
1661 bool Match1 =
1662 match(BinOp->getOperand(1),
1663 m_OneUse(m_Shuffle(m_Value(Op10), m_Value(Op11), m_Mask(Mask1))));
1664 if (!Match0 && !Match1)
1665 return false;
1666
1667 Op00 = Match0 ? Op00 : BinOp->getOperand(0);
1668 Op01 = Match0 ? Op01 : BinOp->getOperand(0);
1669 Op10 = Match1 ? Op10 : BinOp->getOperand(1);
1670 Op11 = Match1 ? Op11 : BinOp->getOperand(1);
1671
1672 Instruction::BinaryOps Opcode = BinOp->getOpcode();
1673 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
1674 auto *BinOpTy = dyn_cast<FixedVectorType>(BinOp->getType());
1675 auto *Op0Ty = dyn_cast<FixedVectorType>(Op00->getType());
1676 auto *Op1Ty = dyn_cast<FixedVectorType>(Op10->getType());
1677 if (!ShuffleDstTy || !BinOpTy || !Op0Ty || !Op1Ty)
1678 return false;
1679
1680 unsigned NumSrcElts = BinOpTy->getNumElements();
1681
1682 // Don't accept shuffles that reference the second operand in
1683 // div/rem or if its an undef arg.
1684 if ((BinOp->isIntDivRem() || !isa<PoisonValue>(I.getOperand(1))) &&
1685 any_of(OuterMask, [NumSrcElts](int M) { return M >= (int)NumSrcElts; }))
1686 return false;
1687
1688 // Merge outer / inner (or identity if no match) shuffles.
1689 SmallVector<int> NewMask0, NewMask1;
1690 for (int M : OuterMask) {
1691 if (M < 0 || M >= (int)NumSrcElts) {
1692 NewMask0.push_back(PoisonMaskElem);
1693 NewMask1.push_back(PoisonMaskElem);
1694 } else {
1695 NewMask0.push_back(Match0 ? Mask0[M] : M);
1696 NewMask1.push_back(Match1 ? Mask1[M] : M);
1697 }
1698 }
1699
1700 unsigned NumOpElts = Op0Ty->getNumElements();
1701 bool IsIdentity0 = ShuffleDstTy == Op0Ty &&
1702 all_of(NewMask0, [NumOpElts](int M) { return M < (int)NumOpElts; }) &&
1703 ShuffleVectorInst::isIdentityMask(NewMask0, NumOpElts);
1704 bool IsIdentity1 = ShuffleDstTy == Op1Ty &&
1705 all_of(NewMask1, [NumOpElts](int M) { return M < (int)NumOpElts; }) &&
1706 ShuffleVectorInst::isIdentityMask(NewMask1, NumOpElts);
1707
1708 // Try to merge shuffles across the binop if the new shuffles are not costly.
1709 InstructionCost OldCost =
1710 TTI.getArithmeticInstrCost(Opcode, BinOpTy, CostKind) +
1712 OuterMask, CostKind, 0, nullptr, {BinOp}, &I);
1713 if (Match0)
1715 Mask0, CostKind, 0, nullptr, {Op00, Op01},
1716 cast<Instruction>(BinOp->getOperand(0)));
1717 if (Match1)
1719 Mask1, CostKind, 0, nullptr, {Op10, Op11},
1720 cast<Instruction>(BinOp->getOperand(1)));
1721
1722 InstructionCost NewCost =
1723 TTI.getArithmeticInstrCost(Opcode, ShuffleDstTy, CostKind);
1724
1725 if (!IsIdentity0)
1727 NewMask0, CostKind, 0, nullptr, {Op00, Op01});
1728 if (!IsIdentity1)
1730 NewMask1, CostKind, 0, nullptr, {Op10, Op11});
1731
1732 LLVM_DEBUG(dbgs() << "Found a shuffle feeding a shuffled binop: " << I
1733 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
1734 << "\n");
1735
1736 // If costs are equal, still fold as we reduce instruction count.
1737 if (NewCost > OldCost)
1738 return false;
1739
1740 Value *LHS =
1741 IsIdentity0 ? Op00 : Builder.CreateShuffleVector(Op00, Op01, NewMask0);
1742 Value *RHS =
1743 IsIdentity1 ? Op10 : Builder.CreateShuffleVector(Op10, Op11, NewMask1);
1744 Value *NewBO = Builder.CreateBinOp(Opcode, LHS, RHS);
1745
1746 // Intersect flags from the old binops.
1747 if (auto *NewInst = dyn_cast<Instruction>(NewBO))
1748 NewInst->copyIRFlags(BinOp);
1749
1750 Worklist.pushValue(LHS);
1751 Worklist.pushValue(RHS);
1752 replaceValue(I, *NewBO);
1753 return true;
1754}
1755
1756/// Try to convert "shuffle (binop), (binop)" into "binop (shuffle), (shuffle)".
1757/// Try to convert "shuffle (cmpop), (cmpop)" into "cmpop (shuffle), (shuffle)".
1758bool VectorCombine::foldShuffleOfBinops(Instruction &I) {
1759 ArrayRef<int> OldMask;
1760 Instruction *LHS, *RHS;
1761 if (!match(&I, m_Shuffle(m_OneUse(m_Instruction(LHS)),
1762 m_OneUse(m_Instruction(RHS)), m_Mask(OldMask))))
1763 return false;
1764
1765 // TODO: Add support for addlike etc.
1766 if (LHS->getOpcode() != RHS->getOpcode())
1767 return false;
1768
1769 Value *X, *Y, *Z, *W;
1770 bool IsCommutative = false;
1773 if (match(LHS, m_BinOp(m_Value(X), m_Value(Y))) &&
1774 match(RHS, m_BinOp(m_Value(Z), m_Value(W)))) {
1775 auto *BO = cast<BinaryOperator>(LHS);
1776 // Don't introduce poison into div/rem.
1777 if (llvm::is_contained(OldMask, PoisonMaskElem) && BO->isIntDivRem())
1778 return false;
1779 IsCommutative = BinaryOperator::isCommutative(BO->getOpcode());
1780 } else if (match(LHS, m_Cmp(PredLHS, m_Value(X), m_Value(Y))) &&
1781 match(RHS, m_Cmp(PredRHS, m_Value(Z), m_Value(W))) &&
1782 (CmpInst::Predicate)PredLHS == (CmpInst::Predicate)PredRHS) {
1783 IsCommutative = cast<CmpInst>(LHS)->isCommutative();
1784 } else
1785 return false;
1786
1787 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
1788 auto *BinResTy = dyn_cast<FixedVectorType>(LHS->getType());
1789 auto *BinOpTy = dyn_cast<FixedVectorType>(X->getType());
1790 if (!ShuffleDstTy || !BinResTy || !BinOpTy || X->getType() != Z->getType())
1791 return false;
1792
1793 unsigned NumSrcElts = BinOpTy->getNumElements();
1794
1795 // If we have something like "add X, Y" and "add Z, X", swap ops to match.
1796 if (IsCommutative && X != Z && Y != W && (X == W || Y == Z))
1797 std::swap(X, Y);
1798
1799 auto ConvertToUnary = [NumSrcElts](int &M) {
1800 if (M >= (int)NumSrcElts)
1801 M -= NumSrcElts;
1802 };
1803
1804 SmallVector<int> NewMask0(OldMask);
1806 if (X == Z) {
1807 llvm::for_each(NewMask0, ConvertToUnary);
1809 Z = PoisonValue::get(BinOpTy);
1810 }
1811
1812 SmallVector<int> NewMask1(OldMask);
1814 if (Y == W) {
1815 llvm::for_each(NewMask1, ConvertToUnary);
1817 W = PoisonValue::get(BinOpTy);
1818 }
1819
1820 // Try to replace a binop with a shuffle if the shuffle is not costly.
1821 InstructionCost OldCost =
1825 OldMask, CostKind, 0, nullptr, {LHS, RHS}, &I);
1826
1827 // Handle shuffle(binop(shuffle(x),y),binop(z,shuffle(w))) style patterns
1828 // where one use shuffles have gotten split across the binop/cmp. These
1829 // often allow a major reduction in total cost that wouldn't happen as
1830 // individual folds.
1831 auto MergeInner = [&](Value *&Op, int Offset, MutableArrayRef<int> Mask,
1832 TTI::TargetCostKind CostKind) -> bool {
1833 Value *InnerOp;
1834 ArrayRef<int> InnerMask;
1835 if (match(Op, m_OneUse(m_Shuffle(m_Value(InnerOp), m_Undef(),
1836 m_Mask(InnerMask)))) &&
1837 InnerOp->getType() == Op->getType() &&
1838 all_of(InnerMask,
1839 [NumSrcElts](int M) { return M < (int)NumSrcElts; })) {
1840 for (int &M : Mask)
1841 if (Offset <= M && M < (int)(Offset + NumSrcElts)) {
1842 M = InnerMask[M - Offset];
1843 M = 0 <= M ? M + Offset : M;
1844 }
1845 OldCost += TTI.getInstructionCost(cast<Instruction>(Op), CostKind);
1846 Op = InnerOp;
1847 return true;
1848 }
1849 return false;
1850 };
1851 bool ReducedInstCount = false;
1852 ReducedInstCount |= MergeInner(X, 0, NewMask0, CostKind);
1853 ReducedInstCount |= MergeInner(Y, 0, NewMask1, CostKind);
1854 ReducedInstCount |= MergeInner(Z, NumSrcElts, NewMask0, CostKind);
1855 ReducedInstCount |= MergeInner(W, NumSrcElts, NewMask1, CostKind);
1856
1857 InstructionCost NewCost =
1858 TTI.getShuffleCost(SK0, BinOpTy, NewMask0, CostKind, 0, nullptr, {X, Z}) +
1859 TTI.getShuffleCost(SK1, BinOpTy, NewMask1, CostKind, 0, nullptr, {Y, W});
1860
1861 if (PredLHS == CmpInst::BAD_ICMP_PREDICATE) {
1862 NewCost +=
1863 TTI.getArithmeticInstrCost(LHS->getOpcode(), ShuffleDstTy, CostKind);
1864 } else {
1865 auto *ShuffleCmpTy =
1866 FixedVectorType::get(BinOpTy->getElementType(), ShuffleDstTy);
1867 NewCost += TTI.getCmpSelInstrCost(LHS->getOpcode(), ShuffleCmpTy,
1868 ShuffleDstTy, PredLHS, CostKind);
1869 }
1870
1871 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two binops: " << I
1872 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
1873 << "\n");
1874
1875 // If either shuffle will constant fold away, then fold for the same cost as
1876 // we will reduce the instruction count.
1877 ReducedInstCount |= (isa<Constant>(X) && isa<Constant>(Z)) ||
1878 (isa<Constant>(Y) && isa<Constant>(W));
1879 if (ReducedInstCount ? (NewCost > OldCost) : (NewCost >= OldCost))
1880 return false;
1881
1882 Value *Shuf0 = Builder.CreateShuffleVector(X, Z, NewMask0);
1883 Value *Shuf1 = Builder.CreateShuffleVector(Y, W, NewMask1);
1884 Value *NewBO = PredLHS == CmpInst::BAD_ICMP_PREDICATE
1885 ? Builder.CreateBinOp(
1886 cast<BinaryOperator>(LHS)->getOpcode(), Shuf0, Shuf1)
1887 : Builder.CreateCmp(PredLHS, Shuf0, Shuf1);
1888
1889 // Intersect flags from the old binops.
1890 if (auto *NewInst = dyn_cast<Instruction>(NewBO)) {
1891 NewInst->copyIRFlags(LHS);
1892 NewInst->andIRFlags(RHS);
1893 }
1894
1895 Worklist.pushValue(Shuf0);
1896 Worklist.pushValue(Shuf1);
1897 replaceValue(I, *NewBO);
1898 return true;
1899}
1900
1901/// Try to convert "shuffle (castop), (castop)" with a shared castop operand
1902/// into "castop (shuffle)".
1903bool VectorCombine::foldShuffleOfCastops(Instruction &I) {
1904 Value *V0, *V1;
1905 ArrayRef<int> OldMask;
1906 if (!match(&I, m_Shuffle(m_Value(V0), m_Value(V1), m_Mask(OldMask))))
1907 return false;
1908
1909 auto *C0 = dyn_cast<CastInst>(V0);
1910 auto *C1 = dyn_cast<CastInst>(V1);
1911 if (!C0 || !C1)
1912 return false;
1913
1914 Instruction::CastOps Opcode = C0->getOpcode();
1915 if (C0->getSrcTy() != C1->getSrcTy())
1916 return false;
1917
1918 // Handle shuffle(zext_nneg(x), sext(y)) -> sext(shuffle(x,y)) folds.
1919 if (Opcode != C1->getOpcode()) {
1920 if (match(C0, m_SExtLike(m_Value())) && match(C1, m_SExtLike(m_Value())))
1921 Opcode = Instruction::SExt;
1922 else
1923 return false;
1924 }
1925
1926 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
1927 auto *CastDstTy = dyn_cast<FixedVectorType>(C0->getDestTy());
1928 auto *CastSrcTy = dyn_cast<FixedVectorType>(C0->getSrcTy());
1929 if (!ShuffleDstTy || !CastDstTy || !CastSrcTy)
1930 return false;
1931
1932 unsigned NumSrcElts = CastSrcTy->getNumElements();
1933 unsigned NumDstElts = CastDstTy->getNumElements();
1934 assert((NumDstElts == NumSrcElts || Opcode == Instruction::BitCast) &&
1935 "Only bitcasts expected to alter src/dst element counts");
1936
1937 // Check for bitcasting of unscalable vector types.
1938 // e.g. <32 x i40> -> <40 x i32>
1939 if (NumDstElts != NumSrcElts && (NumSrcElts % NumDstElts) != 0 &&
1940 (NumDstElts % NumSrcElts) != 0)
1941 return false;
1942
1943 SmallVector<int, 16> NewMask;
1944 if (NumSrcElts >= NumDstElts) {
1945 // The bitcast is from wide to narrow/equal elements. The shuffle mask can
1946 // always be expanded to the equivalent form choosing narrower elements.
1947 assert(NumSrcElts % NumDstElts == 0 && "Unexpected shuffle mask");
1948 unsigned ScaleFactor = NumSrcElts / NumDstElts;
1949 narrowShuffleMaskElts(ScaleFactor, OldMask, NewMask);
1950 } else {
1951 // The bitcast is from narrow elements to wide elements. The shuffle mask
1952 // must choose consecutive elements to allow casting first.
1953 assert(NumDstElts % NumSrcElts == 0 && "Unexpected shuffle mask");
1954 unsigned ScaleFactor = NumDstElts / NumSrcElts;
1955 if (!widenShuffleMaskElts(ScaleFactor, OldMask, NewMask))
1956 return false;
1957 }
1958
1959 auto *NewShuffleDstTy =
1960 FixedVectorType::get(CastSrcTy->getScalarType(), NewMask.size());
1961
1962 // Try to replace a castop with a shuffle if the shuffle is not costly.
1963 InstructionCost CostC0 =
1964 TTI.getCastInstrCost(C0->getOpcode(), CastDstTy, CastSrcTy,
1966 InstructionCost CostC1 =
1967 TTI.getCastInstrCost(C1->getOpcode(), CastDstTy, CastSrcTy,
1969 InstructionCost OldCost = CostC0 + CostC1;
1970 OldCost +=
1972 OldMask, CostKind, 0, nullptr, {}, &I);
1973
1975 TargetTransformInfo::SK_PermuteTwoSrc, CastSrcTy, NewMask, CostKind);
1976 NewCost += TTI.getCastInstrCost(Opcode, ShuffleDstTy, NewShuffleDstTy,
1978 if (!C0->hasOneUse())
1979 NewCost += CostC0;
1980 if (!C1->hasOneUse())
1981 NewCost += CostC1;
1982
1983 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two casts: " << I
1984 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
1985 << "\n");
1986 if (NewCost > OldCost)
1987 return false;
1988
1989 Value *Shuf = Builder.CreateShuffleVector(C0->getOperand(0),
1990 C1->getOperand(0), NewMask);
1991 Value *Cast = Builder.CreateCast(Opcode, Shuf, ShuffleDstTy);
1992
1993 // Intersect flags from the old casts.
1994 if (auto *NewInst = dyn_cast<Instruction>(Cast)) {
1995 NewInst->copyIRFlags(C0);
1996 NewInst->andIRFlags(C1);
1997 }
1998
1999 Worklist.pushValue(Shuf);
2000 replaceValue(I, *Cast);
2001 return true;
2002}
2003
2004/// Try to convert any of:
2005/// "shuffle (shuffle x, y), (shuffle y, x)"
2006/// "shuffle (shuffle x, undef), (shuffle y, undef)"
2007/// "shuffle (shuffle x, undef), y"
2008/// "shuffle x, (shuffle y, undef)"
2009/// into "shuffle x, y".
2010bool VectorCombine::foldShuffleOfShuffles(Instruction &I) {
2011 ArrayRef<int> OuterMask;
2012 Value *OuterV0, *OuterV1;
2013 if (!match(&I,
2014 m_Shuffle(m_Value(OuterV0), m_Value(OuterV1), m_Mask(OuterMask))))
2015 return false;
2016
2017 ArrayRef<int> InnerMask0, InnerMask1;
2018 Value *X0, *X1, *Y0, *Y1;
2019 bool Match0 =
2020 match(OuterV0, m_Shuffle(m_Value(X0), m_Value(Y0), m_Mask(InnerMask0)));
2021 bool Match1 =
2022 match(OuterV1, m_Shuffle(m_Value(X1), m_Value(Y1), m_Mask(InnerMask1)));
2023 if (!Match0 && !Match1)
2024 return false;
2025
2026 X0 = Match0 ? X0 : OuterV0;
2027 Y0 = Match0 ? Y0 : OuterV0;
2028 X1 = Match1 ? X1 : OuterV1;
2029 Y1 = Match1 ? Y1 : OuterV1;
2030 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
2031 auto *ShuffleSrcTy = dyn_cast<FixedVectorType>(X0->getType());
2032 auto *ShuffleImmTy = dyn_cast<FixedVectorType>(OuterV0->getType());
2033 if (!ShuffleDstTy || !ShuffleSrcTy || !ShuffleImmTy ||
2034 X0->getType() != X1->getType())
2035 return false;
2036
2037 unsigned NumSrcElts = ShuffleSrcTy->getNumElements();
2038 unsigned NumImmElts = ShuffleImmTy->getNumElements();
2039
2040 // Attempt to merge shuffles, matching upto 2 source operands.
2041 // Replace index to a poison arg with PoisonMaskElem.
2042 // Bail if either inner masks reference an undef arg.
2043 SmallVector<int, 16> NewMask(OuterMask);
2044 Value *NewX = nullptr, *NewY = nullptr;
2045 for (int &M : NewMask) {
2046 Value *Src = nullptr;
2047 if (0 <= M && M < (int)NumImmElts) {
2048 Src = OuterV0;
2049 if (Match0) {
2050 M = InnerMask0[M];
2051 Src = M >= (int)NumSrcElts ? Y0 : X0;
2052 M = M >= (int)NumSrcElts ? (M - NumSrcElts) : M;
2053 }
2054 } else if (M >= (int)NumImmElts) {
2055 Src = OuterV1;
2056 M -= NumImmElts;
2057 if (Match1) {
2058 M = InnerMask1[M];
2059 Src = M >= (int)NumSrcElts ? Y1 : X1;
2060 M = M >= (int)NumSrcElts ? (M - NumSrcElts) : M;
2061 }
2062 }
2063 if (Src && M != PoisonMaskElem) {
2064 assert(0 <= M && M < (int)NumSrcElts && "Unexpected shuffle mask index");
2065 if (isa<UndefValue>(Src)) {
2066 // We've referenced an undef element - if its poison, update the shuffle
2067 // mask, else bail.
2068 if (!isa<PoisonValue>(Src))
2069 return false;
2070 M = PoisonMaskElem;
2071 continue;
2072 }
2073 if (!NewX || NewX == Src) {
2074 NewX = Src;
2075 continue;
2076 }
2077 if (!NewY || NewY == Src) {
2078 M += NumSrcElts;
2079 NewY = Src;
2080 continue;
2081 }
2082 return false;
2083 }
2084 }
2085
2086 if (!NewX)
2087 return PoisonValue::get(ShuffleDstTy);
2088 if (!NewY)
2089 NewY = PoisonValue::get(ShuffleSrcTy);
2090
2091 // Have we folded to an Identity shuffle?
2092 if (ShuffleVectorInst::isIdentityMask(NewMask, NumSrcElts)) {
2093 replaceValue(I, *NewX);
2094 return true;
2095 }
2096
2097 // Try to merge the shuffles if the new shuffle is not costly.
2098 InstructionCost InnerCost0 = 0;
2099 if (Match0)
2100 InnerCost0 = TTI.getInstructionCost(cast<Instruction>(OuterV0), CostKind);
2101
2102 InstructionCost InnerCost1 = 0;
2103 if (Match1)
2104 InnerCost1 = TTI.getInstructionCost(cast<Instruction>(OuterV1), CostKind);
2105
2107
2108 InstructionCost OldCost = InnerCost0 + InnerCost1 + OuterCost;
2109
2110 bool IsUnary = all_of(NewMask, [&](int M) { return M < (int)NumSrcElts; });
2115 SK, ShuffleSrcTy, NewMask, CostKind, 0, nullptr, {NewX, NewY});
2116 if (!OuterV0->hasOneUse())
2117 NewCost += InnerCost0;
2118 if (!OuterV1->hasOneUse())
2119 NewCost += InnerCost1;
2120
2121 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two shuffles: " << I
2122 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
2123 << "\n");
2124 if (NewCost > OldCost)
2125 return false;
2126
2127 Value *Shuf = Builder.CreateShuffleVector(NewX, NewY, NewMask);
2128 replaceValue(I, *Shuf);
2129 return true;
2130}
2131
2132/// Try to convert
2133/// "shuffle (intrinsic), (intrinsic)" into "intrinsic (shuffle), (shuffle)".
2134bool VectorCombine::foldShuffleOfIntrinsics(Instruction &I) {
2135 Value *V0, *V1;
2136 ArrayRef<int> OldMask;
2137 if (!match(&I, m_Shuffle(m_OneUse(m_Value(V0)), m_OneUse(m_Value(V1)),
2138 m_Mask(OldMask))))
2139 return false;
2140
2141 auto *II0 = dyn_cast<IntrinsicInst>(V0);
2142 auto *II1 = dyn_cast<IntrinsicInst>(V1);
2143 if (!II0 || !II1)
2144 return false;
2145
2146 Intrinsic::ID IID = II0->getIntrinsicID();
2147 if (IID != II1->getIntrinsicID())
2148 return false;
2149
2150 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
2151 auto *II0Ty = dyn_cast<FixedVectorType>(II0->getType());
2152 if (!ShuffleDstTy || !II0Ty)
2153 return false;
2154
2155 if (!isTriviallyVectorizable(IID))
2156 return false;
2157
2158 for (unsigned I = 0, E = II0->arg_size(); I != E; ++I)
2160 II0->getArgOperand(I) != II1->getArgOperand(I))
2161 return false;
2162
2163 InstructionCost OldCost =
2167 CostKind, 0, nullptr, {II0, II1}, &I);
2168
2169 SmallVector<Type *> NewArgsTy;
2170 InstructionCost NewCost = 0;
2171 for (unsigned I = 0, E = II0->arg_size(); I != E; ++I)
2173 NewArgsTy.push_back(II0->getArgOperand(I)->getType());
2174 } else {
2175 auto *VecTy = cast<FixedVectorType>(II0->getArgOperand(I)->getType());
2176 NewArgsTy.push_back(FixedVectorType::get(VecTy->getElementType(),
2177 VecTy->getNumElements() * 2));
2179 VecTy, OldMask, CostKind);
2180 }
2181 IntrinsicCostAttributes NewAttr(IID, ShuffleDstTy, NewArgsTy);
2182 NewCost += TTI.getIntrinsicInstrCost(NewAttr, CostKind);
2183
2184 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two intrinsics: " << I
2185 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
2186 << "\n");
2187
2188 if (NewCost > OldCost)
2189 return false;
2190
2191 SmallVector<Value *> NewArgs;
2192 for (unsigned I = 0, E = II0->arg_size(); I != E; ++I)
2194 NewArgs.push_back(II0->getArgOperand(I));
2195 } else {
2196 Value *Shuf = Builder.CreateShuffleVector(II0->getArgOperand(I),
2197 II1->getArgOperand(I), OldMask);
2198 NewArgs.push_back(Shuf);
2199 Worklist.pushValue(Shuf);
2200 }
2201 Value *NewIntrinsic = Builder.CreateIntrinsic(ShuffleDstTy, IID, NewArgs);
2202
2203 // Intersect flags from the old intrinsics.
2204 if (auto *NewInst = dyn_cast<Instruction>(NewIntrinsic)) {
2205 NewInst->copyIRFlags(II0);
2206 NewInst->andIRFlags(II1);
2207 }
2208
2209 replaceValue(I, *NewIntrinsic);
2210 return true;
2211}
2212
2213using InstLane = std::pair<Use *, int>;
2214
2215static InstLane lookThroughShuffles(Use *U, int Lane) {
2216 while (auto *SV = dyn_cast<ShuffleVectorInst>(U->get())) {
2217 unsigned NumElts =
2218 cast<FixedVectorType>(SV->getOperand(0)->getType())->getNumElements();
2219 int M = SV->getMaskValue(Lane);
2220 if (M < 0)
2221 return {nullptr, PoisonMaskElem};
2222 if (static_cast<unsigned>(M) < NumElts) {
2223 U = &SV->getOperandUse(0);
2224 Lane = M;
2225 } else {
2226 U = &SV->getOperandUse(1);
2227 Lane = M - NumElts;
2228 }
2229 }
2230 return InstLane{U, Lane};
2231}
2232
2236 for (InstLane IL : Item) {
2237 auto [U, Lane] = IL;
2238 InstLane OpLane =
2239 U ? lookThroughShuffles(&cast<Instruction>(U->get())->getOperandUse(Op),
2240 Lane)
2241 : InstLane{nullptr, PoisonMaskElem};
2242 NItem.emplace_back(OpLane);
2243 }
2244 return NItem;
2245}
2246
2247/// Detect concat of multiple values into a vector
2249 const TargetTransformInfo &TTI) {
2250 auto *Ty = cast<FixedVectorType>(Item.front().first->get()->getType());
2251 unsigned NumElts = Ty->getNumElements();
2252 if (Item.size() == NumElts || NumElts == 1 || Item.size() % NumElts != 0)
2253 return false;
2254
2255 // Check that the concat is free, usually meaning that the type will be split
2256 // during legalization.
2257 SmallVector<int, 16> ConcatMask(NumElts * 2);
2258 std::iota(ConcatMask.begin(), ConcatMask.end(), 0);
2259 if (TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, Ty, ConcatMask, CostKind) != 0)
2260 return false;
2261
2262 unsigned NumSlices = Item.size() / NumElts;
2263 // Currently we generate a tree of shuffles for the concats, which limits us
2264 // to a power2.
2265 if (!isPowerOf2_32(NumSlices))
2266 return false;
2267 for (unsigned Slice = 0; Slice < NumSlices; ++Slice) {
2268 Use *SliceV = Item[Slice * NumElts].first;
2269 if (!SliceV || SliceV->get()->getType() != Ty)
2270 return false;
2271 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
2272 auto [V, Lane] = Item[Slice * NumElts + Elt];
2273 if (Lane != static_cast<int>(Elt) || SliceV->get() != V->get())
2274 return false;
2275 }
2276 }
2277 return true;
2278}
2279
2281 const SmallPtrSet<Use *, 4> &IdentityLeafs,
2282 const SmallPtrSet<Use *, 4> &SplatLeafs,
2283 const SmallPtrSet<Use *, 4> &ConcatLeafs,
2284 IRBuilder<> &Builder,
2285 const TargetTransformInfo *TTI) {
2286 auto [FrontU, FrontLane] = Item.front();
2287
2288 if (IdentityLeafs.contains(FrontU)) {
2289 return FrontU->get();
2290 }
2291 if (SplatLeafs.contains(FrontU)) {
2292 SmallVector<int, 16> Mask(Ty->getNumElements(), FrontLane);
2293 return Builder.CreateShuffleVector(FrontU->get(), Mask);
2294 }
2295 if (ConcatLeafs.contains(FrontU)) {
2296 unsigned NumElts =
2297 cast<FixedVectorType>(FrontU->get()->getType())->getNumElements();
2298 SmallVector<Value *> Values(Item.size() / NumElts, nullptr);
2299 for (unsigned S = 0; S < Values.size(); ++S)
2300 Values[S] = Item[S * NumElts].first->get();
2301
2302 while (Values.size() > 1) {
2303 NumElts *= 2;
2304 SmallVector<int, 16> Mask(NumElts, 0);
2305 std::iota(Mask.begin(), Mask.end(), 0);
2306 SmallVector<Value *> NewValues(Values.size() / 2, nullptr);
2307 for (unsigned S = 0; S < NewValues.size(); ++S)
2308 NewValues[S] =
2309 Builder.CreateShuffleVector(Values[S * 2], Values[S * 2 + 1], Mask);
2310 Values = NewValues;
2311 }
2312 return Values[0];
2313 }
2314
2315 auto *I = cast<Instruction>(FrontU->get());
2316 auto *II = dyn_cast<IntrinsicInst>(I);
2317 unsigned NumOps = I->getNumOperands() - (II ? 1 : 0);
2318 SmallVector<Value *> Ops(NumOps);
2319 for (unsigned Idx = 0; Idx < NumOps; Idx++) {
2320 if (II &&
2321 isVectorIntrinsicWithScalarOpAtArg(II->getIntrinsicID(), Idx, TTI)) {
2322 Ops[Idx] = II->getOperand(Idx);
2323 continue;
2324 }
2326 Ty, IdentityLeafs, SplatLeafs, ConcatLeafs,
2327 Builder, TTI);
2328 }
2329
2330 SmallVector<Value *, 8> ValueList;
2331 for (const auto &Lane : Item)
2332 if (Lane.first)
2333 ValueList.push_back(Lane.first->get());
2334
2335 Type *DstTy =
2336 FixedVectorType::get(I->getType()->getScalarType(), Ty->getNumElements());
2337 if (auto *BI = dyn_cast<BinaryOperator>(I)) {
2338 auto *Value = Builder.CreateBinOp((Instruction::BinaryOps)BI->getOpcode(),
2339 Ops[0], Ops[1]);
2340 propagateIRFlags(Value, ValueList);
2341 return Value;
2342 }
2343 if (auto *CI = dyn_cast<CmpInst>(I)) {
2344 auto *Value = Builder.CreateCmp(CI->getPredicate(), Ops[0], Ops[1]);
2345 propagateIRFlags(Value, ValueList);
2346 return Value;
2347 }
2348 if (auto *SI = dyn_cast<SelectInst>(I)) {
2349 auto *Value = Builder.CreateSelect(Ops[0], Ops[1], Ops[2], "", SI);
2350 propagateIRFlags(Value, ValueList);
2351 return Value;
2352 }
2353 if (auto *CI = dyn_cast<CastInst>(I)) {
2354 auto *Value = Builder.CreateCast((Instruction::CastOps)CI->getOpcode(),
2355 Ops[0], DstTy);
2356 propagateIRFlags(Value, ValueList);
2357 return Value;
2358 }
2359 if (II) {
2360 auto *Value = Builder.CreateIntrinsic(DstTy, II->getIntrinsicID(), Ops);
2361 propagateIRFlags(Value, ValueList);
2362 return Value;
2363 }
2364 assert(isa<UnaryInstruction>(I) && "Unexpected instruction type in Generate");
2365 auto *Value =
2366 Builder.CreateUnOp((Instruction::UnaryOps)I->getOpcode(), Ops[0]);
2367 propagateIRFlags(Value, ValueList);
2368 return Value;
2369}
2370
2371// Starting from a shuffle, look up through operands tracking the shuffled index
2372// of each lane. If we can simplify away the shuffles to identities then
2373// do so.
2374bool VectorCombine::foldShuffleToIdentity(Instruction &I) {
2375 auto *Ty = dyn_cast<FixedVectorType>(I.getType());
2376 if (!Ty || I.use_empty())
2377 return false;
2378
2379 SmallVector<InstLane> Start(Ty->getNumElements());
2380 for (unsigned M = 0, E = Ty->getNumElements(); M < E; ++M)
2381 Start[M] = lookThroughShuffles(&*I.use_begin(), M);
2382
2384 Worklist.push_back(Start);
2385 SmallPtrSet<Use *, 4> IdentityLeafs, SplatLeafs, ConcatLeafs;
2386 unsigned NumVisited = 0;
2387
2388 while (!Worklist.empty()) {
2389 if (++NumVisited > MaxInstrsToScan)
2390 return false;
2391
2392 SmallVector<InstLane> Item = Worklist.pop_back_val();
2393 auto [FrontU, FrontLane] = Item.front();
2394
2395 // If we found an undef first lane then bail out to keep things simple.
2396 if (!FrontU)
2397 return false;
2398
2399 // Helper to peek through bitcasts to the same value.
2400 auto IsEquiv = [&](Value *X, Value *Y) {
2401 return X->getType() == Y->getType() &&
2403 };
2404
2405 // Look for an identity value.
2406 if (FrontLane == 0 &&
2407 cast<FixedVectorType>(FrontU->get()->getType())->getNumElements() ==
2408 Ty->getNumElements() &&
2409 all_of(drop_begin(enumerate(Item)), [IsEquiv, Item](const auto &E) {
2410 Value *FrontV = Item.front().first->get();
2411 return !E.value().first || (IsEquiv(E.value().first->get(), FrontV) &&
2412 E.value().second == (int)E.index());
2413 })) {
2414 IdentityLeafs.insert(FrontU);
2415 continue;
2416 }
2417 // Look for constants, for the moment only supporting constant splats.
2418 if (auto *C = dyn_cast<Constant>(FrontU);
2419 C && C->getSplatValue() &&
2420 all_of(drop_begin(Item), [Item](InstLane &IL) {
2421 Value *FrontV = Item.front().first->get();
2422 Use *U = IL.first;
2423 return !U || (isa<Constant>(U->get()) &&
2424 cast<Constant>(U->get())->getSplatValue() ==
2425 cast<Constant>(FrontV)->getSplatValue());
2426 })) {
2427 SplatLeafs.insert(FrontU);
2428 continue;
2429 }
2430 // Look for a splat value.
2431 if (all_of(drop_begin(Item), [Item](InstLane &IL) {
2432 auto [FrontU, FrontLane] = Item.front();
2433 auto [U, Lane] = IL;
2434 return !U || (U->get() == FrontU->get() && Lane == FrontLane);
2435 })) {
2436 SplatLeafs.insert(FrontU);
2437 continue;
2438 }
2439
2440 // We need each element to be the same type of value, and check that each
2441 // element has a single use.
2442 auto CheckLaneIsEquivalentToFirst = [Item](InstLane IL) {
2443 Value *FrontV = Item.front().first->get();
2444 if (!IL.first)
2445 return true;
2446 Value *V = IL.first->get();
2447 if (auto *I = dyn_cast<Instruction>(V); I && !I->hasOneUse())
2448 return false;
2449 if (V->getValueID() != FrontV->getValueID())
2450 return false;
2451 if (auto *CI = dyn_cast<CmpInst>(V))
2452 if (CI->getPredicate() != cast<CmpInst>(FrontV)->getPredicate())
2453 return false;
2454 if (auto *CI = dyn_cast<CastInst>(V))
2455 if (CI->getSrcTy()->getScalarType() !=
2456 cast<CastInst>(FrontV)->getSrcTy()->getScalarType())
2457 return false;
2458 if (auto *SI = dyn_cast<SelectInst>(V))
2459 if (!isa<VectorType>(SI->getOperand(0)->getType()) ||
2460 SI->getOperand(0)->getType() !=
2461 cast<SelectInst>(FrontV)->getOperand(0)->getType())
2462 return false;
2463 if (isa<CallInst>(V) && !isa<IntrinsicInst>(V))
2464 return false;
2465 auto *II = dyn_cast<IntrinsicInst>(V);
2466 return !II || (isa<IntrinsicInst>(FrontV) &&
2467 II->getIntrinsicID() ==
2468 cast<IntrinsicInst>(FrontV)->getIntrinsicID() &&
2469 !II->hasOperandBundles());
2470 };
2471 if (all_of(drop_begin(Item), CheckLaneIsEquivalentToFirst)) {
2472 // Check the operator is one that we support.
2473 if (isa<BinaryOperator, CmpInst>(FrontU)) {
2474 // We exclude div/rem in case they hit UB from poison lanes.
2475 if (auto *BO = dyn_cast<BinaryOperator>(FrontU);
2476 BO && BO->isIntDivRem())
2477 return false;
2480 continue;
2482 FPToUIInst, SIToFPInst, UIToFPInst>(FrontU)) {
2484 continue;
2485 } else if (auto *BitCast = dyn_cast<BitCastInst>(FrontU)) {
2486 // TODO: Handle vector widening/narrowing bitcasts.
2487 auto *DstTy = dyn_cast<FixedVectorType>(BitCast->getDestTy());
2488 auto *SrcTy = dyn_cast<FixedVectorType>(BitCast->getSrcTy());
2489 if (DstTy && SrcTy &&
2490 SrcTy->getNumElements() == DstTy->getNumElements()) {
2492 continue;
2493 }
2494 } else if (isa<SelectInst>(FrontU)) {
2498 continue;
2499 } else if (auto *II = dyn_cast<IntrinsicInst>(FrontU);
2500 II && isTriviallyVectorizable(II->getIntrinsicID()) &&
2501 !II->hasOperandBundles()) {
2502 for (unsigned Op = 0, E = II->getNumOperands() - 1; Op < E; Op++) {
2503 if (isVectorIntrinsicWithScalarOpAtArg(II->getIntrinsicID(), Op,
2504 &TTI)) {
2505 if (!all_of(drop_begin(Item), [Item, Op](InstLane &IL) {
2506 Value *FrontV = Item.front().first->get();
2507 Use *U = IL.first;
2508 return !U || (cast<Instruction>(U->get())->getOperand(Op) ==
2509 cast<Instruction>(FrontV)->getOperand(Op));
2510 }))
2511 return false;
2512 continue;
2513 }
2515 }
2516 continue;
2517 }
2518 }
2519
2520 if (isFreeConcat(Item, CostKind, TTI)) {
2521 ConcatLeafs.insert(FrontU);
2522 continue;
2523 }
2524
2525 return false;
2526 }
2527
2528 if (NumVisited <= 1)
2529 return false;
2530
2531 LLVM_DEBUG(dbgs() << "Found a superfluous identity shuffle: " << I << "\n");
2532
2533 // If we got this far, we know the shuffles are superfluous and can be
2534 // removed. Scan through again and generate the new tree of instructions.
2535 Builder.SetInsertPoint(&I);
2536 Value *V = generateNewInstTree(Start, Ty, IdentityLeafs, SplatLeafs,
2537 ConcatLeafs, Builder, &TTI);
2538 replaceValue(I, *V);
2539 return true;
2540}
2541
2542/// Given a commutative reduction, the order of the input lanes does not alter
2543/// the results. We can use this to remove certain shuffles feeding the
2544/// reduction, removing the need to shuffle at all.
2545bool VectorCombine::foldShuffleFromReductions(Instruction &I) {
2546 auto *II = dyn_cast<IntrinsicInst>(&I);
2547 if (!II)
2548 return false;
2549 switch (II->getIntrinsicID()) {
2550 case Intrinsic::vector_reduce_add:
2551 case Intrinsic::vector_reduce_mul:
2552 case Intrinsic::vector_reduce_and:
2553 case Intrinsic::vector_reduce_or:
2554 case Intrinsic::vector_reduce_xor:
2555 case Intrinsic::vector_reduce_smin:
2556 case Intrinsic::vector_reduce_smax:
2557 case Intrinsic::vector_reduce_umin:
2558 case Intrinsic::vector_reduce_umax:
2559 break;
2560 default:
2561 return false;
2562 }
2563
2564 // Find all the inputs when looking through operations that do not alter the
2565 // lane order (binops, for example). Currently we look for a single shuffle,
2566 // and can ignore splat values.
2567 std::queue<Value *> Worklist;
2569 ShuffleVectorInst *Shuffle = nullptr;
2570 if (auto *Op = dyn_cast<Instruction>(I.getOperand(0)))
2571 Worklist.push(Op);
2572
2573 while (!Worklist.empty()) {
2574 Value *CV = Worklist.front();
2575 Worklist.pop();
2576 if (Visited.contains(CV))
2577 continue;
2578
2579 // Splats don't change the order, so can be safely ignored.
2580 if (isSplatValue(CV))
2581 continue;
2582
2583 Visited.insert(CV);
2584
2585 if (auto *CI = dyn_cast<Instruction>(CV)) {
2586 if (CI->isBinaryOp()) {
2587 for (auto *Op : CI->operand_values())
2588 Worklist.push(Op);
2589 continue;
2590 } else if (auto *SV = dyn_cast<ShuffleVectorInst>(CI)) {
2591 if (Shuffle && Shuffle != SV)
2592 return false;
2593 Shuffle = SV;
2594 continue;
2595 }
2596 }
2597
2598 // Anything else is currently an unknown node.
2599 return false;
2600 }
2601
2602 if (!Shuffle)
2603 return false;
2604
2605 // Check all uses of the binary ops and shuffles are also included in the
2606 // lane-invariant operations (Visited should be the list of lanewise
2607 // instructions, including the shuffle that we found).
2608 for (auto *V : Visited)
2609 for (auto *U : V->users())
2610 if (!Visited.contains(U) && U != &I)
2611 return false;
2612
2614 dyn_cast<FixedVectorType>(II->getOperand(0)->getType());
2615 if (!VecType)
2616 return false;
2617 FixedVectorType *ShuffleInputType =
2618 dyn_cast<FixedVectorType>(Shuffle->getOperand(0)->getType());
2619 if (!ShuffleInputType)
2620 return false;
2621 unsigned NumInputElts = ShuffleInputType->getNumElements();
2622
2623 // Find the mask from sorting the lanes into order. This is most likely to
2624 // become a identity or concat mask. Undef elements are pushed to the end.
2625 SmallVector<int> ConcatMask;
2626 Shuffle->getShuffleMask(ConcatMask);
2627 sort(ConcatMask, [](int X, int Y) { return (unsigned)X < (unsigned)Y; });
2628 // In the case of a truncating shuffle it's possible for the mask
2629 // to have an index greater than the size of the resulting vector.
2630 // This requires special handling.
2631 bool IsTruncatingShuffle = VecType->getNumElements() < NumInputElts;
2632 bool UsesSecondVec =
2633 any_of(ConcatMask, [&](int M) { return M >= (int)NumInputElts; });
2634
2635 FixedVectorType *VecTyForCost =
2636 (UsesSecondVec && !IsTruncatingShuffle) ? VecType : ShuffleInputType;
2639 VecTyForCost, Shuffle->getShuffleMask(), CostKind);
2642 VecTyForCost, ConcatMask, CostKind);
2643
2644 LLVM_DEBUG(dbgs() << "Found a reduction feeding from a shuffle: " << *Shuffle
2645 << "\n");
2646 LLVM_DEBUG(dbgs() << " OldCost: " << OldCost << " vs NewCost: " << NewCost
2647 << "\n");
2648 if (NewCost < OldCost) {
2649 Builder.SetInsertPoint(Shuffle);
2650 Value *NewShuffle = Builder.CreateShuffleVector(
2651 Shuffle->getOperand(0), Shuffle->getOperand(1), ConcatMask);
2652 LLVM_DEBUG(dbgs() << "Created new shuffle: " << *NewShuffle << "\n");
2653 replaceValue(*Shuffle, *NewShuffle);
2654 }
2655
2656 // See if we can re-use foldSelectShuffle, getting it to reduce the size of
2657 // the shuffle into a nicer order, as it can ignore the order of the shuffles.
2658 return foldSelectShuffle(*Shuffle, true);
2659}
2660
2661/// Determine if its more efficient to fold:
2662/// reduce(trunc(x)) -> trunc(reduce(x)).
2663/// reduce(sext(x)) -> sext(reduce(x)).
2664/// reduce(zext(x)) -> zext(reduce(x)).
2665bool VectorCombine::foldCastFromReductions(Instruction &I) {
2666 auto *II = dyn_cast<IntrinsicInst>(&I);
2667 if (!II)
2668 return false;
2669
2670 bool TruncOnly = false;
2671 Intrinsic::ID IID = II->getIntrinsicID();
2672 switch (IID) {
2673 case Intrinsic::vector_reduce_add:
2674 case Intrinsic::vector_reduce_mul:
2675 TruncOnly = true;
2676 break;
2677 case Intrinsic::vector_reduce_and:
2678 case Intrinsic::vector_reduce_or:
2679 case Intrinsic::vector_reduce_xor:
2680 break;
2681 default:
2682 return false;
2683 }
2684
2685 unsigned ReductionOpc = getArithmeticReductionInstruction(IID);
2686 Value *ReductionSrc = I.getOperand(0);
2687
2688 Value *Src;
2689 if (!match(ReductionSrc, m_OneUse(m_Trunc(m_Value(Src)))) &&
2690 (TruncOnly || !match(ReductionSrc, m_OneUse(m_ZExtOrSExt(m_Value(Src))))))
2691 return false;
2692
2693 auto CastOpc =
2694 (Instruction::CastOps)cast<Instruction>(ReductionSrc)->getOpcode();
2695
2696 auto *SrcTy = cast<VectorType>(Src->getType());
2697 auto *ReductionSrcTy = cast<VectorType>(ReductionSrc->getType());
2698 Type *ResultTy = I.getType();
2699
2701 ReductionOpc, ReductionSrcTy, std::nullopt, CostKind);
2702 OldCost += TTI.getCastInstrCost(CastOpc, ReductionSrcTy, SrcTy,
2704 cast<CastInst>(ReductionSrc));
2705 InstructionCost NewCost =
2706 TTI.getArithmeticReductionCost(ReductionOpc, SrcTy, std::nullopt,
2707 CostKind) +
2708 TTI.getCastInstrCost(CastOpc, ResultTy, ReductionSrcTy->getScalarType(),
2710
2711 if (OldCost <= NewCost || !NewCost.isValid())
2712 return false;
2713
2714 Value *NewReduction = Builder.CreateIntrinsic(SrcTy->getScalarType(),
2715 II->getIntrinsicID(), {Src});
2716 Value *NewCast = Builder.CreateCast(CastOpc, NewReduction, ResultTy);
2717 replaceValue(I, *NewCast);
2718 return true;
2719}
2720
2721/// This method looks for groups of shuffles acting on binops, of the form:
2722/// %x = shuffle ...
2723/// %y = shuffle ...
2724/// %a = binop %x, %y
2725/// %b = binop %x, %y
2726/// shuffle %a, %b, selectmask
2727/// We may, especially if the shuffle is wider than legal, be able to convert
2728/// the shuffle to a form where only parts of a and b need to be computed. On
2729/// architectures with no obvious "select" shuffle, this can reduce the total
2730/// number of operations if the target reports them as cheaper.
2731bool VectorCombine::foldSelectShuffle(Instruction &I, bool FromReduction) {
2732 auto *SVI = cast<ShuffleVectorInst>(&I);
2733 auto *VT = cast<FixedVectorType>(I.getType());
2734 auto *Op0 = dyn_cast<Instruction>(SVI->getOperand(0));
2735 auto *Op1 = dyn_cast<Instruction>(SVI->getOperand(1));
2736 if (!Op0 || !Op1 || Op0 == Op1 || !Op0->isBinaryOp() || !Op1->isBinaryOp() ||
2737 VT != Op0->getType())
2738 return false;
2739
2740 auto *SVI0A = dyn_cast<Instruction>(Op0->getOperand(0));
2741 auto *SVI0B = dyn_cast<Instruction>(Op0->getOperand(1));
2742 auto *SVI1A = dyn_cast<Instruction>(Op1->getOperand(0));
2743 auto *SVI1B = dyn_cast<Instruction>(Op1->getOperand(1));
2744 SmallPtrSet<Instruction *, 4> InputShuffles({SVI0A, SVI0B, SVI1A, SVI1B});
2745 auto checkSVNonOpUses = [&](Instruction *I) {
2746 if (!I || I->getOperand(0)->getType() != VT)
2747 return true;
2748 return any_of(I->users(), [&](User *U) {
2749 return U != Op0 && U != Op1 &&
2750 !(isa<ShuffleVectorInst>(U) &&
2751 (InputShuffles.contains(cast<Instruction>(U)) ||
2752 isInstructionTriviallyDead(cast<Instruction>(U))));
2753 });
2754 };
2755 if (checkSVNonOpUses(SVI0A) || checkSVNonOpUses(SVI0B) ||
2756 checkSVNonOpUses(SVI1A) || checkSVNonOpUses(SVI1B))
2757 return false;
2758
2759 // Collect all the uses that are shuffles that we can transform together. We
2760 // may not have a single shuffle, but a group that can all be transformed
2761 // together profitably.
2763 auto collectShuffles = [&](Instruction *I) {
2764 for (auto *U : I->users()) {
2765 auto *SV = dyn_cast<ShuffleVectorInst>(U);
2766 if (!SV || SV->getType() != VT)
2767 return false;
2768 if ((SV->getOperand(0) != Op0 && SV->getOperand(0) != Op1) ||
2769 (SV->getOperand(1) != Op0 && SV->getOperand(1) != Op1))
2770 return false;
2771 if (!llvm::is_contained(Shuffles, SV))
2772 Shuffles.push_back(SV);
2773 }
2774 return true;
2775 };
2776 if (!collectShuffles(Op0) || !collectShuffles(Op1))
2777 return false;
2778 // From a reduction, we need to be processing a single shuffle, otherwise the
2779 // other uses will not be lane-invariant.
2780 if (FromReduction && Shuffles.size() > 1)
2781 return false;
2782
2783 // Add any shuffle uses for the shuffles we have found, to include them in our
2784 // cost calculations.
2785 if (!FromReduction) {
2786 for (ShuffleVectorInst *SV : Shuffles) {
2787 for (auto *U : SV->users()) {
2788 ShuffleVectorInst *SSV = dyn_cast<ShuffleVectorInst>(U);
2789 if (SSV && isa<UndefValue>(SSV->getOperand(1)) && SSV->getType() == VT)
2790 Shuffles.push_back(SSV);
2791 }
2792 }
2793 }
2794
2795 // For each of the output shuffles, we try to sort all the first vector
2796 // elements to the beginning, followed by the second array elements at the
2797 // end. If the binops are legalized to smaller vectors, this may reduce total
2798 // number of binops. We compute the ReconstructMask mask needed to convert
2799 // back to the original lane order.
2801 SmallVector<SmallVector<int>> OrigReconstructMasks;
2802 int MaxV1Elt = 0, MaxV2Elt = 0;
2803 unsigned NumElts = VT->getNumElements();
2804 for (ShuffleVectorInst *SVN : Shuffles) {
2806 SVN->getShuffleMask(Mask);
2807
2808 // Check the operands are the same as the original, or reversed (in which
2809 // case we need to commute the mask).
2810 Value *SVOp0 = SVN->getOperand(0);
2811 Value *SVOp1 = SVN->getOperand(1);
2812 if (isa<UndefValue>(SVOp1)) {
2813 auto *SSV = cast<ShuffleVectorInst>(SVOp0);
2814 SVOp0 = SSV->getOperand(0);
2815 SVOp1 = SSV->getOperand(1);
2816 for (unsigned I = 0, E = Mask.size(); I != E; I++) {
2817 if (Mask[I] >= static_cast<int>(SSV->getShuffleMask().size()))
2818 return false;
2819 Mask[I] = Mask[I] < 0 ? Mask[I] : SSV->getMaskValue(Mask[I]);
2820 }
2821 }
2822 if (SVOp0 == Op1 && SVOp1 == Op0) {
2823 std::swap(SVOp0, SVOp1);
2825 }
2826 if (SVOp0 != Op0 || SVOp1 != Op1)
2827 return false;
2828
2829 // Calculate the reconstruction mask for this shuffle, as the mask needed to
2830 // take the packed values from Op0/Op1 and reconstructing to the original
2831 // order.
2832 SmallVector<int> ReconstructMask;
2833 for (unsigned I = 0; I < Mask.size(); I++) {
2834 if (Mask[I] < 0) {
2835 ReconstructMask.push_back(-1);
2836 } else if (Mask[I] < static_cast<int>(NumElts)) {
2837 MaxV1Elt = std::max(MaxV1Elt, Mask[I]);
2838 auto It = find_if(V1, [&](const std::pair<int, int> &A) {
2839 return Mask[I] == A.first;
2840 });
2841 if (It != V1.end())
2842 ReconstructMask.push_back(It - V1.begin());
2843 else {
2844 ReconstructMask.push_back(V1.size());
2845 V1.emplace_back(Mask[I], V1.size());
2846 }
2847 } else {
2848 MaxV2Elt = std::max<int>(MaxV2Elt, Mask[I] - NumElts);
2849 auto It = find_if(V2, [&](const std::pair<int, int> &A) {
2850 return Mask[I] - static_cast<int>(NumElts) == A.first;
2851 });
2852 if (It != V2.end())
2853 ReconstructMask.push_back(NumElts + It - V2.begin());
2854 else {
2855 ReconstructMask.push_back(NumElts + V2.size());
2856 V2.emplace_back(Mask[I] - NumElts, NumElts + V2.size());
2857 }
2858 }
2859 }
2860
2861 // For reductions, we know that the lane ordering out doesn't alter the
2862 // result. In-order can help simplify the shuffle away.
2863 if (FromReduction)
2864 sort(ReconstructMask);
2865 OrigReconstructMasks.push_back(std::move(ReconstructMask));
2866 }
2867
2868 // If the Maximum element used from V1 and V2 are not larger than the new
2869 // vectors, the vectors are already packes and performing the optimization
2870 // again will likely not help any further. This also prevents us from getting
2871 // stuck in a cycle in case the costs do not also rule it out.
2872 if (V1.empty() || V2.empty() ||
2873 (MaxV1Elt == static_cast<int>(V1.size()) - 1 &&
2874 MaxV2Elt == static_cast<int>(V2.size()) - 1))
2875 return false;
2876
2877 // GetBaseMaskValue takes one of the inputs, which may either be a shuffle, a
2878 // shuffle of another shuffle, or not a shuffle (that is treated like a
2879 // identity shuffle).
2880 auto GetBaseMaskValue = [&](Instruction *I, int M) {
2881 auto *SV = dyn_cast<ShuffleVectorInst>(I);
2882 if (!SV)
2883 return M;
2884 if (isa<UndefValue>(SV->getOperand(1)))
2885 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
2886 if (InputShuffles.contains(SSV))
2887 return SSV->getMaskValue(SV->getMaskValue(M));
2888 return SV->getMaskValue(M);
2889 };
2890
2891 // Attempt to sort the inputs my ascending mask values to make simpler input
2892 // shuffles and push complex shuffles down to the uses. We sort on the first
2893 // of the two input shuffle orders, to try and get at least one input into a
2894 // nice order.
2895 auto SortBase = [&](Instruction *A, std::pair<int, int> X,
2896 std::pair<int, int> Y) {
2897 int MXA = GetBaseMaskValue(A, X.first);
2898 int MYA = GetBaseMaskValue(A, Y.first);
2899 return MXA < MYA;
2900 };
2901 stable_sort(V1, [&](std::pair<int, int> A, std::pair<int, int> B) {
2902 return SortBase(SVI0A, A, B);
2903 });
2904 stable_sort(V2, [&](std::pair<int, int> A, std::pair<int, int> B) {
2905 return SortBase(SVI1A, A, B);
2906 });
2907 // Calculate our ReconstructMasks from the OrigReconstructMasks and the
2908 // modified order of the input shuffles.
2909 SmallVector<SmallVector<int>> ReconstructMasks;
2910 for (const auto &Mask : OrigReconstructMasks) {
2911 SmallVector<int> ReconstructMask;
2912 for (int M : Mask) {
2913 auto FindIndex = [](const SmallVector<std::pair<int, int>> &V, int M) {
2914 auto It = find_if(V, [M](auto A) { return A.second == M; });
2915 assert(It != V.end() && "Expected all entries in Mask");
2916 return std::distance(V.begin(), It);
2917 };
2918 if (M < 0)
2919 ReconstructMask.push_back(-1);
2920 else if (M < static_cast<int>(NumElts)) {
2921 ReconstructMask.push_back(FindIndex(V1, M));
2922 } else {
2923 ReconstructMask.push_back(NumElts + FindIndex(V2, M));
2924 }
2925 }
2926 ReconstructMasks.push_back(std::move(ReconstructMask));
2927 }
2928
2929 // Calculate the masks needed for the new input shuffles, which get padded
2930 // with undef
2931 SmallVector<int> V1A, V1B, V2A, V2B;
2932 for (unsigned I = 0; I < V1.size(); I++) {
2933 V1A.push_back(GetBaseMaskValue(SVI0A, V1[I].first));
2934 V1B.push_back(GetBaseMaskValue(SVI0B, V1[I].first));
2935 }
2936 for (unsigned I = 0; I < V2.size(); I++) {
2937 V2A.push_back(GetBaseMaskValue(SVI1A, V2[I].first));
2938 V2B.push_back(GetBaseMaskValue(SVI1B, V2[I].first));
2939 }
2940 while (V1A.size() < NumElts) {
2943 }
2944 while (V2A.size() < NumElts) {
2947 }
2948
2949 auto AddShuffleCost = [&](InstructionCost C, Instruction *I) {
2950 auto *SV = dyn_cast<ShuffleVectorInst>(I);
2951 if (!SV)
2952 return C;
2953 return C + TTI.getShuffleCost(isa<UndefValue>(SV->getOperand(1))
2956 VT, SV->getShuffleMask(), CostKind);
2957 };
2958 auto AddShuffleMaskCost = [&](InstructionCost C, ArrayRef<int> Mask) {
2959 return C + TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, VT, Mask, CostKind);
2960 };
2961
2962 // Get the costs of the shuffles + binops before and after with the new
2963 // shuffle masks.
2964 InstructionCost CostBefore =
2965 TTI.getArithmeticInstrCost(Op0->getOpcode(), VT, CostKind) +
2966 TTI.getArithmeticInstrCost(Op1->getOpcode(), VT, CostKind);
2967 CostBefore += std::accumulate(Shuffles.begin(), Shuffles.end(),
2968 InstructionCost(0), AddShuffleCost);
2969 CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(),
2970 InstructionCost(0), AddShuffleCost);
2971
2972 // The new binops will be unused for lanes past the used shuffle lengths.
2973 // These types attempt to get the correct cost for that from the target.
2974 FixedVectorType *Op0SmallVT =
2975 FixedVectorType::get(VT->getScalarType(), V1.size());
2976 FixedVectorType *Op1SmallVT =
2977 FixedVectorType::get(VT->getScalarType(), V2.size());
2978 InstructionCost CostAfter =
2979 TTI.getArithmeticInstrCost(Op0->getOpcode(), Op0SmallVT, CostKind) +
2980 TTI.getArithmeticInstrCost(Op1->getOpcode(), Op1SmallVT, CostKind);
2981 CostAfter += std::accumulate(ReconstructMasks.begin(), ReconstructMasks.end(),
2982 InstructionCost(0), AddShuffleMaskCost);
2983 std::set<SmallVector<int>> OutputShuffleMasks({V1A, V1B, V2A, V2B});
2984 CostAfter +=
2985 std::accumulate(OutputShuffleMasks.begin(), OutputShuffleMasks.end(),
2986 InstructionCost(0), AddShuffleMaskCost);
2987
2988 LLVM_DEBUG(dbgs() << "Found a binop select shuffle pattern: " << I << "\n");
2989 LLVM_DEBUG(dbgs() << " CostBefore: " << CostBefore
2990 << " vs CostAfter: " << CostAfter << "\n");
2991 if (CostBefore <= CostAfter)
2992 return false;
2993
2994 // The cost model has passed, create the new instructions.
2995 auto GetShuffleOperand = [&](Instruction *I, unsigned Op) -> Value * {
2996 auto *SV = dyn_cast<ShuffleVectorInst>(I);
2997 if (!SV)
2998 return I;
2999 if (isa<UndefValue>(SV->getOperand(1)))
3000 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
3001 if (InputShuffles.contains(SSV))
3002 return SSV->getOperand(Op);
3003 return SV->getOperand(Op);
3004 };
3005 Builder.SetInsertPoint(*SVI0A->getInsertionPointAfterDef());
3006 Value *NSV0A = Builder.CreateShuffleVector(GetShuffleOperand(SVI0A, 0),
3007 GetShuffleOperand(SVI0A, 1), V1A);
3008 Builder.SetInsertPoint(*SVI0B->getInsertionPointAfterDef());
3009 Value *NSV0B = Builder.CreateShuffleVector(GetShuffleOperand(SVI0B, 0),
3010 GetShuffleOperand(SVI0B, 1), V1B);
3011 Builder.SetInsertPoint(*SVI1A->getInsertionPointAfterDef());
3012 Value *NSV1A = Builder.CreateShuffleVector(GetShuffleOperand(SVI1A, 0),
3013 GetShuffleOperand(SVI1A, 1), V2A);
3014 Builder.SetInsertPoint(*SVI1B->getInsertionPointAfterDef());
3015 Value *NSV1B = Builder.CreateShuffleVector(GetShuffleOperand(SVI1B, 0),
3016 GetShuffleOperand(SVI1B, 1), V2B);
3017 Builder.SetInsertPoint(Op0);
3018 Value *NOp0 = Builder.CreateBinOp((Instruction::BinaryOps)Op0->getOpcode(),
3019 NSV0A, NSV0B);
3020 if (auto *I = dyn_cast<Instruction>(NOp0))
3021 I->copyIRFlags(Op0, true);
3022 Builder.SetInsertPoint(Op1);
3023 Value *NOp1 = Builder.CreateBinOp((Instruction::BinaryOps)Op1->getOpcode(),
3024 NSV1A, NSV1B);
3025 if (auto *I = dyn_cast<Instruction>(NOp1))
3026 I->copyIRFlags(Op1, true);
3027
3028 for (int S = 0, E = ReconstructMasks.size(); S != E; S++) {
3029 Builder.SetInsertPoint(Shuffles[S]);
3030 Value *NSV = Builder.CreateShuffleVector(NOp0, NOp1, ReconstructMasks[S]);
3031 replaceValue(*Shuffles[S], *NSV);
3032 }
3033
3034 Worklist.pushValue(NSV0A);
3035 Worklist.pushValue(NSV0B);
3036 Worklist.pushValue(NSV1A);
3037 Worklist.pushValue(NSV1B);
3038 for (auto *S : Shuffles)
3039 Worklist.add(S);
3040 return true;
3041}
3042
3043/// Check if instruction depends on ZExt and this ZExt can be moved after the
3044/// instruction. Move ZExt if it is profitable. For example:
3045/// logic(zext(x),y) -> zext(logic(x,trunc(y)))
3046/// lshr((zext(x),y) -> zext(lshr(x,trunc(y)))
3047/// Cost model calculations takes into account if zext(x) has other users and
3048/// whether it can be propagated through them too.
3049bool VectorCombine::shrinkType(Instruction &I) {
3050 Value *ZExted, *OtherOperand;
3051 if (!match(&I, m_c_BitwiseLogic(m_ZExt(m_Value(ZExted)),
3052 m_Value(OtherOperand))) &&
3053 !match(&I, m_LShr(m_ZExt(m_Value(ZExted)), m_Value(OtherOperand))))
3054 return false;
3055
3056 Value *ZExtOperand = I.getOperand(I.getOperand(0) == OtherOperand ? 1 : 0);
3057
3058 auto *BigTy = cast<FixedVectorType>(I.getType());
3059 auto *SmallTy = cast<FixedVectorType>(ZExted->getType());
3060 unsigned BW = SmallTy->getElementType()->getPrimitiveSizeInBits();
3061
3062 if (I.getOpcode() == Instruction::LShr) {
3063 // Check that the shift amount is less than the number of bits in the
3064 // smaller type. Otherwise, the smaller lshr will return a poison value.
3065 KnownBits ShAmtKB = computeKnownBits(I.getOperand(1), *DL);
3066 if (ShAmtKB.getMaxValue().uge(BW))
3067 return false;
3068 } else {
3069 // Check that the expression overall uses at most the same number of bits as
3070 // ZExted
3071 KnownBits KB = computeKnownBits(&I, *DL);
3072 if (KB.countMaxActiveBits() > BW)
3073 return false;
3074 }
3075
3076 // Calculate costs of leaving current IR as it is and moving ZExt operation
3077 // later, along with adding truncates if needed
3079 Instruction::ZExt, BigTy, SmallTy,
3080 TargetTransformInfo::CastContextHint::None, CostKind);
3081 InstructionCost CurrentCost = ZExtCost;
3082 InstructionCost ShrinkCost = 0;
3083
3084 // Calculate total cost and check that we can propagate through all ZExt users
3085 for (User *U : ZExtOperand->users()) {
3086 auto *UI = cast<Instruction>(U);
3087 if (UI == &I) {
3088 CurrentCost +=
3089 TTI.getArithmeticInstrCost(UI->getOpcode(), BigTy, CostKind);
3090 ShrinkCost +=
3091 TTI.getArithmeticInstrCost(UI->getOpcode(), SmallTy, CostKind);
3092 ShrinkCost += ZExtCost;
3093 continue;
3094 }
3095
3096 if (!Instruction::isBinaryOp(UI->getOpcode()))
3097 return false;
3098
3099 // Check if we can propagate ZExt through its other users
3100 KnownBits KB = computeKnownBits(UI, *DL);
3101 if (KB.countMaxActiveBits() > BW)
3102 return false;
3103
3104 CurrentCost += TTI.getArithmeticInstrCost(UI->getOpcode(), BigTy, CostKind);
3105 ShrinkCost +=
3106 TTI.getArithmeticInstrCost(UI->getOpcode(), SmallTy, CostKind);
3107 ShrinkCost += ZExtCost;
3108 }
3109
3110 // If the other instruction operand is not a constant, we'll need to
3111 // generate a truncate instruction. So we have to adjust cost
3112 if (!isa<Constant>(OtherOperand))
3113 ShrinkCost += TTI.getCastInstrCost(
3114 Instruction::Trunc, SmallTy, BigTy,
3115 TargetTransformInfo::CastContextHint::None, CostKind);
3116
3117 // If the cost of shrinking types and leaving the IR is the same, we'll lean
3118 // towards modifying the IR because shrinking opens opportunities for other
3119 // shrinking optimisations.
3120 if (ShrinkCost > CurrentCost)
3121 return false;
3122
3123 Builder.SetInsertPoint(&I);
3124 Value *Op0 = ZExted;
3125 Value *Op1 = Builder.CreateTrunc(OtherOperand, SmallTy);
3126 // Keep the order of operands the same
3127 if (I.getOperand(0) == OtherOperand)
3128 std::swap(Op0, Op1);
3129 Value *NewBinOp =
3130 Builder.CreateBinOp((Instruction::BinaryOps)I.getOpcode(), Op0, Op1);
3131 cast<Instruction>(NewBinOp)->copyIRFlags(&I);
3132 cast<Instruction>(NewBinOp)->copyMetadata(I);
3133 Value *NewZExtr = Builder.CreateZExt(NewBinOp, BigTy);
3134 replaceValue(I, *NewZExtr);
3135 return true;
3136}
3137
3138/// insert (DstVec, (extract SrcVec, ExtIdx), InsIdx) -->
3139/// shuffle (DstVec, SrcVec, Mask)
3140bool VectorCombine::foldInsExtVectorToShuffle(Instruction &I) {
3141 Value *DstVec, *SrcVec;
3142 uint64_t ExtIdx, InsIdx;
3143 if (!match(&I,
3144 m_InsertElt(m_Value(DstVec),
3145 m_ExtractElt(m_Value(SrcVec), m_ConstantInt(ExtIdx)),
3146 m_ConstantInt(InsIdx))))
3147 return false;
3148
3149 auto *VecTy = dyn_cast<FixedVectorType>(I.getType());
3150 if (!VecTy || SrcVec->getType() != VecTy)
3151 return false;
3152
3153 unsigned NumElts = VecTy->getNumElements();
3154 if (ExtIdx >= NumElts || InsIdx >= NumElts)
3155 return false;
3156
3157 // Insertion into poison is a cheaper single operand shuffle.
3160 if (isa<PoisonValue>(DstVec) && !isa<UndefValue>(SrcVec)) {
3162 Mask[InsIdx] = ExtIdx;
3163 std::swap(DstVec, SrcVec);
3164 } else {
3166 std::iota(Mask.begin(), Mask.end(), 0);
3167 Mask[InsIdx] = ExtIdx + NumElts;
3168 }
3169
3170 // Cost
3171 auto *Ins = cast<InsertElementInst>(&I);
3172 auto *Ext = cast<ExtractElementInst>(I.getOperand(1));
3173 InstructionCost InsCost =
3174 TTI.getVectorInstrCost(*Ins, VecTy, CostKind, InsIdx);
3175 InstructionCost ExtCost =
3176 TTI.getVectorInstrCost(*Ext, VecTy, CostKind, ExtIdx);
3177 InstructionCost OldCost = ExtCost + InsCost;
3178
3179 // Ignore 'free' identity insertion shuffle.
3180 // TODO: getShuffleCost should return TCC_Free for Identity shuffles.
3181 InstructionCost NewCost = 0;
3182 if (!ShuffleVectorInst::isIdentityMask(Mask, NumElts))
3183 NewCost += TTI.getShuffleCost(SK, VecTy, Mask, CostKind, 0, nullptr,
3184 {DstVec, SrcVec});
3185 if (!Ext->hasOneUse())
3186 NewCost += ExtCost;
3187
3188 LLVM_DEBUG(dbgs() << "Found a insert/extract shuffle-like pair: " << I
3189 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
3190 << "\n");
3191
3192 if (OldCost < NewCost)
3193 return false;
3194
3195 // Canonicalize undef param to RHS to help further folds.
3196 if (isa<UndefValue>(DstVec) && !isa<UndefValue>(SrcVec)) {
3198 std::swap(DstVec, SrcVec);
3199 }
3200
3201 Value *Shuf = Builder.CreateShuffleVector(DstVec, SrcVec, Mask);
3202 replaceValue(I, *Shuf);
3203
3204 return true;
3205}
3206
3207/// This is the entry point for all transforms. Pass manager differences are
3208/// handled in the callers of this function.
3209bool VectorCombine::run() {
3211 return false;
3212
3213 // Don't attempt vectorization if the target does not support vectors.
3214 if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
3215 return false;
3216
3217 LLVM_DEBUG(dbgs() << "\n\nVECTORCOMBINE on " << F.getName() << "\n");
3218
3219 bool MadeChange = false;
3220 auto FoldInst = [this, &MadeChange](Instruction &I) {
3221 Builder.SetInsertPoint(&I);
3222 bool IsVectorType = isa<VectorType>(I.getType());
3223 bool IsFixedVectorType = isa<FixedVectorType>(I.getType());
3224 auto Opcode = I.getOpcode();
3225
3226 LLVM_DEBUG(dbgs() << "VC: Visiting: " << I << '\n');
3227
3228 // These folds should be beneficial regardless of when this pass is run
3229 // in the optimization pipeline.
3230 // The type checking is for run-time efficiency. We can avoid wasting time
3231 // dispatching to folding functions if there's no chance of matching.
3232 if (IsFixedVectorType) {
3233 switch (Opcode) {
3234 case Instruction::InsertElement:
3235 MadeChange |= vectorizeLoadInsert(I);
3236 break;
3237 case Instruction::ShuffleVector:
3238 MadeChange |= widenSubvectorLoad(I);
3239 break;
3240 default:
3241 break;
3242 }
3243 }
3244
3245 // This transform works with scalable and fixed vectors
3246 // TODO: Identify and allow other scalable transforms
3247 if (IsVectorType) {
3248 MadeChange |= scalarizeBinopOrCmp(I);
3249 MadeChange |= scalarizeLoadExtract(I);
3250 MadeChange |= scalarizeVPIntrinsic(I);
3251 }
3252
3253 if (Opcode == Instruction::Store)
3254 MadeChange |= foldSingleElementStore(I);
3255
3256 // If this is an early pipeline invocation of this pass, we are done.
3257 if (TryEarlyFoldsOnly)
3258 return;
3259
3260 // Otherwise, try folds that improve codegen but may interfere with
3261 // early IR canonicalizations.
3262 // The type checking is for run-time efficiency. We can avoid wasting time
3263 // dispatching to folding functions if there's no chance of matching.
3264 if (IsFixedVectorType) {
3265 switch (Opcode) {
3266 case Instruction::InsertElement:
3267 MadeChange |= foldInsExtFNeg(I);
3268 MadeChange |= foldInsExtBinop(I);
3269 MadeChange |= foldInsExtVectorToShuffle(I);
3270 break;
3271 case Instruction::ShuffleVector:
3272 MadeChange |= foldPermuteOfBinops(I);
3273 MadeChange |= foldShuffleOfBinops(I);
3274 MadeChange |= foldShuffleOfCastops(I);
3275 MadeChange |= foldShuffleOfShuffles(I);
3276 MadeChange |= foldShuffleOfIntrinsics(I);
3277 MadeChange |= foldSelectShuffle(I);
3278 MadeChange |= foldShuffleToIdentity(I);
3279 break;
3280 case Instruction::BitCast:
3281 MadeChange |= foldBitcastShuffle(I);
3282 break;
3283 default:
3284 MadeChange |= shrinkType(I);
3285 break;
3286 }
3287 } else {
3288 switch (Opcode) {
3289 case Instruction::Call:
3290 MadeChange |= foldShuffleFromReductions(I);
3291 MadeChange |= foldCastFromReductions(I);
3292 break;
3293 case Instruction::ICmp:
3294 case Instruction::FCmp:
3295 MadeChange |= foldExtractExtract(I);
3296 break;
3297 case Instruction::Or:
3298 MadeChange |= foldConcatOfBoolMasks(I);
3299 [[fallthrough]];
3300 default:
3301 if (Instruction::isBinaryOp(Opcode)) {
3302 MadeChange |= foldExtractExtract(I);
3303 MadeChange |= foldExtractedCmps(I);
3304 }
3305 break;
3306 }
3307 }
3308 };
3309
3310 for (BasicBlock &BB : F) {
3311 // Ignore unreachable basic blocks.
3312 if (!DT.isReachableFromEntry(&BB))
3313 continue;
3314 // Use early increment range so that we can erase instructions in loop.
3315 for (Instruction &I : make_early_inc_range(BB)) {
3316 if (I.isDebugOrPseudoInst())
3317 continue;
3318 FoldInst(I);
3319 }
3320 }
3321
3322 while (!Worklist.isEmpty()) {
3323 Instruction *I = Worklist.removeOne();
3324 if (!I)
3325 continue;
3326
3329 continue;
3330 }
3331
3332 FoldInst(*I);
3333 }
3334
3335 return MadeChange;
3336}
3337
3340 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
3344 const DataLayout *DL = &F.getDataLayout();
3345 VectorCombine Combiner(F, TTI, DT, AA, AC, DL, TTI::TCK_RecipThroughput,
3346 TryEarlyFoldsOnly);
3347 if (!Combiner.run())
3348 return PreservedAnalyses::all();
3351 return PA;
3352}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static cl::opt< TargetTransformInfo::TargetCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(TargetTransformInfo::TCK_RecipThroughput), cl::values(clEnumValN(TargetTransformInfo::TCK_RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(TargetTransformInfo::TCK_Latency, "latency", "Instruction latency"), clEnumValN(TargetTransformInfo::TCK_CodeSize, "code-size", "Code size"), clEnumValN(TargetTransformInfo::TCK_SizeAndLatency, "size-latency", "Code size and latency")))
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(...)
Definition: Debug.h:106
This file defines the DenseMap class.
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1315
bool End
Definition: ELF_riscv.cpp:480
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU)
Definition: LICM.cpp:1504
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
uint64_t IntrinsicInst * II
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
FunctionAnalysisManager FAM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned OpIndex
This file contains some templates that are useful if you are working with the STL at all.
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:166
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:245
static bool isFreeConcat(ArrayRef< InstLane > Item, TTI::TargetCostKind CostKind, const TargetTransformInfo &TTI)
Detect concat of multiple values into a vector.
static SmallVector< InstLane > generateInstLaneVectorFromOperand(ArrayRef< InstLane > Item, int Op)
static Value * createShiftShuffle(Value *Vec, unsigned OldIndex, unsigned NewIndex, IRBuilder<> &Builder)
Create a shuffle that translates (shifts) 1 element from the input vector to a new element location.
static Value * peekThroughBitcasts(Value *V)
Return the source operand of a potentially bitcasted value.
static Align computeAlignmentAfterScalarization(Align VectorAlignment, Type *ScalarType, Value *Idx, const DataLayout &DL)
The memory operation on a vector of ScalarType had alignment of VectorAlignment.
static ScalarizationResult canScalarizeAccess(VectorType *VecTy, Value *Idx, Instruction *CtxI, AssumptionCache &AC, const DominatorTree &DT)
Check if it is legal to scalarize a memory access to VecTy at index Idx.
static cl::opt< bool > DisableVectorCombine("disable-vector-combine", cl::init(false), cl::Hidden, cl::desc("Disable all vector combine transforms"))
static InstLane lookThroughShuffles(Use *U, int Lane)
static bool canWidenLoad(LoadInst *Load, const TargetTransformInfo &TTI)
static const unsigned InvalidIndex
static Value * generateNewInstTree(ArrayRef< InstLane > Item, FixedVectorType *Ty, const SmallPtrSet< Use *, 4 > &IdentityLeafs, const SmallPtrSet< Use *, 4 > &SplatLeafs, const SmallPtrSet< Use *, 4 > &ConcatLeafs, IRBuilder<> &Builder, const TargetTransformInfo *TTI)
std::pair< Use *, int > InstLane
static cl::opt< unsigned > MaxInstrsToScan("vector-combine-max-scan-instrs", cl::init(30), cl::Hidden, cl::desc("Max number of instructions to scan for vector combining."))
static cl::opt< bool > DisableBinopExtractShuffle("disable-binop-extract-shuffle", cl::init(false), cl::Hidden, cl::desc("Disable binop extract to shuffle transforms"))
static bool isMemModifiedBetween(BasicBlock::iterator Begin, BasicBlock::iterator End, const MemoryLocation &Loc, AAResults &AA)
static ExtractElementInst * translateExtract(ExtractElementInst *ExtElt, unsigned NewIndex, IRBuilder<> &Builder)
Given an extract element instruction with constant index operand, shuffle the source vector (shift th...
static constexpr int Concat[]
Value * RHS
Value * LHS
A manager for alias analyses.
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
Class for arbitrary precision integers.
Definition: APInt.h:78
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:239
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition: APInt.h:1221
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:410
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
const T & front() const
front - Get the first element.
Definition: ArrayRef.h:171
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
bool hasFnAttr(Attribute::AttrKind Kind) const
Return true if the attribute exists for the function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:177
BinaryOps getOpcode() const
Definition: InstrTypes.h:370
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:72
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1286
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
Definition: InstrTypes.h:1277
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:980
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:673
bool isFPPredicate() const
Definition: InstrTypes.h:780
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
Definition: CmpPredicate.h:22
static std::optional< CmpPredicate > getMatching(CmpPredicate A, CmpPredicate B)
Compares two CmpPredicates taking samesign into account and returns the canonicalized CmpPredicate if...
Combiner implementation.
Definition: Combiner.h:34
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2555
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:148
This class represents a range of values.
Definition: ConstantRange.h:47
ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
ConstantRange binaryAnd(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-and of a value in this ra...
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1421
This is an important base class in LLVM.
Definition: Constant.h:42
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:63
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:156
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition: DenseMap.h:226
iterator end()
Definition: DenseMap.h:84
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:321
This instruction extracts a single (scalar) element from a VectorType value.
This class represents a cast from floating point to signed integer.
This class represents a cast from floating point to unsigned integer.
Class to represent fixed width SIMD vectors.
Definition: DerivedTypes.h:563
unsigned getNumElements() const
Definition: DerivedTypes.h:606
static FixedVectorType * getDoubleElementsVectorType(FixedVectorType *VTy)
Definition: DerivedTypes.h:598
static FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition: Type.cpp:791
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2511
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2499
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1815
Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Definition: IRBuilder.cpp:1163
Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Definition: IRBuilder.cpp:1053
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition: IRBuilder.h:2574
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition: IRBuilder.h:2186
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition: IRBuilder.h:1882
Value * CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2211
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition: IRBuilder.h:510
Value * CreateUnOp(Instruction::UnaryOps Opc, Value *V, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1761
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Definition: IRBuilder.cpp:900
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:505
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2404
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2152
LoadInst * CreateLoad(Type *Ty, Value *Ptr, const char *Name)
Provided to resolve 'CreateLoad(Ty, Ptr, "...")' correctly, instead of converting the string to 'bool...
Definition: IRBuilder.h:1798
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition: IRBuilder.h:1459
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition: IRBuilder.h:2033
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition: IRBuilder.h:2533
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1811
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition: IRBuilder.h:2019
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition: IRBuilder.h:588
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1671
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:199
Value * CreateFNegFMF(Value *V, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1747
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2705
InstructionWorklist - This is the worklist management logic for InstCombine and other simplification ...
void pushUsersToWorkList(Instruction &I)
When an instruction is simplified, add all users of the instruction to the work lists because they mi...
void push(Instruction *I)
Push the instruction onto the worklist stack.
void remove(Instruction *I)
Remove I from the worklist if it exists.
void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
bool isBinaryOp() const
Definition: Instruction.h:315
bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
bool isIntDivRem() const
Definition: Instruction.h:316
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:55
An instruction for reading from memory.
Definition: Instructions.h:176
Representation for a specific memory location.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:310
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1878
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:111
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:117
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:146
This class represents a sign extension of integer types.
This class represents a cast from signed integer to floating point.
This instruction constructs a fixed permutation of two input vectors.
int getMaskValue(unsigned Elt) const
Return the shuffle mask value of this instruction for the given element index.
VectorType * getType() const
Overload to return most specific vector type.
static void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
static bool isIdentityMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector without lane crossin...
static void commuteShuffleMask(MutableArrayRef< int > Mask, unsigned InVecNumElts)
Change values in a shuffle permute mask assuming the two vector operands of length InVecNumElts have ...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:384
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:458
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
void assign(size_type NumElts, ValueParamT Elt)
Definition: SmallVector.h:704
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:937
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
An instruction for storing to memory.
Definition: Instructions.h:292
void setAlignment(Align Align)
Definition: Instructions.h:337
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, OperandValueInfo Op1Info={OK_AnyValue, OP_None}, OperandValueInfo Op2Info={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
InstructionCost getAddressComputationCost(Type *Ty, ScalarEvolution *SE=nullptr, const SCEV *Ptr=nullptr) const
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, OperandValueInfo OpdInfo={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of vector reduction intrinsics.
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
unsigned getRegisterClassForType(bool Vector, Type *Ty=nullptr) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *Tp, ArrayRef< int > Mask={}, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args={}, const Instruction *CxtI=nullptr) const
unsigned getMinVectorRegisterBitWidth() const
unsigned getNumberOfRegisters(unsigned ClassID) const
InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, ArrayRef< Value * > VL={}) const
Estimate the overhead of scalarizing an instruction.
InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, Value *Op0=nullptr, Value *Op1=nullptr) const
ShuffleKind
The various kinds of shuffle patterns for vector queries.
@ SK_PermuteSingleSrc
Shuffle elements of single source vector with any shuffle mask.
@ SK_Broadcast
Broadcast element 0 to all other elements.
@ SK_PermuteTwoSrc
Merge elements from two source vectors into one with any shuffle mask.
@ None
The cast is not used with a load/store of any kind.
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:270
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:264
static IntegerType * getIntNTy(LLVMContext &C, unsigned N)
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:184
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:237
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:355
This class represents a cast unsigned integer to floating point.
A Use represents the edge between a Value definition and its users.
Definition: Use.h:35
op_range operands()
Definition: User.h:288
Value * getOperand(unsigned i) const
Definition: User.h:228
static bool isVPBinOp(Intrinsic::ID ID)
This is the common base class for vector predication intrinsics.
std::optional< unsigned > getFunctionalIntrinsicID() const
std::optional< unsigned > getFunctionalOpcode() const
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition: Value.h:746
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
iterator_range< user_iterator > users()
Definition: Value.h:421
Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition: Value.cpp:946
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition: Value.h:532
bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition: Value.cpp:149
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
This class represents zero extension of integer types.
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:125
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
AttributeList getAttributes(LLVMContext &C, ID id)
Return the attributes for an intrinsic.
class_match< PoisonValue > m_Poison()
Match an arbitrary poison constant.
Definition: PatternMatch.h:160
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:100
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:165
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:982
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:826
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:885
DisjointOr_match< LHS, RHS > m_DisjointOr(const LHS &L, const RHS &R)
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
Definition: PatternMatch.h:168
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
match_combine_and< LTy, RTy > m_CombineAnd(const LTy &L, const RTy &R)
Combine two pattern matchers matching L && R.
Definition: PatternMatch.h:245
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
Definition: PatternMatch.h:599
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
BinOpPred_match< LHS, RHS, is_bitwiselogic_op, true > m_c_BitwiseLogic(const LHS &L, const RHS &R)
Matches bitwise logic operations in either order.
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
Definition: PatternMatch.h:105
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
match_combine_or< CastInst_match< OpTy, SExtInst >, NNegZExt_match< OpTy > > m_SExtLike(const OpTy &Op)
Match either "sext" or "zext nneg".
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:152
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition: STLExtras.h:329
@ Offset
Definition: DWP.cpp:480
void stable_sort(R &&Range)
Definition: STLExtras.h:2037
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1732
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:1739
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
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:2448
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
unsigned getArithmeticReductionInstruction(Intrinsic::ID RdxID)
Returns the arithmetic instruction opcode used when expanding a reduction.
Definition: LoopUtils.cpp:960
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition: STLExtras.h:657
bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
Definition: Loads.cpp:378
bool widenShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Try to transform a shuffle mask by replacing elements with the scaled index for an equivalent mask of...
Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
ConstantRange computeConstantRange(const Value *V, bool ForSigned, bool UseInstrInfo=true, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
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:1746
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction will return.
Definition: Local.cpp:406
bool isSplatValue(const Value *V, int Index=-1, unsigned Depth=0)
Return true if each element of the vector value V is poisoned or equal to every other non-poisoned el...
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition: MathExtras.h:292
bool isModSet(const ModRefInfo MRI)
Definition: ModRef.h:48
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1664
bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const DataLayout &DL, Instruction *ScanFrom, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if we know that executing a load from this value cannot trap.
Definition: Loads.cpp:393
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
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:548
void propagateIRFlags(Value *I, ArrayRef< Value * > VL, Value *OpValue=nullptr, bool IncludeWrapFlags=true)
Get the intersection (logical and) of all of the potential IR flags of each scalar operation (VL) tha...
Definition: LoopUtils.cpp:1368
bool isKnownNonZero(const Value *V, const SimplifyQuery &Q, unsigned Depth=0)
Return true if the given value is known to be non-zero when defined.
constexpr int PoisonMaskElem
void narrowShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Replace each shuffle mask index with the scaled sequential indices for an equivalent mask of narrowed...
bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
DWARFExpression::Operation Op
constexpr unsigned BitWidth
Definition: BitmaskEnum.h:217
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:1766
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1903
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition: Alignment.h:212
bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
Definition: VectorUtils.cpp:46
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39
unsigned countMaxActiveBits() const
Returns the maximum number of bits needed to represent all possible unsigned values with these known ...
Definition: KnownBits.h:288
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition: KnownBits.h:137