LLVM 24.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 "VectorizeOptions.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/ScopeExit.h"
22#include "llvm/ADT/Statistic.h"
27#include "llvm/Analysis/Loads.h"
32#include "llvm/IR/Dominators.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/IRBuilder.h"
42#include <numeric>
43#include <optional>
44#include <queue>
45#include <set>
46
47#define DEBUG_TYPE "vector-combine"
49
50using namespace llvm;
51using namespace llvm::PatternMatch;
52
53STATISTIC(NumVecLoad, "Number of vector loads formed");
54STATISTIC(NumVecCmp, "Number of vector compares formed");
55STATISTIC(NumVecBO, "Number of vector binops formed");
56STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
57STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
58STATISTIC(NumScalarOps, "Number of scalar unary + binary ops formed");
59STATISTIC(NumScalarCmp, "Number of scalar compares formed");
60STATISTIC(NumScalarIntrinsic, "Number of scalar intrinsic calls formed");
61
62static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
63
64namespace {
65class VectorCombine {
66public:
67 VectorCombine(const VectorizeOptions &Opts, Function &F,
68 const TargetTransformInfo &TTI, const DominatorTree &DT,
70 TTI::TargetCostKind CostKind, bool TryEarlyFoldsOnly)
71 : Opts(Opts), F(F),
72 Builder(*F.getParent(), InstSimplifyFolder(*DL),
74 // Automatically add newly created instructions
75 // into the deferred queue.
76 Worklist.add(I);
77 })),
78 TTI(TTI), DT(DT), AA(AA), DL(DL), CostKind(CostKind),
79 SQ(*DL, /*TLI=*/nullptr, &DT, &AC),
80 TryEarlyFoldsOnly(TryEarlyFoldsOnly) {}
81
82 bool run();
83
84private:
85 const VectorizeOptions &Opts;
86 Function &F;
87 IRBuilder<InstSimplifyFolder, IRBuilderCallbackInserter> Builder;
88 const TargetTransformInfo &TTI;
89 const DominatorTree &DT;
90 AAResults &AA;
91 const DataLayout *DL;
92 TTI::TargetCostKind CostKind;
93 const SimplifyQuery SQ;
94
95 /// If true, only perform beneficial early IR transforms. Do not introduce new
96 /// vector operations.
97 bool TryEarlyFoldsOnly;
98
99 InstructionWorklist Worklist;
100
101 /// Next instruction to iterate. It will be updated when it is erased by
102 /// RecursivelyDeleteTriviallyDeadInstructions.
103 Instruction *NextInst;
104
105 // TODO: Direct calls from the top-level "run" loop use a plain "Instruction"
106 // parameter. That should be updated to specific sub-classes because the
107 // run loop was changed to dispatch on opcode.
108 bool vectorizeLoadInsert(Instruction &I);
109 bool widenSubvectorLoad(Instruction &I);
110 ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
111 ExtractElementInst *Ext1,
112 unsigned PreferredExtractIndex) const;
113 bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
114 const Instruction &I,
115 ExtractElementInst *&ConvertToShuffle,
116 unsigned PreferredExtractIndex);
117 Value *foldExtExtCmp(Value *V0, Value *V1, Value *ExtIndex, Instruction &I);
118 Value *foldExtExtBinop(Value *V0, Value *V1, Value *ExtIndex, Instruction &I);
119 bool foldExtractExtract(Instruction &I);
120 bool foldInsExtFNeg(Instruction &I);
121 bool foldInsExtBinop(Instruction &I);
122 bool foldInsExtVectorToShuffle(Instruction &I);
123 bool foldInsertScalarPartsToShuffle(Instruction &I);
124 bool foldBitOpOfCastops(Instruction &I);
125 bool foldBitOpOfCastConstant(Instruction &I);
126 bool foldBitcastShuffle(Instruction &I);
127 bool scalarizeOpOrCmp(Instruction &I);
128 bool foldExtractedCmps(Instruction &I);
129 bool foldSelectsFromBitcast(Instruction &I);
130 bool foldBinopOfReductions(Instruction &I);
131 bool foldInsertElementsToStores(Instruction &I);
132 bool scalarizeLoad(Instruction &I);
133 bool scalarizeLoadExtract(LoadInst *LI, VectorType *VecTy, Value *Ptr);
134 bool scalarizeLoadBitcast(LoadInst *LI, VectorType *VecTy, Value *Ptr);
135 bool scalarizeExtExtract(Instruction &I);
136 bool foldConcatOfBoolMasks(Instruction &I);
137 bool foldPermuteOfBinops(Instruction &I);
138 bool foldShuffleOfBinops(Instruction &I);
139 bool foldShuffleOfSelects(Instruction &I);
140 bool foldShuffleOfCastops(Instruction &I);
141 bool foldShuffleOfShuffles(Instruction &I);
142 bool foldShuffleOfAdjacentLoads(Instruction &I);
143 bool foldPermuteOfIntrinsic(Instruction &I);
144 bool foldShufflesOfLengthChangingShuffles(Instruction &I);
145 bool foldShuffleOfIntrinsics(Instruction &I);
146 bool foldShuffleToIdentity(Instruction &I);
147 bool foldShuffleFromReductions(Instruction &I);
148 bool foldShuffleChainsToReduce(Instruction &I);
149 bool foldCastFromReductions(Instruction &I);
150 bool foldSignBitReductionCmp(Instruction &I);
151 bool foldReductionZeroTest(Instruction &I);
152 bool foldICmpEqZeroVectorReduce(Instruction &I);
153 bool foldEquivalentReductionCmp(Instruction &I);
154 bool foldReduceAddCmpZero(Instruction &I);
155 bool foldSelectShuffle(Instruction &I, bool FromReduction = false);
156 bool foldInterleaveIntrinsics(Instruction &I);
157 bool foldDeinterleaveIntrinsics(Instruction &I);
158 bool foldBitcastOfVPLoad(Instruction &I);
159 bool foldBitOrderReverseAndSwap(Instruction &I);
160 bool shrinkType(Instruction &I);
161 bool shrinkLoadForShuffles(Instruction &I);
162 bool shrinkPhiOfShuffles(Instruction &I);
163 bool foldInterleaveOfDeinterleaveChains(Instruction &I);
164
165 void replaceValue(Instruction &Old, Value &New, bool Erase = true) {
166 LLVM_DEBUG(dbgs() << "VC: Replacing: " << Old << '\n');
167 LLVM_DEBUG(dbgs() << " With: " << New << '\n');
168 Old.replaceAllUsesWith(&New);
169 if (auto *NewI = dyn_cast<Instruction>(&New)) {
170 New.takeName(&Old);
171 Worklist.pushUsersToWorkList(*NewI);
172 Worklist.pushValue(NewI);
173 }
174 if (Erase && isInstructionTriviallyDead(&Old)) {
175 eraseInstruction(Old);
176 } else {
177 Worklist.push(&Old);
178 }
179 }
180
181 void eraseInstruction(Instruction &I) {
182 LLVM_DEBUG(dbgs() << "VC: Erasing: " << I << '\n');
183 SmallVector<Value *> Ops(I.operands());
184 Worklist.remove(&I);
185 I.eraseFromParent();
186
187 // Push remaining users of the operands and then the operand itself - allows
188 // further folds that were hindered by OneUse limits.
189 SmallPtrSet<Value *, 4> Visited;
190 for (Value *Op : Ops) {
191 if (!Visited.contains(Op)) {
192 if (auto *OpI = dyn_cast<Instruction>(Op)) {
194 OpI, nullptr, nullptr, [&](Value *V) {
195 if (auto *I = dyn_cast<Instruction>(V)) {
196 LLVM_DEBUG(dbgs() << "VC: Erased: " << *I << '\n');
197 Worklist.remove(I);
198 if (I == NextInst)
199 NextInst = NextInst->getNextNode();
200 Visited.insert(I);
201 }
202 }))
203 continue;
204 Worklist.pushUsersToWorkList(*OpI);
205 Worklist.pushValue(OpI);
206 }
207 }
208 }
209 }
210};
211} // namespace
212
213/// Return the source operand of a potentially bitcasted value. If there is no
214/// bitcast, return the input value itself.
216 while (auto *BitCast = dyn_cast<BitCastInst>(V))
217 V = BitCast->getOperand(0);
218 return V;
219}
220
221/// Helper to peek through bitcasts to the same value.
222static bool isEquivBitcast(Value *X, Value *Y) {
223 return X->getType() == Y->getType() &&
225}
226
228 // Do not widen load if atomic/volatile or under asan/hwasan/memtag/tsan.
229 // The widened load may load data from dirty regions or create data races
230 // non-existent in the source.
231 if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
232 Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
234 return false;
235
236 // We are potentially transforming byte-sized (8-bit) memory accesses, so make
237 // sure we have all of our type-based constraints in place for this target.
238 Type *ScalarTy = Load->getType()->getScalarType();
239 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
240 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
241 if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
242 ScalarSize % 8 != 0)
243 return false;
244
245 return true;
246}
247
248bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
249 // Match insert into fixed vector of scalar value.
250 // TODO: Handle non-zero insert index.
251 Value *Scalar;
252 if (!match(&I,
254 return false;
255
256 // Optionally match an extract from another vector.
257 Value *X;
258 bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
259 if (!HasExtract)
260 X = Scalar;
261
262 auto *Load = dyn_cast<LoadInst>(X);
263 if (!canWidenLoad(Load, TTI))
264 return false;
265
266 Type *ScalarTy = Scalar->getType();
267 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
268 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
269
270 // Check safety of replacing the scalar load with a larger vector load.
271 // We use minimal alignment (maximum flexibility) because we only care about
272 // the dereferenceable region. When calculating cost and creating a new op,
273 // we may use a larger value based on alignment attributes.
274 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
275 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
276
277 unsigned MinVecNumElts = MinVectorSize / ScalarSize;
278 auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
279 unsigned OffsetEltIndex = 0;
280 Align Alignment = Load->getAlign();
281 // Ignore frees because the existing load proves that the object has not been
282 // freed. Allocations cannot shrink, so this is sufficient.
283 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1),
285 /*IgnoreFree=*/true)) {
286 // It is not safe to load directly from the pointer, but we can still peek
287 // through gep offsets and check if it safe to load from a base address with
288 // updated alignment. If it is, we can shuffle the element(s) into place
289 // after loading.
290 unsigned OffsetBitWidth = DL->getIndexTypeSizeInBits(SrcPtr->getType());
291 APInt Offset(OffsetBitWidth, 0);
293
294 // We want to shuffle the result down from a high element of a vector, so
295 // the offset must be positive.
296 if (Offset.isNegative())
297 return false;
298
299 // The offset must be a multiple of the scalar element to shuffle cleanly
300 // in the element's size.
301 uint64_t ScalarSizeInBytes = ScalarSize / 8;
302 if (Offset.urem(ScalarSizeInBytes) != 0)
303 return false;
304
305 // If we load MinVecNumElts, will our target element still be loaded?
306 APInt OffsetEltIndexAP = Offset.udiv(ScalarSizeInBytes);
307 if (OffsetEltIndexAP.uge(MinVecNumElts))
308 return false;
309 OffsetEltIndex = OffsetEltIndexAP.getZExtValue();
310
311 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1),
313 /*IgnoreFree=*/true))
314 return false;
315
316 // Update alignment with offset value. Note that the offset could be negated
317 // to more accurately represent "(new) SrcPtr - Offset = (old) SrcPtr", but
318 // negation does not change the result of the alignment calculation.
319 Alignment = commonAlignment(Alignment, Offset.getZExtValue());
320 }
321
322 // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
323 // Use the greater of the alignment on the load or its source pointer.
324 Alignment = std::max(SrcPtr->getPointerAlignment(*DL), Alignment);
325 Type *LoadTy = Load->getType();
326 unsigned AS = Load->getPointerAddressSpace();
327 InstructionCost OldCost =
328 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS, CostKind);
329 APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
330 OldCost +=
331 TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
332 /* Insert */ true, HasExtract, CostKind);
333
334 // New pattern: load VecPtr
335 InstructionCost NewCost =
336 TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS, CostKind);
337 // Optionally, we are shuffling the loaded vector element(s) into place.
338 // For the mask set everything but element 0 to undef to prevent poison from
339 // propagating from the extra loaded memory. This will also optionally
340 // shrink/grow the vector from the loaded size to the output size.
341 // We assume this operation has no cost in codegen if there was no offset.
342 // Note that we could use freeze to avoid poison problems, but then we might
343 // still need a shuffle to change the vector size.
344 auto *Ty = cast<FixedVectorType>(I.getType());
345 unsigned OutputNumElts = Ty->getNumElements();
346 SmallVector<int, 16> Mask(OutputNumElts, PoisonMaskElem);
347 assert(OffsetEltIndex < MinVecNumElts && "Address offset too big");
348 Mask[0] = OffsetEltIndex;
349 if (OffsetEltIndex)
350 NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, Ty, MinVecTy,
351 CostKind, Mask);
352
353 // We can aggressively convert to the vector form because the backend can
354 // invert this transform if it does not result in a performance win.
355 if (OldCost < NewCost || !NewCost.isValid())
356 return false;
357
358 // It is safe and potentially profitable to load a vector directly:
359 // inselt undef, load Scalar, 0 --> load VecPtr
360 Builder.SetInsertPoint(Load);
361 Value *CastedPtr =
362 Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Builder.getPtrTy(AS));
363 Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
364 VecLd = Builder.CreateShuffleVector(VecLd, Mask);
365
366 replaceValue(I, *VecLd);
367 ++NumVecLoad;
368 return true;
369}
370
371/// If we are loading a vector and then inserting it into a larger vector with
372/// undefined elements, try to load the larger vector and eliminate the insert.
373/// This removes a shuffle in IR and may allow combining of other loaded values.
374bool VectorCombine::widenSubvectorLoad(Instruction &I) {
375 // Match subvector insert of fixed vector.
376 auto *Shuf = cast<ShuffleVectorInst>(&I);
377 if (!Shuf->isIdentityWithPadding())
378 return false;
379
380 // Allow a non-canonical shuffle mask that is choosing elements from op1.
381 unsigned NumOpElts =
382 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
383 unsigned OpIndex = any_of(Shuf->getShuffleMask(), [&NumOpElts](int M) {
384 return M >= (int)(NumOpElts);
385 });
386
387 auto *Load = dyn_cast<LoadInst>(Shuf->getOperand(OpIndex));
388 if (!canWidenLoad(Load, TTI))
389 return false;
390
391 // We use minimal alignment (maximum flexibility) because we only care about
392 // the dereferenceable region. When calculating cost and creating a new op,
393 // we may use a larger value based on alignment attributes.
394 auto *Ty = cast<FixedVectorType>(I.getType());
395 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
396 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
397 Align Alignment = Load->getAlign();
398 // Ignore frees because the existing load proves that the object has not been
399 // freed. Allocations cannot shrink, so this is sufficient.
400 if (!isSafeToLoadUnconditionally(SrcPtr, Ty, Align(1),
402 /*IgnoreFree=*/true))
403 return false;
404
405 Alignment = std::max(SrcPtr->getPointerAlignment(*DL), Alignment);
406 Type *LoadTy = Load->getType();
407 unsigned AS = Load->getPointerAddressSpace();
408
409 // Original pattern: insert_subvector (load PtrOp)
410 // This conservatively assumes that the cost of a subvector insert into an
411 // undef value is 0. We could add that cost if the cost model accurately
412 // reflects the real cost of that operation.
413 InstructionCost OldCost =
414 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS, CostKind);
415
416 // New pattern: load PtrOp
417 InstructionCost NewCost =
418 TTI.getMemoryOpCost(Instruction::Load, Ty, Alignment, AS, CostKind);
419
420 // We can aggressively convert to the vector form because the backend can
421 // invert this transform if it does not result in a performance win.
422 if (OldCost < NewCost || !NewCost.isValid())
423 return false;
424
425 Builder.SetInsertPoint(Load);
426 Value *CastedPtr =
427 Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Builder.getPtrTy(AS));
428 Value *VecLd = Builder.CreateAlignedLoad(Ty, CastedPtr, Alignment);
429 replaceValue(I, *VecLd);
430 ++NumVecLoad;
431 return true;
432}
433
434/// Determine which, if any, of the inputs should be replaced by a shuffle
435/// followed by extract from a different index.
436ExtractElementInst *VectorCombine::getShuffleExtract(
437 ExtractElementInst *Ext0, ExtractElementInst *Ext1,
438 unsigned PreferredExtractIndex = InvalidIndex) const {
439 auto *Index0C = dyn_cast<ConstantInt>(Ext0->getIndexOperand());
440 auto *Index1C = dyn_cast<ConstantInt>(Ext1->getIndexOperand());
441 assert(Index0C && Index1C && "Expected constant extract indexes");
442
443 unsigned Index0 = Index0C->getZExtValue();
444 unsigned Index1 = Index1C->getZExtValue();
445
446 // If the extract indexes are identical, no shuffle is needed.
447 if (Index0 == Index1)
448 return nullptr;
449
450 Type *VecTy = Ext0->getVectorOperand()->getType();
451 assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
452 InstructionCost Cost0 =
453 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
454 InstructionCost Cost1 =
455 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
456
457 // If both costs are invalid no shuffle is needed
458 if (!Cost0.isValid() && !Cost1.isValid())
459 return nullptr;
460
461 // We are extracting from 2 different indexes, so one operand must be shuffled
462 // before performing a vector operation and/or extract. The more expensive
463 // extract will be replaced by a shuffle.
464 if (Cost0 > Cost1)
465 return Ext0;
466 if (Cost1 > Cost0)
467 return Ext1;
468
469 // If the costs are equal and there is a preferred extract index, shuffle the
470 // opposite operand.
471 if (PreferredExtractIndex == Index0)
472 return Ext1;
473 if (PreferredExtractIndex == Index1)
474 return Ext0;
475
476 // Otherwise, replace the extract with the higher index.
477 return Index0 > Index1 ? Ext0 : Ext1;
478}
479
480/// Compare the relative costs of 2 extracts followed by scalar operation vs.
481/// vector operation(s) followed by extract. Return true if the existing
482/// instructions are cheaper than a vector alternative. Otherwise, return false
483/// and if one of the extracts should be transformed to a shufflevector, set
484/// \p ConvertToShuffle to that extract instruction.
485bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
486 ExtractElementInst *Ext1,
487 const Instruction &I,
488 ExtractElementInst *&ConvertToShuffle,
489 unsigned PreferredExtractIndex) {
490 auto *Ext0IndexC = dyn_cast<ConstantInt>(Ext0->getIndexOperand());
491 auto *Ext1IndexC = dyn_cast<ConstantInt>(Ext1->getIndexOperand());
492 assert(Ext0IndexC && Ext1IndexC && "Expected constant extract indexes");
493
494 unsigned Opcode = I.getOpcode();
495 Value *Ext0Src = Ext0->getVectorOperand();
496 Value *Ext1Src = Ext1->getVectorOperand();
497 Type *ScalarTy = Ext0->getType();
498 auto *VecTy = cast<VectorType>(Ext0Src->getType());
499 InstructionCost ScalarOpCost, VectorOpCost;
500
501 // Get cost estimates for scalar and vector versions of the operation.
502 bool IsBinOp = Instruction::isBinaryOp(Opcode);
503 if (IsBinOp) {
504 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy, CostKind);
505 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy, CostKind);
506 } else {
507 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
508 "Expected a compare");
509 CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
510 ScalarOpCost = TTI.getCmpSelInstrCost(
511 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred, CostKind);
512 VectorOpCost = TTI.getCmpSelInstrCost(
513 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred, CostKind);
514 }
515
516 // Get cost estimates for the extract elements. These costs will factor into
517 // both sequences.
518 unsigned Ext0Index = Ext0IndexC->getZExtValue();
519 unsigned Ext1Index = Ext1IndexC->getZExtValue();
520
521 InstructionCost Extract0Cost =
522 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Ext0Index);
523 InstructionCost Extract1Cost =
524 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Ext1Index);
525
526 // A more expensive extract will always be replaced by a splat shuffle.
527 // For example, if Ext0 is more expensive:
528 // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
529 // extelt (opcode (splat V0, Ext0), V1), Ext1
530 // TODO: Evaluate whether that always results in lowest cost. Alternatively,
531 // check the cost of creating a broadcast shuffle and shuffling both
532 // operands to element 0.
533 unsigned BestExtIndex = Extract0Cost > Extract1Cost ? Ext0Index : Ext1Index;
534 unsigned BestInsIndex = Extract0Cost > Extract1Cost ? Ext1Index : Ext0Index;
535 InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
536
537 // Extra uses of the extracts mean that we include those costs in the
538 // vector total because those instructions will not be eliminated.
539 InstructionCost OldCost, NewCost;
540 if (Ext0Src == Ext1Src && Ext0Index == Ext1Index) {
541 // Handle a special case. If the 2 extracts are identical, adjust the
542 // formulas to account for that. The extra use charge allows for either the
543 // CSE'd pattern or an unoptimized form with identical values:
544 // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
545 bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
546 : !Ext0->hasOneUse() || !Ext1->hasOneUse();
547 OldCost = CheapExtractCost + ScalarOpCost;
548 NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
549 } else {
550 // Handle the general case. Each extract is actually a different value:
551 // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
552 OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
553 NewCost = VectorOpCost + CheapExtractCost +
554 !Ext0->hasOneUse() * Extract0Cost +
555 !Ext1->hasOneUse() * Extract1Cost;
556 }
557
558 ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
559 if (ConvertToShuffle) {
560 if (IsBinOp && Opts.disable_binop_extract_shuffle)
561 return true;
562
563 // If we are extracting from 2 different indexes, then one operand must be
564 // shuffled before performing the vector operation. The shuffle mask is
565 // poison except for 1 lane that is being translated to the remaining
566 // extraction lane. Therefore, it is a splat shuffle. Ex:
567 // ShufMask = { poison, poison, 0, poison }
568 // TODO: The cost model has an option for a "broadcast" shuffle
569 // (splat-from-element-0), but no option for a more general splat.
570 if (auto *FixedVecTy = dyn_cast<FixedVectorType>(VecTy)) {
571 SmallVector<int> ShuffleMask(FixedVecTy->getNumElements(),
573 ShuffleMask[BestInsIndex] = BestExtIndex;
575 VecTy, VecTy, CostKind, ShuffleMask, 0,
576 nullptr, {ConvertToShuffle});
577 } else {
579 VecTy, VecTy, CostKind, {}, 0, nullptr,
580 {ConvertToShuffle});
581 }
582 }
583
584 LLVM_DEBUG(dbgs() << "Found a binop of extractions: " << I << "\n OldCost: "
585 << OldCost << " vs NewCost: " << NewCost << "\n");
586
587 // Aggressively form a vector op if the cost is equal because the transform
588 // may enable further optimization.
589 // Codegen can reverse this transform (scalarize) if it was not profitable.
590 return OldCost < NewCost;
591}
592
593/// Create a shuffle that translates (shifts) 1 element from the input vector
594/// to a new element location.
595static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
596 unsigned NewIndex, IRBuilderBase &Builder) {
597 // The shuffle mask is poison except for 1 lane that is being translated
598 // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
599 // ShufMask = { 2, poison, poison, poison }
600 auto *VecTy = cast<FixedVectorType>(Vec->getType());
601 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem);
602 ShufMask[NewIndex] = OldIndex;
603 return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
604}
605
606/// Given an extract element instruction with constant index operand, shuffle
607/// the source vector (shift the scalar element) to a NewIndex for extraction.
608/// Return null if the input can be constant folded, so that we are not creating
609/// unnecessary instructions.
610static Value *translateExtract(ExtractElementInst *ExtElt, unsigned NewIndex,
611 IRBuilderBase &Builder) {
612 // Shufflevectors can only be created for fixed-width vectors.
613 Value *X = ExtElt->getVectorOperand();
614 if (!isa<FixedVectorType>(X->getType()))
615 return nullptr;
616
617 // If the extract can be constant-folded, this code is unsimplified. Defer
618 // to other passes to handle that.
619 Value *C = ExtElt->getIndexOperand();
620 assert(isa<ConstantInt>(C) && "Expected a constant index operand");
621 if (isa<Constant>(X))
622 return nullptr;
623
624 Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
625 NewIndex, Builder);
626 return Shuf;
627}
628
629/// Try to reduce extract element costs by converting scalar compares to vector
630/// compares followed by extract.
631/// cmp (ext0 V0, ExtIndex), (ext1 V1, ExtIndex)
632Value *VectorCombine::foldExtExtCmp(Value *V0, Value *V1, Value *ExtIndex,
633 Instruction &I) {
634 assert(isa<CmpInst>(&I) && "Expected a compare");
635
636 // cmp Pred (extelt V0, ExtIndex), (extelt V1, ExtIndex)
637 // --> extelt (cmp Pred V0, V1), ExtIndex
638 ++NumVecCmp;
639 CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
640 Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
641 return Builder.CreateExtractElement(VecCmp, ExtIndex, "foldExtExtCmp");
642}
643
644/// Try to reduce extract element costs by converting scalar binops to vector
645/// binops followed by extract.
646/// bo (ext0 V0, ExtIndex), (ext1 V1, ExtIndex)
647Value *VectorCombine::foldExtExtBinop(Value *V0, Value *V1, Value *ExtIndex,
648 Instruction &I) {
649 assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
650
651 // bo (extelt V0, ExtIndex), (extelt V1, ExtIndex)
652 // --> extelt (bo V0, V1), ExtIndex
653 ++NumVecBO;
654 Value *VecBO = Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0,
655 V1, "foldExtExtBinop");
656
657 // All IR flags are safe to back-propagate because any potential poison
658 // created in unused vector elements is discarded by the extract.
659 if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
660 VecBOInst->copyIRFlags(&I);
661
662 return Builder.CreateExtractElement(VecBO, ExtIndex, "foldExtExtBinop");
663}
664
665/// Match an instruction with extracted vector operands.
666bool VectorCombine::foldExtractExtract(Instruction &I) {
667 // It is not safe to transform things like div, urem, etc. because we may
668 // create undefined behavior when executing those on unknown vector elements.
670 return false;
671
672 Instruction *I0, *I1;
673 CmpPredicate Pred = CmpInst::BAD_ICMP_PREDICATE;
674 if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
676 return false;
677
678 Value *V0, *V1;
679 uint64_t C0, C1;
680 if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
682 V0->getType() != V1->getType())
683 return false;
684
685 // For fixed-width vectors, reject out-of-bounds extract indexes
686 if (auto *FixedVecTy = dyn_cast<FixedVectorType>(V0->getType())) {
687 unsigned NumElts = FixedVecTy->getNumElements();
688 if (C0 >= NumElts || C1 >= NumElts)
689 return false;
690 }
691
692 // If the scalar value 'I' is going to be re-inserted into a vector, then try
693 // to create an extract to that same element. The extract/insert can be
694 // reduced to a "select shuffle".
695 // TODO: If we add a larger pattern match that starts from an insert, this
696 // probably becomes unnecessary.
697 auto *Ext0 = cast<ExtractElementInst>(I0);
698 auto *Ext1 = cast<ExtractElementInst>(I1);
699 uint64_t InsertIndex = InvalidIndex;
700 if (I.hasOneUse())
701 match(I.user_back(),
702 m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
703
704 ExtractElementInst *ExtractToChange;
705 if (isExtractExtractCheap(Ext0, Ext1, I, ExtractToChange, InsertIndex))
706 return false;
707
708 Value *ExtOp0 = Ext0->getVectorOperand();
709 Value *ExtOp1 = Ext1->getVectorOperand();
710
711 if (ExtractToChange) {
712 unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
713 Value *NewExtOp =
714 translateExtract(ExtractToChange, CheapExtractIdx, Builder);
715 if (!NewExtOp)
716 return false;
717 if (ExtractToChange == Ext0)
718 ExtOp0 = NewExtOp;
719 else
720 ExtOp1 = NewExtOp;
721 }
722
723 Value *ExtIndex = ExtractToChange == Ext0 ? Ext1->getIndexOperand()
724 : Ext0->getIndexOperand();
726 ? foldExtExtCmp(ExtOp0, ExtOp1, ExtIndex, I)
727 : foldExtExtBinop(ExtOp0, ExtOp1, ExtIndex, I);
728 replaceValue(I, *NewExt);
729 return true;
730}
731
732/// Try to replace an extract + scalar fneg + insert with a vector fneg +
733/// shuffle.
734bool VectorCombine::foldInsExtFNeg(Instruction &I) {
735 // Match an insert (op (extract)) pattern.
736 Value *DstVec;
737 uint64_t ExtIdx, InsIdx;
738 Instruction *FNeg;
739 if (!match(&I, m_InsertElt(m_Value(DstVec), m_OneUse(m_Instruction(FNeg)),
740 m_ConstantInt(InsIdx))))
741 return false;
742
743 // Note: This handles the canonical fneg instruction and "fsub -0.0, X".
744 Value *SrcVec;
745 Instruction *Extract;
746 // TODO: Confirm whether m_FNegOrFSubNegZero is correct.
748 m_Instruction(Extract),
749 m_ExtractElt(m_Value(SrcVec), m_ConstantInt(ExtIdx))))))
750 return false;
751
752 auto *DstVecTy = cast<FixedVectorType>(DstVec->getType());
753 auto *DstVecScalarTy = DstVecTy->getScalarType();
754 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcVec->getType());
755 if (!SrcVecTy || DstVecScalarTy != SrcVecTy->getScalarType())
756 return false;
757
758 // Ignore if insert/extract index is out of bounds or destination vector has
759 // one element
760 unsigned NumDstElts = DstVecTy->getNumElements();
761 unsigned NumSrcElts = SrcVecTy->getNumElements();
762 if (ExtIdx > NumSrcElts || InsIdx >= NumDstElts || NumDstElts == 1)
763 return false;
764
765 // We are inserting the negated element into the same lane that we extracted
766 // from. This is equivalent to a select-shuffle that chooses all but the
767 // negated element from the destination vector.
768 SmallVector<int> Mask(NumDstElts);
769 std::iota(Mask.begin(), Mask.end(), 0);
770 Mask[InsIdx] = (ExtIdx % NumDstElts) + NumDstElts;
771 InstructionCost OldCost =
772 TTI.getArithmeticInstrCost(Instruction::FNeg, DstVecScalarTy, CostKind) +
773 TTI.getVectorInstrCost(I, DstVecTy, CostKind, InsIdx);
774
775 // If the extract has one use, it will be eliminated, so count it in the
776 // original cost. If it has more than one use, ignore the cost because it will
777 // be the same before/after.
778 if (Extract->hasOneUse())
779 OldCost += TTI.getVectorInstrCost(*Extract, SrcVecTy, CostKind, ExtIdx);
780
781 InstructionCost NewCost =
782 TTI.getArithmeticInstrCost(Instruction::FNeg, SrcVecTy, CostKind) +
784 DstVecTy, CostKind, Mask);
785
786 bool NeedLenChg = SrcVecTy->getNumElements() != NumDstElts;
787 // If the lengths of the two vectors are not equal,
788 // we need to add a length-change vector. Add this cost.
789 SmallVector<int> SrcMask;
790 if (NeedLenChg) {
791 SrcMask.assign(NumDstElts, PoisonMaskElem);
792 SrcMask[ExtIdx % NumDstElts] = ExtIdx;
794 DstVecTy, SrcVecTy, CostKind, SrcMask);
795 }
796
797 LLVM_DEBUG(dbgs() << "Found an insertion of (extract)fneg : " << I
798 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
799 << "\n");
800 if (NewCost > OldCost)
801 return false;
802
803 Value *NewShuf, *LenChgShuf = nullptr;
804 // insertelt DstVec, (fneg (extractelt SrcVec, Index)), Index
805 Value *VecFNeg = Builder.CreateFNegFMF(SrcVec, FNeg);
806 if (NeedLenChg) {
807 // shuffle DstVec, (shuffle (fneg SrcVec), poison, SrcMask), Mask
808 LenChgShuf = Builder.CreateShuffleVector(VecFNeg, SrcMask);
809 NewShuf = Builder.CreateShuffleVector(DstVec, LenChgShuf, Mask);
810 } else {
811 // shuffle DstVec, (fneg SrcVec), Mask
812 NewShuf = Builder.CreateShuffleVector(DstVec, VecFNeg, Mask);
813 }
814
815 replaceValue(I, *NewShuf);
816 return true;
817}
818
819/// Try to fold insert(binop(x,y),binop(a,b),idx)
820/// --> binop(insert(x,a,idx),insert(y,b,idx))
821bool VectorCombine::foldInsExtBinop(Instruction &I) {
822 BinaryOperator *VecBinOp, *SclBinOp;
824 if (!match(&I,
825 m_InsertElt(m_OneUse(m_BinOp(VecBinOp)),
826 m_OneUse(m_BinOp(SclBinOp)), m_ConstantInt(Index))))
827 return false;
828
829 // TODO: Add support for addlike etc.
830 Instruction::BinaryOps BinOpcode = VecBinOp->getOpcode();
831 if (BinOpcode != SclBinOp->getOpcode())
832 return false;
833
834 auto *ResultTy = dyn_cast<FixedVectorType>(I.getType());
835 if (!ResultTy)
836 return false;
837
838 // TODO: Attempt to detect m_ExtractElt for scalar operands and convert to
839 // shuffle?
840
841 InstructionCost OldCost = TTI.getInstructionCost(&I, CostKind) +
842 TTI.getInstructionCost(VecBinOp, CostKind) +
843 TTI.getInstructionCost(SclBinOp, CostKind);
844 InstructionCost NewCost =
845 TTI.getArithmeticInstrCost(BinOpcode, ResultTy, CostKind) +
846 TTI.getVectorInstrCost(Instruction::InsertElement, ResultTy, CostKind,
847 Index, VecBinOp->getOperand(0),
848 SclBinOp->getOperand(0)) +
849 TTI.getVectorInstrCost(Instruction::InsertElement, ResultTy, CostKind,
850 Index, VecBinOp->getOperand(1),
851 SclBinOp->getOperand(1));
852
853 LLVM_DEBUG(dbgs() << "Found an insertion of two binops: " << I
854 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
855 << "\n");
856 if (NewCost > OldCost)
857 return false;
858
859 Value *NewIns0 = Builder.CreateInsertElement(VecBinOp->getOperand(0),
860 SclBinOp->getOperand(0), Index);
861 Value *NewIns1 = Builder.CreateInsertElement(VecBinOp->getOperand(1),
862 SclBinOp->getOperand(1), Index);
863 Value *NewBO = Builder.CreateBinOp(BinOpcode, NewIns0, NewIns1);
864
865 // Intersect flags from the old binops.
866 if (auto *NewInst = dyn_cast<Instruction>(NewBO)) {
867 NewInst->copyIRFlags(VecBinOp);
868 NewInst->andIRFlags(SclBinOp);
869 }
870
871 replaceValue(I, *NewBO);
872 return true;
873}
874
875/// Match: bitop(castop(x), castop(y)) -> castop(bitop(x, y))
876/// Supports: bitcast, trunc, sext, zext
877bool VectorCombine::foldBitOpOfCastops(Instruction &I) {
878 // Check if this is a bitwise logic operation
879 auto *BinOp = dyn_cast<BinaryOperator>(&I);
880 if (!BinOp || !BinOp->isBitwiseLogicOp())
881 return false;
882
883 // Get the cast instructions
884 auto *LHSCast = dyn_cast<CastInst>(BinOp->getOperand(0));
885 auto *RHSCast = dyn_cast<CastInst>(BinOp->getOperand(1));
886 if (!LHSCast || !RHSCast) {
887 LLVM_DEBUG(dbgs() << " One or both operands are not cast instructions\n");
888 return false;
889 }
890
891 // Both casts must be the same type
892 Instruction::CastOps CastOpcode = LHSCast->getOpcode();
893 if (CastOpcode != RHSCast->getOpcode())
894 return false;
895
896 // Only handle supported cast operations
897 switch (CastOpcode) {
898 case Instruction::BitCast:
899 case Instruction::Trunc:
900 case Instruction::SExt:
901 case Instruction::ZExt:
902 break;
903 default:
904 return false;
905 }
906
907 Value *LHSSrc = LHSCast->getOperand(0);
908 Value *RHSSrc = RHSCast->getOperand(0);
909
910 // Source types must match
911 if (LHSSrc->getType() != RHSSrc->getType())
912 return false;
913
914 auto *SrcTy = LHSSrc->getType();
915 auto *DstTy = I.getType();
916 // Bitcasts can handle scalar/vector mixes, such as i16 -> <16 x i1>.
917 // Other casts only handle vector types with integer elements.
918 if (CastOpcode != Instruction::BitCast &&
919 (!isa<FixedVectorType>(SrcTy) || !isa<FixedVectorType>(DstTy)))
920 return false;
921
922 // Only integer scalar/vector values are legal for bitwise logic operations.
923 if (!SrcTy->getScalarType()->isIntegerTy() ||
924 !DstTy->getScalarType()->isIntegerTy())
925 return false;
926
927 // Cost Check :
928 // OldCost = bitlogic + 2*casts
929 // NewCost = bitlogic + cast
930
931 // Calculate specific costs for each cast with instruction context
933 CastOpcode, DstTy, SrcTy, TTI::CastContextHint::None, CostKind, LHSCast);
935 CastOpcode, DstTy, SrcTy, TTI::CastContextHint::None, CostKind, RHSCast);
936
937 InstructionCost OldCost =
938 TTI.getArithmeticInstrCost(BinOp->getOpcode(), DstTy, CostKind) +
939 LHSCastCost + RHSCastCost;
940
941 // For new cost, we can't provide an instruction (it doesn't exist yet)
942 InstructionCost GenericCastCost = TTI.getCastInstrCost(
943 CastOpcode, DstTy, SrcTy, TTI::CastContextHint::None, CostKind);
944
945 InstructionCost NewCost =
946 TTI.getArithmeticInstrCost(BinOp->getOpcode(), SrcTy, CostKind) +
947 GenericCastCost;
948
949 // Account for multi-use casts using specific costs
950 if (!LHSCast->hasOneUse())
951 NewCost += LHSCastCost;
952 if (!RHSCast->hasOneUse())
953 NewCost += RHSCastCost;
954
955 LLVM_DEBUG(dbgs() << "foldBitOpOfCastops: OldCost=" << OldCost
956 << " NewCost=" << NewCost << "\n");
957
958 if (NewCost > OldCost)
959 return false;
960
961 // Create the operation on the source type
962 Value *NewOp = Builder.CreateBinOp(BinOp->getOpcode(), LHSSrc, RHSSrc,
963 BinOp->getName() + ".inner");
964 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NewOp))
965 NewBinOp->copyIRFlags(BinOp);
966
967 // Create the cast operation directly to ensure we get a new instruction
968 Instruction *NewCast = CastInst::Create(CastOpcode, NewOp, I.getType());
969
970 // Preserve cast instruction flags
971 NewCast->copyIRFlags(LHSCast);
972 NewCast->andIRFlags(RHSCast);
973
974 // Insert the new instruction
975 Value *Result = Builder.Insert(NewCast);
976
977 replaceValue(I, *Result);
978 return true;
979}
980
981/// Match:
982// bitop(castop(x), C) ->
983// bitop(castop(x), castop(InvC)) ->
984// castop(bitop(x, InvC))
985// Supports: bitcast
986bool VectorCombine::foldBitOpOfCastConstant(Instruction &I) {
988 Constant *C;
989
990 // Check if this is a bitwise logic operation
992 return false;
993
994 // Get the cast instructions
995 auto *LHSCast = dyn_cast<CastInst>(LHS);
996 if (!LHSCast)
997 return false;
998
999 Instruction::CastOps CastOpcode = LHSCast->getOpcode();
1000
1001 // Only handle supported cast operations
1002 switch (CastOpcode) {
1003 case Instruction::BitCast:
1004 case Instruction::ZExt:
1005 case Instruction::SExt:
1006 case Instruction::Trunc:
1007 break;
1008 default:
1009 return false;
1010 }
1011
1012 Value *LHSSrc = LHSCast->getOperand(0);
1013
1014 auto *SrcTy = LHSSrc->getType();
1015 auto *DstTy = I.getType();
1016 // Bitcasts can handle scalar/vector mixes, such as i16 -> <16 x i1>.
1017 // Other casts only handle vector types with integer elements.
1018 if (CastOpcode != Instruction::BitCast &&
1019 (!isa<FixedVectorType>(SrcTy) || !isa<FixedVectorType>(DstTy)))
1020 return false;
1021
1022 // Only integer scalar/vector values are legal for bitwise logic operations.
1023 if (!SrcTy->getScalarType()->isIntegerTy() ||
1024 !DstTy->getScalarType()->isIntegerTy())
1025 return false;
1026
1027 // Find the constant InvC, such that castop(InvC) equals to C.
1028 PreservedCastFlags RHSFlags;
1029 Constant *InvC = getLosslessInvCast(C, SrcTy, CastOpcode, *DL, &RHSFlags);
1030 if (!InvC)
1031 return false;
1032
1033 // Cost Check :
1034 // OldCost = bitlogic + cast
1035 // NewCost = bitlogic + cast
1036
1037 // Calculate specific costs for each cast with instruction context
1038 InstructionCost LHSCastCost = TTI.getCastInstrCost(
1039 CastOpcode, DstTy, SrcTy, TTI::CastContextHint::None, CostKind, LHSCast);
1040
1041 InstructionCost OldCost =
1042 TTI.getArithmeticInstrCost(I.getOpcode(), DstTy, CostKind) + LHSCastCost;
1043
1044 // For new cost, we can't provide an instruction (it doesn't exist yet)
1045 InstructionCost GenericCastCost = TTI.getCastInstrCost(
1046 CastOpcode, DstTy, SrcTy, TTI::CastContextHint::None, CostKind);
1047
1048 InstructionCost NewCost =
1049 TTI.getArithmeticInstrCost(I.getOpcode(), SrcTy, CostKind) +
1050 GenericCastCost;
1051
1052 // Account for multi-use casts using specific costs
1053 if (!LHSCast->hasOneUse())
1054 NewCost += LHSCastCost;
1055
1056 LLVM_DEBUG(dbgs() << "foldBitOpOfCastConstant: OldCost=" << OldCost
1057 << " NewCost=" << NewCost << "\n");
1058
1059 if (NewCost > OldCost)
1060 return false;
1061
1062 // Create the operation on the source type
1063 Value *NewOp = Builder.CreateBinOp((Instruction::BinaryOps)I.getOpcode(),
1064 LHSSrc, InvC, I.getName() + ".inner");
1065 if (auto *NewBinOp = dyn_cast<BinaryOperator>(NewOp))
1066 NewBinOp->copyIRFlags(&I);
1067
1068 // Create the cast operation directly to ensure we get a new instruction
1069 Instruction *NewCast = CastInst::Create(CastOpcode, NewOp, I.getType());
1070
1071 // Preserve cast instruction flags
1072 if (RHSFlags.NNeg)
1073 NewCast->setNonNeg();
1074 if (RHSFlags.NUW)
1075 NewCast->setHasNoUnsignedWrap();
1076 if (RHSFlags.NSW)
1077 NewCast->setHasNoSignedWrap();
1078
1079 NewCast->andIRFlags(LHSCast);
1080
1081 // Insert the new instruction
1082 Value *Result = Builder.Insert(NewCast);
1083
1084 replaceValue(I, *Result);
1085 return true;
1086}
1087
1088/// If this is a bitcast of a shuffle, try to bitcast the source vector to the
1089/// destination type followed by shuffle. This can enable further transforms by
1090/// moving bitcasts or shuffles together.
1091bool VectorCombine::foldBitcastShuffle(Instruction &I) {
1092 Value *V0, *V1;
1093 ArrayRef<int> Mask;
1094 if (!match(&I, m_BitCast(m_OneUse(
1095 m_Shuffle(m_Value(V0), m_Value(V1), m_Mask(Mask))))))
1096 return false;
1097
1098 // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
1099 // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
1100 // mask for scalable type is a splat or not.
1101 // 2) Disallow non-vector casts.
1102 // TODO: We could allow any shuffle.
1103 auto *DestTy = dyn_cast<FixedVectorType>(I.getType());
1104 auto *SrcTy = dyn_cast<FixedVectorType>(V0->getType());
1105 if (!DestTy || !SrcTy)
1106 return false;
1107
1108 unsigned DestEltSize = DestTy->getScalarSizeInBits();
1109 unsigned SrcEltSize = SrcTy->getScalarSizeInBits();
1110 if (SrcTy->getPrimitiveSizeInBits() % DestEltSize != 0)
1111 return false;
1112
1113 bool IsUnary = isa<UndefValue>(V1);
1114
1115 // For binary shuffles, only fold bitcast(shuffle(X,Y))
1116 // if it won't increase the number of bitcasts.
1117 if (!IsUnary) {
1120 if (!(BCTy0 && BCTy0->getElementType() == DestTy->getElementType()) &&
1121 !(BCTy1 && BCTy1->getElementType() == DestTy->getElementType()))
1122 return false;
1123 }
1124
1125 SmallVector<int, 16> NewMask;
1126 if (DestEltSize <= SrcEltSize) {
1127 // The bitcast is from wide to narrow/equal elements. The shuffle mask can
1128 // always be expanded to the equivalent form choosing narrower elements.
1129 if (SrcEltSize % DestEltSize != 0)
1130 return false;
1131 unsigned ScaleFactor = SrcEltSize / DestEltSize;
1132 narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
1133 } else {
1134 // The bitcast is from narrow elements to wide elements. The shuffle mask
1135 // must choose consecutive elements to allow casting first.
1136 if (DestEltSize % SrcEltSize != 0)
1137 return false;
1138 unsigned ScaleFactor = DestEltSize / SrcEltSize;
1139 if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
1140 return false;
1141 }
1142
1143 // Bitcast the shuffle src - keep its original width but using the destination
1144 // scalar type.
1145 unsigned NumSrcElts = SrcTy->getPrimitiveSizeInBits() / DestEltSize;
1146 auto *NewShuffleTy =
1147 FixedVectorType::get(DestTy->getScalarType(), NumSrcElts);
1148 auto *OldShuffleTy =
1149 FixedVectorType::get(SrcTy->getScalarType(), Mask.size());
1150 unsigned NumOps = IsUnary ? 1 : 2;
1151
1152 // The new shuffle must not cost more than the old shuffle.
1156
1157 InstructionCost NewCost =
1158 TTI.getShuffleCost(SK, DestTy, NewShuffleTy, CostKind, NewMask) +
1159 (NumOps * TTI.getCastInstrCost(Instruction::BitCast, NewShuffleTy, SrcTy,
1160 TargetTransformInfo::CastContextHint::None,
1161 CostKind));
1162 InstructionCost OldCost =
1163 TTI.getShuffleCost(SK, OldShuffleTy, SrcTy, CostKind, Mask) +
1164 TTI.getCastInstrCost(Instruction::BitCast, DestTy, OldShuffleTy,
1165 TargetTransformInfo::CastContextHint::None,
1166 CostKind);
1167
1168 LLVM_DEBUG(dbgs() << "Found a bitcasted shuffle: " << I << "\n OldCost: "
1169 << OldCost << " vs NewCost: " << NewCost << "\n");
1170
1171 if (NewCost > OldCost || !NewCost.isValid())
1172 return false;
1173
1174 // bitcast (shuf V0, V1, MaskC) --> shuf (bitcast V0), (bitcast V1), MaskC'
1175 ++NumShufOfBitcast;
1176 Value *CastV0 = Builder.CreateBitCast(peekThroughBitcasts(V0), NewShuffleTy);
1177 Value *CastV1 = Builder.CreateBitCast(peekThroughBitcasts(V1), NewShuffleTy);
1178 Value *Shuf = Builder.CreateShuffleVector(CastV0, CastV1, NewMask);
1179 replaceValue(I, *Shuf);
1180 return true;
1181}
1182
1183/// Match a vector op/compare/intrinsic with at least one
1184/// inserted scalar operand and convert to scalar op/cmp/intrinsic followed
1185/// by insertelement.
1186bool VectorCombine::scalarizeOpOrCmp(Instruction &I) {
1187 auto *UO = dyn_cast<UnaryOperator>(&I);
1188 auto *BO = dyn_cast<BinaryOperator>(&I);
1189 auto *CI = dyn_cast<CmpInst>(&I);
1190 auto *II = dyn_cast<IntrinsicInst>(&I);
1191 if (!UO && !BO && !CI && !II)
1192 return false;
1193
1194 // TODO: Allow intrinsics with different argument types
1195 if (II) {
1196 if (!isTriviallyVectorizable(II->getIntrinsicID()))
1197 return false;
1198 for (auto [Idx, Arg] : enumerate(II->args()))
1199 if (Arg->getType() != II->getType() &&
1200 !isVectorIntrinsicWithScalarOpAtArg(II->getIntrinsicID(), Idx, &TTI))
1201 return false;
1202 }
1203
1204 // Do not convert the vector condition of a vector select into a scalar
1205 // condition. That may cause problems for codegen because of differences in
1206 // boolean formats and register-file transfers.
1207 // TODO: Can we account for that in the cost model?
1208 if (CI)
1209 for (User *U : I.users())
1210 if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
1211 return false;
1212
1213 // Match constant vectors or scalars being inserted into constant vectors:
1214 // vec_op [VecC0 | (inselt VecC0, V0, Index)], ...
1215 SmallVector<Value *> VecCs, ScalarOps;
1216 std::optional<uint64_t> Index;
1217
1218 auto Ops = II ? II->args() : I.operands();
1219 for (auto [OpNum, Op] : enumerate(Ops)) {
1220 Constant *VecC;
1221 Value *V;
1222 uint64_t InsIdx = 0;
1223 if (match(Op.get(), m_InsertElt(m_Constant(VecC), m_Value(V),
1224 m_ConstantInt(InsIdx)))) {
1225 // Bail if any inserts are out of bounds.
1226 VectorType *OpTy = cast<VectorType>(Op->getType());
1227 if (OpTy->getElementCount().getKnownMinValue() <= InsIdx)
1228 return false;
1229 // All inserts must have the same index.
1230 // TODO: Deal with mismatched index constants and variable indexes?
1231 if (!Index)
1232 Index = InsIdx;
1233 else if (InsIdx != *Index)
1234 return false;
1235 VecCs.push_back(VecC);
1236 ScalarOps.push_back(V);
1237 } else if (II && isVectorIntrinsicWithScalarOpAtArg(II->getIntrinsicID(),
1238 OpNum, &TTI)) {
1239 VecCs.push_back(Op.get());
1240 ScalarOps.push_back(Op.get());
1241 } else if (match(Op.get(), m_Constant(VecC))) {
1242 VecCs.push_back(VecC);
1243 ScalarOps.push_back(nullptr);
1244 } else {
1245 return false;
1246 }
1247 }
1248
1249 // Bail if all operands are constant.
1250 if (!Index.has_value())
1251 return false;
1252
1253 VectorType *VecTy = cast<VectorType>(I.getType());
1254 Type *ScalarTy = VecTy->getScalarType();
1255 assert(VecTy->isVectorTy() &&
1256 (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
1257 ScalarTy->isPointerTy()) &&
1258 "Unexpected types for insert element into binop or cmp");
1259
1260 unsigned Opcode = I.getOpcode();
1261 InstructionCost ScalarOpCost, VectorOpCost;
1262 if (CI) {
1263 CmpInst::Predicate Pred = CI->getPredicate();
1264 ScalarOpCost = TTI.getCmpSelInstrCost(
1265 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred, CostKind);
1266 VectorOpCost = TTI.getCmpSelInstrCost(
1267 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred, CostKind);
1268 } else if (UO || BO) {
1269 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy, CostKind);
1270 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy, CostKind);
1271 } else {
1272 IntrinsicCostAttributes ScalarICA(
1273 II->getIntrinsicID(), ScalarTy,
1274 SmallVector<Type *>(II->arg_size(), ScalarTy));
1275 ScalarOpCost = TTI.getIntrinsicInstrCost(ScalarICA, CostKind);
1276 IntrinsicCostAttributes VectorICA(
1277 II->getIntrinsicID(), VecTy,
1278 SmallVector<Type *>(II->arg_size(), VecTy));
1279 VectorOpCost = TTI.getIntrinsicInstrCost(VectorICA, CostKind);
1280 }
1281
1282 // Fold the vector constants in the original vectors into a new base vector to
1283 // get more accurate cost modelling.
1284 Value *NewVecC = nullptr;
1285 if (CI)
1286 NewVecC = simplifyCmpInst(CI->getPredicate(), VecCs[0], VecCs[1], SQ);
1287 else if (UO)
1288 NewVecC =
1289 simplifyUnOp(UO->getOpcode(), VecCs[0], UO->getFastMathFlags(), SQ);
1290 else if (BO)
1291 NewVecC = simplifyBinOp(BO->getOpcode(), VecCs[0], VecCs[1], SQ);
1292 else if (II)
1293 NewVecC = simplifyCall(II, II->getCalledOperand(), VecCs, SQ);
1294
1295 if (!NewVecC)
1296 return false;
1297
1298 // Get cost estimate for the insert element. This cost will factor into
1299 // both sequences.
1300 InstructionCost OldCost = VectorOpCost;
1301 InstructionCost NewCost =
1302 ScalarOpCost + TTI.getVectorInstrCost(Instruction::InsertElement, VecTy,
1303 CostKind, *Index, NewVecC);
1304
1305 for (auto [Idx, Op, VecC, Scalar] : enumerate(Ops, VecCs, ScalarOps)) {
1306 if (!Scalar || (II && isVectorIntrinsicWithScalarOpAtArg(
1307 II->getIntrinsicID(), Idx, &TTI)))
1308 continue;
1310 Instruction::InsertElement, VecTy, CostKind, *Index, VecC, Scalar);
1311 OldCost += InsertCost;
1312 NewCost += !Op->hasOneUse() * InsertCost;
1313 }
1314
1315 // We want to scalarize unless the vector variant actually has lower cost.
1316 if (OldCost < NewCost || !NewCost.isValid())
1317 return false;
1318
1319 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
1320 // inselt NewVecC, (scalar_op V0, V1), Index
1321 if (CI)
1322 ++NumScalarCmp;
1323 else if (UO || BO)
1324 ++NumScalarOps;
1325 else
1326 ++NumScalarIntrinsic;
1327
1328 // For constant cases, extract the scalar element, this should constant fold.
1329 for (auto [OpIdx, Scalar, VecC] : enumerate(ScalarOps, VecCs))
1330 if (!Scalar)
1331 ScalarOps[OpIdx] = ConstantExpr::getExtractElement(
1332 cast<Constant>(VecC), Builder.getInt64(*Index));
1333
1334 Value *Scalar;
1335 // We need to pass the flags during the creation of instructions. Constant
1336 // folding might remove the instructions, so post setting the flags might
1337 // pollute the later instructions.
1338 if (CI) {
1339 if (FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I)) {
1340 Scalar = Builder.CreateFCmpFMF(CI->getPredicate(), ScalarOps[0],
1341 ScalarOps[1], FPMO->getFastMathFlags(),
1342 CI->getName() + ".scalar");
1343 } else {
1344 Scalar = Builder.CreateICmp(CI->getPredicate(), ScalarOps[0],
1345 ScalarOps[1], CI->getName() + ".scalar");
1346 }
1347 } else if (UO) {
1348 Scalar = Builder.CreateUnOpFMF(UO->getOpcode(), ScalarOps[0], UO,
1349 UO->getName() + ".scalar");
1350 } else if (BO) {
1351 if (OverflowingBinaryOperator *OBO =
1353 Scalar = Builder.CreateNoWrapBinOp(
1354 BO->getOpcode(), ScalarOps[0], ScalarOps[1], OBO->hasNoUnsignedWrap(),
1355 OBO->hasNoSignedWrap(), BO->getName() + ".scalar");
1356 } else if (PossiblyDisjointInst *PDI = dyn_cast<PossiblyDisjointInst>(&I)) {
1357 Scalar = Builder.CreateOr(ScalarOps[0], ScalarOps[1],
1358 BO->getName() + ".scalar", PDI->isDisjoint());
1359 } else if (PossiblyExactOperator *PEO =
1361 Scalar =
1362 Builder.CreateExactBinOp(BO->getOpcode(), ScalarOps[0], ScalarOps[1],
1363 PEO->isExact(), BO->getName() + ".scalar");
1364 } else if (FPMathOperator *FPMO = dyn_cast<FPMathOperator>(&I)) {
1365 Scalar = Builder.CreateBinOpFMF(BO->getOpcode(), ScalarOps[0],
1366 ScalarOps[1], FPMO->getFastMathFlags(),
1367 BO->getName() + ".scalar");
1368 } else {
1369 Scalar = Builder.CreateBinOp(BO->getOpcode(), ScalarOps[0], ScalarOps[1],
1370 BO->getName() + ".scalar");
1371 }
1372 } else {
1373 FastMathFlags FMF;
1374 if (auto *FPMO = dyn_cast<FPMathOperator>(&I))
1375 FMF = FPMO->getFastMathFlags();
1376 Scalar = Builder.CreateIntrinsic(ScalarTy, II->getIntrinsicID(), ScalarOps,
1377 FMF, II->getName() + ".scalar");
1378 }
1379
1380 Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, *Index);
1381 replaceValue(I, *Insert);
1382 return true;
1383}
1384
1385/// Try to combine a scalar binop + 2 scalar compares of extracted elements of
1386/// a vector into vector operations followed by extract. Note: The SLP pass
1387/// may miss this pattern because of implementation problems.
1388bool VectorCombine::foldExtractedCmps(Instruction &I) {
1389 auto *BI = dyn_cast<BinaryOperator>(&I);
1390
1391 // We are looking for a scalar binop of booleans.
1392 // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
1393 if (!BI || !I.getType()->isIntegerTy(1))
1394 return false;
1395
1396 // The compare predicates should match, and each compare should have a
1397 // constant operand.
1398 Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
1399 Instruction *I0, *I1;
1400 Constant *C0, *C1;
1401 CmpPredicate P0, P1;
1402 if (!match(B0, m_Cmp(P0, m_Instruction(I0), m_Constant(C0))) ||
1403 !match(B1, m_Cmp(P1, m_Instruction(I1), m_Constant(C1))))
1404 return false;
1405
1406 auto MatchingPred = CmpPredicate::getMatching(P0, P1);
1407 if (!MatchingPred)
1408 return false;
1409
1410 // The compare operands must be extracts of the same vector with constant
1411 // extract indexes.
1412 Value *X;
1413 uint64_t Index0, Index1;
1414 if (!match(I0, m_ExtractElt(m_Value(X), m_ConstantInt(Index0))) ||
1415 !match(I1, m_ExtractElt(m_Specific(X), m_ConstantInt(Index1))))
1416 return false;
1417
1418 auto *Ext0 = cast<ExtractElementInst>(I0);
1419 auto *Ext1 = cast<ExtractElementInst>(I1);
1420 ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1, CostKind);
1421 if (!ConvertToShuf)
1422 return false;
1423 assert((ConvertToShuf == Ext0 || ConvertToShuf == Ext1) &&
1424 "Unknown ExtractElementInst");
1425
1426 // The original scalar pattern is:
1427 // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
1428 CmpInst::Predicate Pred = *MatchingPred;
1429 unsigned CmpOpcode =
1430 CmpInst::isFPPredicate(Pred) ? Instruction::FCmp : Instruction::ICmp;
1431 auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
1432 if (!VecTy)
1433 return false;
1434
1435 if (Index0 >= VecTy->getNumElements() || Index1 >= VecTy->getNumElements())
1436 return false;
1437
1438 InstructionCost Ext0Cost =
1439 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
1440 InstructionCost Ext1Cost =
1441 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
1443 CmpOpcode, I0->getType(), CmpInst::makeCmpResultType(I0->getType()), Pred,
1444 CostKind);
1445
1446 InstructionCost OldCost =
1447 Ext0Cost + Ext1Cost + CmpCost * 2 +
1448 TTI.getArithmeticInstrCost(I.getOpcode(), I.getType(), CostKind);
1449
1450 // The proposed vector pattern is:
1451 // vcmp = cmp Pred X, VecC
1452 // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
1453 int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
1454 int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
1457 CmpOpcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred, CostKind);
1458 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem);
1459 ShufMask[CheapIndex] = ExpensiveIndex;
1461 CmpTy, CostKind, ShufMask);
1462 NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy, CostKind);
1463 NewCost += TTI.getVectorInstrCost(*Ext0, CmpTy, CostKind, CheapIndex);
1464 NewCost += Ext0->hasOneUse() ? 0 : Ext0Cost;
1465 NewCost += Ext1->hasOneUse() ? 0 : Ext1Cost;
1466
1467 // Aggressively form vector ops if the cost is equal because the transform
1468 // may enable further optimization.
1469 // Codegen can reverse this transform (scalarize) if it was not profitable.
1470 if (OldCost < NewCost || !NewCost.isValid())
1471 return false;
1472
1473 // Create a vector constant from the 2 scalar constants.
1474 SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
1475 PoisonValue::get(VecTy->getElementType()));
1476 CmpC[Index0] = C0;
1477 CmpC[Index1] = C1;
1478 Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
1479 Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
1480 Value *LHS = ConvertToShuf == Ext0 ? Shuf : VCmp;
1481 Value *RHS = ConvertToShuf == Ext0 ? VCmp : Shuf;
1482 Value *VecLogic = Builder.CreateBinOp(BI->getOpcode(), LHS, RHS);
1483 Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
1484 replaceValue(I, *NewExt);
1485 ++NumVecCmpBO;
1486 return true;
1487}
1488
1489/// Try to fold scalar selects that select between extracted elements and zero
1490/// into extracting from a vector select. This is rooted at the bitcast.
1491///
1492/// This pattern arises when a vector is bitcast to a smaller element type,
1493/// elements are extracted, and then conditionally selected with zero:
1494///
1495/// %bc = bitcast <4 x i32> %src to <16 x i8>
1496/// %e0 = extractelement <16 x i8> %bc, i32 0
1497/// %s0 = select i1 %cond, i8 %e0, i8 0
1498/// %e1 = extractelement <16 x i8> %bc, i32 1
1499/// %s1 = select i1 %cond, i8 %e1, i8 0
1500/// ...
1501///
1502/// Transforms to:
1503/// %sel = select i1 %cond, <4 x i32> %src, <4 x i32> zeroinitializer
1504/// %bc = bitcast <4 x i32> %sel to <16 x i8>
1505/// %e0 = extractelement <16 x i8> %bc, i32 0
1506/// %e1 = extractelement <16 x i8> %bc, i32 1
1507/// ...
1508///
1509/// This is profitable because vector select on wider types produces fewer
1510/// select/cndmask instructions than scalar selects on each element.
1511bool VectorCombine::foldSelectsFromBitcast(Instruction &I) {
1512 auto *BC = dyn_cast<BitCastInst>(&I);
1513 if (!BC)
1514 return false;
1515
1516 FixedVectorType *SrcVecTy = dyn_cast<FixedVectorType>(BC->getSrcTy());
1517 FixedVectorType *DstVecTy = dyn_cast<FixedVectorType>(BC->getDestTy());
1518 if (!SrcVecTy || !DstVecTy)
1519 return false;
1520
1521 // Source must be 32-bit or 64-bit elements, destination must be smaller
1522 // integer elements. Zero in all these types is all-bits-zero.
1523 Type *SrcEltTy = SrcVecTy->getElementType();
1524 Type *DstEltTy = DstVecTy->getElementType();
1525 unsigned SrcEltBits = SrcEltTy->getPrimitiveSizeInBits();
1526 unsigned DstEltBits = DstEltTy->getPrimitiveSizeInBits();
1527
1528 if (SrcEltBits != 32 && SrcEltBits != 64)
1529 return false;
1530
1531 if (!DstEltTy->isIntegerTy() || DstEltBits >= SrcEltBits)
1532 return false;
1533
1534 // Check profitability using TTI before collecting users.
1535 Type *CondTy = CmpInst::makeCmpResultType(DstEltTy);
1536 Type *VecCondTy = CmpInst::makeCmpResultType(SrcVecTy);
1537
1538 InstructionCost ScalarSelCost =
1539 TTI.getCmpSelInstrCost(Instruction::Select, DstEltTy, CondTy,
1540 CmpInst::BAD_ICMP_PREDICATE, CostKind);
1541 InstructionCost VecSelCost =
1542 TTI.getCmpSelInstrCost(Instruction::Select, SrcVecTy, VecCondTy,
1543 CmpInst::BAD_ICMP_PREDICATE, CostKind);
1544
1545 // We need at least this many selects for vectorization to be profitable.
1546 // VecSelCost < ScalarSelCost * NumSelects => NumSelects > VecSelCost /
1547 // ScalarSelCost
1548 if (!ScalarSelCost.isValid() || ScalarSelCost == 0)
1549 return false;
1550
1551 unsigned MinSelects = (VecSelCost.getValue() / ScalarSelCost.getValue()) + 1;
1552
1553 // Quick check: if bitcast doesn't have enough users, bail early.
1554 if (!BC->hasNUsesOrMore(MinSelects))
1555 return false;
1556
1557 // Collect all select users that match the pattern, grouped by condition.
1558 // Pattern: select i1 %cond, (extractelement %bc, idx), 0
1559 DenseMap<Value *, SmallVector<SelectInst *, 8>> CondToSelects;
1560
1561 for (User *U : BC->users()) {
1562 auto *Ext = dyn_cast<ExtractElementInst>(U);
1563 if (!Ext)
1564 continue;
1565
1566 for (User *ExtUser : Ext->users()) {
1567 Value *Cond;
1568 // Match: select i1 %cond, %ext, 0
1569 if (match(ExtUser, m_Select(m_Value(Cond), m_Specific(Ext), m_Zero())) &&
1570 Cond->getType()->isIntegerTy(1))
1571 CondToSelects[Cond].push_back(cast<SelectInst>(ExtUser));
1572 }
1573 }
1574
1575 if (CondToSelects.empty())
1576 return false;
1577
1578 bool MadeChange = false;
1579 Value *SrcVec = BC->getOperand(0);
1580
1581 // Process each group of selects with the same condition.
1582 for (auto [Cond, Selects] : CondToSelects) {
1583 // Only profitable if vector select cost < total scalar select cost.
1584 if (Selects.size() < MinSelects) {
1585 LLVM_DEBUG(dbgs() << "VectorCombine: foldSelectsFromBitcast not "
1586 << "profitable (VecCost=" << VecSelCost
1587 << ", ScalarCost=" << ScalarSelCost
1588 << ", NumSelects=" << Selects.size() << ")\n");
1589 continue;
1590 }
1591
1592 // Create the vector select and bitcast once for this condition.
1593 auto InsertPt = std::next(BC->getIterator());
1594
1595 if (auto *CondInst = dyn_cast<Instruction>(Cond))
1596 if (DT.dominates(BC, CondInst))
1597 InsertPt = std::next(CondInst->getIterator());
1598
1599 Builder.SetInsertPoint(InsertPt);
1600 Value *VecSel =
1601 Builder.CreateSelect(Cond, SrcVec, Constant::getNullValue(SrcVecTy));
1602 Value *NewBC = Builder.CreateBitCast(VecSel, DstVecTy);
1603
1604 // Replace each scalar select with an extract from the new bitcast.
1605 for (SelectInst *Sel : Selects) {
1606 auto *Ext = cast<ExtractElementInst>(Sel->getTrueValue());
1607 Value *Idx = Ext->getIndexOperand();
1608
1609 Builder.SetInsertPoint(Sel);
1610 Value *NewExt = Builder.CreateExtractElement(NewBC, Idx);
1611 replaceValue(*Sel, *NewExt);
1612 MadeChange = true;
1613 }
1614
1615 LLVM_DEBUG(dbgs() << "VectorCombine: folded " << Selects.size()
1616 << " selects into vector select\n");
1617 }
1618
1619 return MadeChange;
1620}
1621
1623 TTI::TargetCostKind CostKind,
1624 const TargetTransformInfo &TTI,
1625 InstructionCost &CostBeforeReduction,
1626 InstructionCost &CostAfterReduction) {
1627 Instruction *Op0, *Op1;
1628 auto *RedOp = dyn_cast<Instruction>(II.getOperand(0));
1629 auto *VecRedTy = cast<VectorType>(II.getOperand(0)->getType());
1630 unsigned ReductionOpc =
1631 getArithmeticReductionInstruction(II.getIntrinsicID());
1632 if (RedOp && match(RedOp, m_ZExtOrSExt(m_Value()))) {
1633 bool IsUnsigned = isa<ZExtInst>(RedOp);
1634 auto *ExtType = cast<VectorType>(RedOp->getOperand(0)->getType());
1635
1636 CostBeforeReduction =
1637 TTI.getCastInstrCost(RedOp->getOpcode(), VecRedTy, ExtType,
1638 TTI::CastContextHint::None, CostKind, RedOp);
1639 CostAfterReduction =
1640 TTI.getExtendedReductionCost(ReductionOpc, IsUnsigned, II.getType(),
1641 ExtType, FastMathFlags(), CostKind);
1642 return;
1643 }
1644 if (RedOp && II.getIntrinsicID() == Intrinsic::vector_reduce_add &&
1645 match(RedOp,
1647 match(Op0, m_ZExtOrSExt(m_Value())) &&
1648 Op0->getOpcode() == Op1->getOpcode() &&
1649 Op0->getOperand(0)->getType() == Op1->getOperand(0)->getType() &&
1650 (Op0->getOpcode() == RedOp->getOpcode() || Op0 == Op1)) {
1651 // Matched reduce.add(ext(mul(ext(A), ext(B)))
1652 bool IsUnsigned = isa<ZExtInst>(Op0);
1653 auto *ExtType = cast<VectorType>(Op0->getOperand(0)->getType());
1654 VectorType *MulType = VectorType::get(Op0->getType(), VecRedTy);
1655
1656 InstructionCost ExtCost =
1657 TTI.getCastInstrCost(Op0->getOpcode(), MulType, ExtType,
1658 TTI::CastContextHint::None, CostKind, Op0);
1659 InstructionCost MulCost =
1660 TTI.getArithmeticInstrCost(Instruction::Mul, MulType, CostKind);
1661 InstructionCost Ext2Cost =
1662 TTI.getCastInstrCost(RedOp->getOpcode(), VecRedTy, MulType,
1663 TTI::CastContextHint::None, CostKind, RedOp);
1664
1665 CostBeforeReduction = ExtCost * 2 + MulCost + Ext2Cost;
1666 CostAfterReduction = TTI.getMulAccReductionCost(
1667 IsUnsigned, ReductionOpc, II.getType(), ExtType, CostKind);
1668 return;
1669 }
1670 CostAfterReduction = TTI.getArithmeticReductionCost(ReductionOpc, VecRedTy,
1671 std::nullopt, CostKind);
1672}
1673
1674bool VectorCombine::foldBinopOfReductions(Instruction &I) {
1675 Instruction::BinaryOps BinOpOpc = cast<BinaryOperator>(&I)->getOpcode();
1676 Intrinsic::ID ReductionIID = getReductionForBinop(BinOpOpc);
1677 if (BinOpOpc == Instruction::Sub)
1678 ReductionIID = Intrinsic::vector_reduce_add;
1679 if (ReductionIID == Intrinsic::not_intrinsic)
1680 return false;
1681 // FP reductions have a start-value operand that this fold doesn't handle.
1682 if (ReductionIID == Intrinsic::vector_reduce_fadd ||
1683 ReductionIID == Intrinsic::vector_reduce_fmul)
1684 return false;
1685
1686 auto checkIntrinsicAndGetItsArgument = [](Value *V,
1687 Intrinsic::ID IID) -> Value * {
1688 auto *II = dyn_cast<IntrinsicInst>(V);
1689 if (!II)
1690 return nullptr;
1691 if (II->getIntrinsicID() == IID && II->hasOneUse())
1692 return II->getArgOperand(0);
1693 return nullptr;
1694 };
1695
1696 Value *V0 = checkIntrinsicAndGetItsArgument(I.getOperand(0), ReductionIID);
1697 if (!V0)
1698 return false;
1699 Value *V1 = checkIntrinsicAndGetItsArgument(I.getOperand(1), ReductionIID);
1700 if (!V1)
1701 return false;
1702
1703 auto *VTy = cast<VectorType>(V0->getType());
1704 if (V1->getType() != VTy)
1705 return false;
1706 const auto &II0 = *cast<IntrinsicInst>(I.getOperand(0));
1707 const auto &II1 = *cast<IntrinsicInst>(I.getOperand(1));
1708 unsigned ReductionOpc =
1709 getArithmeticReductionInstruction(II0.getIntrinsicID());
1710
1711 InstructionCost OldCost = 0;
1712 InstructionCost NewCost = 0;
1713 InstructionCost CostOfRedOperand0 = 0;
1714 InstructionCost CostOfRed0 = 0;
1715 InstructionCost CostOfRedOperand1 = 0;
1716 InstructionCost CostOfRed1 = 0;
1717 analyzeCostOfVecReduction(II0, CostKind, TTI, CostOfRedOperand0, CostOfRed0);
1718 analyzeCostOfVecReduction(II1, CostKind, TTI, CostOfRedOperand1, CostOfRed1);
1719 OldCost = CostOfRed0 + CostOfRed1 + TTI.getInstructionCost(&I, CostKind);
1720 NewCost =
1721 CostOfRedOperand0 + CostOfRedOperand1 +
1722 TTI.getArithmeticInstrCost(BinOpOpc, VTy, CostKind) +
1723 TTI.getArithmeticReductionCost(ReductionOpc, VTy, std::nullopt, CostKind);
1724 if (NewCost >= OldCost || !NewCost.isValid())
1725 return false;
1726
1727 LLVM_DEBUG(dbgs() << "Found two mergeable reductions: " << I
1728 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
1729 << "\n");
1730 Value *VectorBO;
1731 if (BinOpOpc == Instruction::Or)
1732 VectorBO = Builder.CreateOr(V0, V1, "",
1733 cast<PossiblyDisjointInst>(I).isDisjoint());
1734 else
1735 VectorBO = Builder.CreateBinOp(BinOpOpc, V0, V1);
1736
1737 Value *Rdx = Builder.CreateIntrinsic(ReductionIID, {VTy}, {VectorBO});
1738 replaceValue(I, *Rdx);
1739 return true;
1740}
1741
1742// Check if memory is modified, freed, or synchronized between two instrs in
1743// the same BB.
1744static bool isMemModifiedBetween(const VectorizeOptions &Opts,
1747 const MemoryLocation &Loc, AAResults &AA) {
1748 unsigned NumScanned = 0;
1749 if (std::any_of(Begin, End, [&](const Instruction &Instr) {
1750 return isModSet(AA.getModRefInfo(&Instr, Loc)) ||
1751 ++NumScanned > Opts.vector_combine_max_scan_instrs;
1752 }))
1753 return true;
1754
1755 // willNotFreeBetween expects instructions rather than iterators. An empty
1756 // range cannot free or synchronize, so avoid dereferencing its end.
1757 return Begin != End && !willNotFreeBetween(&*Begin, &*End);
1758}
1759
1760namespace {
1761/// Helper class to indicate whether a vector index can be safely scalarized and
1762/// if a freeze needs to be inserted.
1763class ScalarizationResult {
1764 enum class StatusTy { Unsafe, Safe, SafeWithFreeze };
1765
1766 StatusTy Status;
1767 Value *ToFreeze;
1768
1769 ScalarizationResult(StatusTy Status, Value *ToFreeze = nullptr)
1770 : Status(Status), ToFreeze(ToFreeze) {}
1771
1772public:
1773 ScalarizationResult(const ScalarizationResult &Other) = default;
1774 ~ScalarizationResult() {
1775 assert(!ToFreeze && "freeze() not called with ToFreeze being set");
1776 }
1777
1778 static ScalarizationResult unsafe() { return {StatusTy::Unsafe}; }
1779 static ScalarizationResult safe() { return {StatusTy::Safe}; }
1780 static ScalarizationResult safeWithFreeze(Value *ToFreeze) {
1781 return {StatusTy::SafeWithFreeze, ToFreeze};
1782 }
1783
1784 /// Returns true if the index can be scalarize without requiring a freeze.
1785 bool isSafe() const { return Status == StatusTy::Safe; }
1786 /// Returns true if the index cannot be scalarized.
1787 bool isUnsafe() const { return Status == StatusTy::Unsafe; }
1788 /// Returns true if the index can be scalarize, but requires inserting a
1789 /// freeze.
1790 bool isSafeWithFreeze() const { return Status == StatusTy::SafeWithFreeze; }
1791
1792 /// Reset the state of Unsafe and clear ToFreze if set.
1793 void discard() {
1794 ToFreeze = nullptr;
1795 Status = StatusTy::Unsafe;
1796 }
1797
1798 /// Freeze the ToFreeze and update the use in \p User to use it.
1799 void freeze(IRBuilderBase &Builder, Instruction &UserI) {
1800 assert(isSafeWithFreeze() &&
1801 "should only be used when freezing is required");
1802 assert(is_contained(ToFreeze->users(), &UserI) &&
1803 "UserI must be a user of ToFreeze");
1804 IRBuilder<>::InsertPointGuard Guard(Builder);
1805 Builder.SetInsertPoint(cast<Instruction>(&UserI));
1806 Value *Frozen =
1807 Builder.CreateFreeze(ToFreeze, ToFreeze->getName() + ".frozen");
1808 for (Use &U : make_early_inc_range((UserI.operands())))
1809 if (U.get() == ToFreeze)
1810 U.set(Frozen);
1811
1812 ToFreeze = nullptr;
1813 }
1814};
1815} // namespace
1816
1817/// Check if it is legal to scalarize a memory access to \p VecTy at index \p
1818/// Idx. \p Idx must access a valid vector element.
1819static ScalarizationResult canScalarizeAccess(VectorType *VecTy, Value *Idx,
1820 const SimplifyQuery &SQ) {
1821 // We do checks for both fixed vector types and scalable vector types.
1822 // This is the number of elements of fixed vector types,
1823 // or the minimum number of elements of scalable vector types.
1824 uint64_t NumElements = VecTy->getElementCount().getKnownMinValue();
1825 unsigned IntWidth = Idx->getType()->getScalarSizeInBits();
1826
1827 if (auto *C = dyn_cast<ConstantInt>(Idx)) {
1828 if (C->getValue().ult(NumElements))
1829 return ScalarizationResult::safe();
1830 return ScalarizationResult::unsafe();
1831 }
1832
1833 // Always unsafe if the index type can't handle all inbound values.
1834 if (!llvm::isUIntN(IntWidth, NumElements))
1835 return ScalarizationResult::unsafe();
1836
1837 APInt Zero(IntWidth, 0);
1838 APInt MaxElts(IntWidth, NumElements);
1839 ConstantRange ValidIndices(Zero, MaxElts);
1840 ConstantRange IdxRange(IntWidth, true);
1841
1842 if (isGuaranteedNotToBePoison(Idx, SQ.AC, SQ.CtxI, SQ.DT)) {
1843 if (ValidIndices.contains(
1844 computeConstantRange(Idx, /*ForSigned=*/false, SQ)))
1845 return ScalarizationResult::safe();
1846 return ScalarizationResult::unsafe();
1847 }
1848
1849 // If the index may be poison, check if we can insert a freeze before the
1850 // range of the index is restricted.
1851 Value *IdxBase;
1852 ConstantInt *CI;
1853 if (match(Idx, m_And(m_Value(IdxBase), m_ConstantInt(CI)))) {
1854 IdxRange = IdxRange.binaryAnd(CI->getValue());
1855 } else if (match(Idx, m_URem(m_Value(IdxBase), m_ConstantInt(CI)))) {
1856 IdxRange = IdxRange.urem(CI->getValue());
1857 }
1858
1859 if (ValidIndices.contains(IdxRange))
1860 return ScalarizationResult::safeWithFreeze(IdxBase);
1861 return ScalarizationResult::unsafe();
1862}
1863
1864/// Return the GEP index type if the unsigned vector index \p Idx can be
1865/// represented by an inbounds GEP. A null result means that the maximum byte
1866/// offset cannot be represented by the pointer's signed GEP index type.
1867///
1868/// unsigned lane range
1869/// |
1870/// v
1871/// MaxByteOffset = MaxLane * element store size
1872/// |
1873/// +-- unavailable or outside signed GEP range --> reject
1874/// |
1875/// v
1876/// valid range --> use the pointer's GEP index type
1878 Type *PtrTy,
1879 const DataLayout &DL) {
1880 auto *GEPIndexTy = cast<IntegerType>(DL.getIndexType(PtrTy));
1881 unsigned GEPBits = GEPIndexTy->getBitWidth();
1882 uint64_t NumElements = VecTy->getElementCount().getKnownMinValue();
1883
1884 uint64_t MaxLane = NumElements - 1;
1885 if (auto *C = dyn_cast<ConstantInt>(Idx)) {
1886 if (C->getValue().uge(NumElements))
1887 return nullptr;
1888 MaxLane = C->getZExtValue();
1889 }
1890
1891 Type *ElemTy = VecTy->getElementType();
1892 if (!DL.typeSizeEqualsStoreSize(ElemTy))
1893 return nullptr;
1894
1895 TypeSize ElemStride = DL.getTypeStoreSize(ElemTy);
1896 if (ElemStride.isScalable())
1897 return nullptr;
1898
1899 // Compare both values in a common width:
1900 //
1901 // MaxLane (uint64_t) * ElemStride (uint64_t) signed_max(GEPBits)
1902 // | |
1903 // v v
1904 // ByteOffset (up to 128 bits) sext to WideBits
1905 // \ /
1906 // +------------ ugt ------------+
1907 // |
1908 // greater -> reject
1909 //
1910 // WideBits = max(GEPBits, 128) prevents the multiplication from wrapping
1911 // and preserves the GEP limit during the comparison.
1912 unsigned WideBits = std::max(GEPBits, 128u);
1913 APInt MaxLaneValue(WideBits, MaxLane);
1914 APInt ByteOffset = MaxLaneValue;
1915 ByteOffset *= APInt(WideBits, ElemStride.getFixedValue());
1916 APInt MaxGEPOffset = APInt::getSignedMaxValue(GEPBits).sext(WideBits);
1917 // Reject offsets outside the GEP's positive signed range. Compare as
1918 // unsigned because the full 128-bit product may set its sign bit.
1919 if (ByteOffset.ugt(MaxGEPOffset))
1920 return nullptr;
1921
1922 return GEPIndexTy;
1923}
1924
1925/// Materialize an index for a scalarized GEP after profitability is known.
1926/// Vector element indices are unsigned, but GEP sign-extends narrow integer
1927/// indices. Widen a narrow index explicitly so its unsigned value is retained.
1929 IRBuilderBase &Builder) {
1930 unsigned SrcBits = Idx->getType()->getIntegerBitWidth();
1931 unsigned DstBits = GEPIndexTy->getBitWidth();
1932 if (SrcBits >= DstBits)
1933 return Idx;
1934
1935 return Builder.CreateZExt(Idx, GEPIndexTy, Idx->getName() + ".gepidx");
1936}
1937
1938/// The memory operation on a vector of \p ScalarType had alignment of
1939/// \p VectorAlignment. Compute the maximal, but conservatively correct,
1940/// alignment that will be valid for the memory operation on a single scalar
1941/// element of the same type with index \p Idx.
1943 Type *ScalarType, Value *Idx,
1944 const DataLayout &DL) {
1945 if (auto *C = dyn_cast<ConstantInt>(Idx))
1946 return commonAlignment(VectorAlignment,
1947 C->getZExtValue() * DL.getTypeStoreSize(ScalarType));
1948 return commonAlignment(VectorAlignment, DL.getTypeStoreSize(ScalarType));
1949}
1950
1951/// Fold a vector store fed by a single-use insertelement chain into scalar
1952/// stores.
1953///
1954/// Before:
1955///
1956/// %p --> vector load --> insert %x, lane 1 --> insert %y, lane 3
1957/// |
1958/// v
1959/// vector store to %p
1960///
1961/// Vector lanes: [ 0 ] [ 1 ] [ 2 ] [ 3 ]
1962/// Stored value: [ old | x | old | y ] (one vector store)
1963///
1964/// After:
1965///
1966/// +--> GEP(%p, lane 1) --> store %x
1967/// %p -------------+
1968/// +--> GEP(%p, lane 3) --> store %y
1969///
1970/// Vector lanes: [ 0 ] [ 1 ] [ 2 ] [ 3 ]
1971/// Scalar stores: x y
1972/// store@1 store@3
1973///
1974/// Step 1. Gate:
1975/// target supports vector-element GEP addressing
1976///
1977/// Step 2. Trace:
1978/// vector store <-- insertelement <-- ... <-- insertelement <-- load
1979///
1980/// Steps 3-5. Validate:
1981/// reject unprofitable full overwrites; require simple accesses, a
1982/// common address/block, no memory write in between, and scalarizable
1983/// indices.
1984bool VectorCombine::foldInsertElementsToStores(Instruction &I) {
1985 // Step 1: The target must support addressing a vector element with a GEP.
1987 return false;
1988
1989 auto *SI = cast<StoreInst>(&I);
1990 if (!SI->isSimple() || !isa<VectorType>(SI->getValueOperand()->getType()))
1991 return false;
1992
1993 // Step 2: Collect a single-use insertelement chain, starting at the vector
1994 // store and walking back to the candidate load.
1995 Value *Source = SI->getValueOperand();
1996 SmallVector<std::pair<Value *, Value *>, 4> InsertElements;
1997 Value *Base = Source;
1998 while (auto *Insert = dyn_cast<InsertElementInst>(Base)) {
1999 if (!Insert->hasOneUse())
2000 break;
2001 Value *InsertVal = Insert->getOperand(1);
2002 Value *Idx = Insert->getOperand(2);
2003 InsertElements.push_back({InsertVal, Idx});
2004 Base = Insert->getOperand(0);
2005 }
2006
2007 if (InsertElements.empty())
2008 return false;
2009
2010 // The backwards walk collected the inserts in reverse program order. Restore
2011 // it now so later scalar stores preserve writes to duplicate/equal indices.
2012 std::reverse(InsertElements.begin(), InsertElements.end());
2013 auto *Load = dyn_cast<LoadInst>(Base);
2014 if (!Load)
2015 return false;
2016 auto *VecTy = cast<VectorType>(SI->getValueOperand()->getType());
2017
2018 // Step 3: Avoid replacing a complete overwrite with scalar stores when every
2019 // lane receives the same value; keeping the vector operation is preferable.
2020 if (auto *FVT = dyn_cast<FixedVectorType>(VecTy)) {
2021 if (InsertElements.size() == FVT->getNumElements()) {
2022 Value *FirstVal = InsertElements.front().first;
2023 if (all_of(InsertElements,
2024 [FirstVal](const auto &Elt) { return Elt.first == FirstVal; }))
2025 return false;
2026 }
2027 }
2028 Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts();
2029 // Step 4: Establish the load/store update is legal: both accesses are simple,
2030 // have the same base address and block, have scalar elements whose type size
2031 // equals their store size, and no intervening operation modifies the updated
2032 // memory.
2033 if (!Load->isSimple() || Load->getParent() != SI->getParent() ||
2034 !DL->typeSizeEqualsStoreSize(Load->getType()->getScalarType()) ||
2035 SrcAddr != SI->getPointerOperand()->stripPointerCasts())
2036 return false;
2037
2038 if (isMemModifiedBetween(Opts, Load->getIterator(), SI->getIterator(),
2039 MemoryLocation::get(SI), AA))
2040 return false;
2041
2042 // Step 5: Validate every index before changing IR. A safe-with-freeze result
2043 // is recorded by ScalarizationResult, so discard it until profitability is
2044 // known; otherwise a rejected candidate could leave a freeze behind.
2045 for (auto [InsertVal, Idx] : InsertElements) {
2046 auto ScalarizableIdx =
2047 canScalarizeAccess(VecTy, Idx, SQ.getWithInstruction(&I));
2048 if (ScalarizableIdx.isUnsafe())
2049 return false;
2050
2051 auto GEPIndex =
2052 getScalarizedGEPIndexInfo(VecTy, Idx, SI->getPointerOperandType(), *DL);
2053 if (!GEPIndex) {
2054 ScalarizableIdx.discard();
2055 return false;
2056 }
2057
2058 // We are only checking legality here. Do not mutate IR before the
2059 // profitability check, but also do not leave a pending ToFreeze behind.
2060 ScalarizableIdx.discard();
2061 }
2062
2064 Instruction::Store, SI->getValueOperand()->getType(), SI->getAlign(),
2065 SI->getPointerAddressSpace(), CostKind);
2066
2067 if (Load->hasOneUse())
2068 OldCost += TTI.getMemoryOpCost(Instruction::Load, Load->getType(),
2069 Load->getAlign(),
2070 Load->getPointerAddressSpace(), CostKind);
2071
2072 for (auto [InsertVal, Idx] : InsertElements) {
2073 int Index = -1;
2074 if (auto *CIdx = dyn_cast<ConstantInt>(Idx))
2075 Index = CIdx->getZExtValue();
2076
2077 OldCost += TTI.getVectorInstrCost(Instruction::InsertElement, VecTy,
2078 CostKind, Index);
2079 }
2080
2081 InstructionCost NewCost = 0;
2082 // This transform replaces insertelement operations on a single vector with
2083 // GEPs and scalar stores, so assume constant-index GEP offsets stay within
2084 // addressing-mode ranges that getGEPCost considers TCC_Free. Cost only GEPs
2085 // with dynamic indices.
2086 for (auto [InsertVal, Idx] : InsertElements) {
2087 if (isa<ConstantInt>(Idx))
2088 continue;
2089 const Value *GEPIndices[] = {ConstantInt::get(Idx->getType(), 0), Idx};
2090 NewCost += TTI.getGEPCost(VecTy, SI->getPointerOperand(), GEPIndices,
2091 CostKind, InsertVal->getType());
2092 }
2093
2094 for (auto [InsertVal, Idx] : InsertElements) {
2095 Align ScalarOpAlignment = computeAlignmentAfterScalarization(
2096 std::max(SI->getAlign(), Load->getAlign()), InsertVal->getType(), Idx,
2097 *DL);
2098
2099 NewCost += TTI.getMemoryOpCost(Instruction::Store, InsertVal->getType(),
2100 ScalarOpAlignment,
2101 SI->getPointerAddressSpace(), CostKind);
2102 }
2103
2104 LLVM_DEBUG(dbgs() << "Found an insert-elements vector store scalarization "
2105 "candidate: "
2106 << I << "\n"
2107 << " NumInserts: " << InsertElements.size() << "\n"
2108 << " OldCost: " << OldCost << " vs NewCost: " << NewCost
2109 << "\n");
2110
2111 if (OldCost <= NewCost)
2112 return false;
2113
2114 for (auto [InsertVal, Idx] : InsertElements) {
2115 auto ScalarizableIdx =
2116 canScalarizeAccess(VecTy, Idx, SQ.getWithInstruction(&I));
2117 assert(!ScalarizableIdx.isUnsafe() && "already checked above");
2118
2119 if (ScalarizableIdx.isSafeWithFreeze())
2120 ScalarizableIdx.freeze(Builder, *cast<Instruction>(Idx));
2121 }
2122
2123 Worklist.push(Load);
2124 StoreInst *LastStore = nullptr;
2125 for (auto [InsertVal, Idx] : InsertElements) {
2126 auto ScalarizableIdx =
2127 canScalarizeAccess(VecTy, Idx, SQ.getWithInstruction(&I));
2128 if (ScalarizableIdx.isUnsafe())
2129 return false;
2130
2131 IntegerType *GEPIndexTy =
2132 getScalarizedGEPIndexInfo(VecTy, Idx, SI->getPointerOperandType(), *DL);
2133
2134 Value *GEPIdx = materializeScalarizedGEPIndex(Idx, GEPIndexTy, Builder);
2135 Value *GEP = Builder.CreateInBoundsGEP(
2136 SI->getValueOperand()->getType(), SI->getPointerOperand(),
2137 {ConstantInt::get(GEPIdx->getType(), 0), GEPIdx});
2138
2139 LastStore = Builder.CreateStore(InsertVal, GEP);
2140 LastStore->copyMetadata(*SI);
2141
2142 // The new GEP may change the pointer operand, so !invariant.group cannot
2143 // be transferred to the scalar store.
2144 LastStore->setMetadata(LLVMContext::MD_invariant_group, nullptr);
2145 Align ScalarOpAlignment = computeAlignmentAfterScalarization(
2146 std::max(SI->getAlign(), Load->getAlign()), InsertVal->getType(), Idx,
2147 *DL);
2148 LastStore->setAlignment(ScalarOpAlignment);
2149 }
2150
2151 replaceValue(I, *LastStore);
2153 return true;
2154}
2155
2156/// Try to scalarize vector loads feeding extractelement or bitcast
2157/// instructions.
2158bool VectorCombine::scalarizeLoad(Instruction &I) {
2159 Value *Ptr;
2160 if (!match(&I, m_Load(m_Value(Ptr))))
2161 return false;
2162
2163 auto *LI = cast<LoadInst>(&I);
2164 auto *VecTy = cast<VectorType>(LI->getType());
2165
2166 // The isSimple() check could be isUnordered(), but for now we cowardly
2167 // refuse to handle even unordered atomics.
2168 if (!LI->isSimple() || !DL->typeSizeEqualsStoreSize(VecTy->getScalarType()))
2169 return false;
2170
2171 bool AllExtracts = true;
2172 bool AllBitcasts = true;
2173 Instruction *LastCheckedInst = LI;
2174 unsigned NumInstChecked = 0;
2175
2176 // Check what type of users we have (must either all be extracts or
2177 // bitcasts) and ensure no memory modifications between the load and
2178 // its users.
2179 for (User *U : LI->users()) {
2180 auto *UI = dyn_cast<Instruction>(U);
2181 if (!UI || UI->getParent() != LI->getParent())
2182 return false;
2183
2184 // If any user is waiting to be erased, then bail out as this will
2185 // distort the cost calculation and possibly lead to infinite loops.
2186 if (UI->use_empty())
2187 return false;
2188
2189 if (!isa<ExtractElementInst>(UI))
2190 AllExtracts = false;
2191 if (!isa<BitCastInst>(UI))
2192 AllBitcasts = false;
2193
2194 // Check if any instruction between the load and the user may modify memory.
2195 if (LastCheckedInst->comesBefore(UI)) {
2196 for (Instruction &I :
2197 make_range(std::next(LI->getIterator()), UI->getIterator())) {
2198 // Bail out if we reached the check limit or the instruction may write
2199 // to memory.
2200 if (NumInstChecked == Opts.vector_combine_max_scan_instrs ||
2201 I.mayWriteToMemory())
2202 return false;
2203 NumInstChecked++;
2204 }
2205 LastCheckedInst = UI;
2206 }
2207 }
2208
2209 if (AllExtracts)
2210 return scalarizeLoadExtract(LI, VecTy, Ptr);
2211 if (AllBitcasts)
2212 return scalarizeLoadBitcast(LI, VecTy, Ptr);
2213 return false;
2214}
2215
2216/// Try to scalarize vector loads feeding extractelement instructions.
2217bool VectorCombine::scalarizeLoadExtract(LoadInst *LI, VectorType *VecTy,
2218 Value *Ptr) {
2220 return false;
2221
2222 DenseMap<ExtractElementInst *, ScalarizationResult> NeedFreeze;
2223 DenseMap<ExtractElementInst *, IntegerType *> GEPIndexInfos;
2224 llvm::scope_exit FailureGuard([&]() {
2225 // If the transform is aborted, discard the ScalarizationResults.
2226 for (auto &Pair : NeedFreeze)
2227 Pair.second.discard();
2228 });
2229
2230 InstructionCost OriginalCost =
2231 TTI.getMemoryOpCost(Instruction::Load, VecTy, LI->getAlign(),
2232 LI->getPointerAddressSpace(), CostKind);
2233 InstructionCost ScalarizedCost = 0;
2234
2235 for (User *U : LI->users()) {
2236 auto *UI = cast<ExtractElementInst>(U);
2237
2238 auto ScalarIdx = canScalarizeAccess(VecTy, UI->getIndexOperand(),
2239 SQ.getWithInstruction(LI));
2240 if (ScalarIdx.isUnsafe())
2241 return false;
2242
2243 IntegerType *GEPIndex = getScalarizedGEPIndexInfo(
2244 VecTy, UI->getIndexOperand(), LI->getPointerOperandType(), *DL);
2245 if (!GEPIndex) {
2246 ScalarIdx.discard();
2247 return false;
2248 }
2249
2250 GEPIndexInfos.try_emplace(UI, GEPIndex);
2251
2252 if (ScalarIdx.isSafeWithFreeze()) {
2253 NeedFreeze.try_emplace(UI, ScalarIdx);
2254 ScalarIdx.discard();
2255 }
2256
2257 auto *Index = dyn_cast<ConstantInt>(UI->getIndexOperand());
2258 OriginalCost +=
2259 TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, CostKind,
2260 Index ? Index->getZExtValue() : -1);
2261 ScalarizedCost +=
2262 TTI.getMemoryOpCost(Instruction::Load, VecTy->getElementType(),
2263 Align(1), LI->getPointerAddressSpace(), CostKind);
2264 ScalarizedCost += TTI.getAddressComputationCost(LI->getPointerOperandType(),
2265 nullptr, nullptr, CostKind);
2266 if (!Index && UI->getIndexOperand()->getType()->getIntegerBitWidth() <
2267 GEPIndex->getBitWidth())
2268 ScalarizedCost += TTI.getCastInstrCost(
2269 Instruction::ZExt, GEPIndex, UI->getIndexOperand()->getType(),
2270 TTI::CastContextHint::None, CostKind);
2271 }
2272
2273 LLVM_DEBUG(dbgs() << "Found all extractions of a vector load: " << *LI
2274 << "\n LoadExtractCost: " << OriginalCost
2275 << " vs ScalarizedCost: " << ScalarizedCost << "\n");
2276
2277 if (ScalarizedCost > OriginalCost)
2278 return false;
2279 if (ScalarizedCost == OriginalCost && !LI->hasOneUse())
2280 return false;
2281
2282 // Ensure we add the load back to the worklist BEFORE its users so they can
2283 // erased in the correct order.
2284 Worklist.push(LI);
2285
2286 Type *ElemType = VecTy->getElementType();
2287
2288 // Replace extracts with narrow scalar loads.
2289 for (User *U : LI->users()) {
2290 auto *EI = cast<ExtractElementInst>(U);
2291 Value *Idx = EI->getIndexOperand();
2292
2293 // Insert 'freeze' for poison indexes.
2294 if (auto It = NeedFreeze.find(EI); It != NeedFreeze.end())
2295 It->second.freeze(Builder, *cast<Instruction>(Idx));
2296
2297 Builder.SetInsertPoint(EI);
2298 auto It = GEPIndexInfos.find(EI);
2299 assert(It != GEPIndexInfos.end() &&
2300 "Missing scalarized GEP index information");
2301 Value *GEPIdx = materializeScalarizedGEPIndex(Idx, It->second, Builder);
2302 Value *GEP = Builder.CreateInBoundsGEP(
2303 VecTy, Ptr, {ConstantInt::get(GEPIdx->getType(), 0), GEPIdx});
2304 auto *NewLoad = cast<LoadInst>(
2305 Builder.CreateLoad(ElemType, GEP, EI->getName() + ".scalar"));
2306
2307 Align ScalarOpAlignment =
2308 computeAlignmentAfterScalarization(LI->getAlign(), ElemType, Idx, *DL);
2309 NewLoad->setAlignment(ScalarOpAlignment);
2310 NewLoad->copyMetadata(*LI,
2311 {LLVMContext::MD_mmra, LLVMContext::MD_nontemporal,
2312 LLVMContext::MD_mem_cache_hint});
2313
2314 if (auto *ConstIdx = dyn_cast<ConstantInt>(Idx)) {
2315 size_t Offset = ConstIdx->getZExtValue() * DL->getTypeStoreSize(ElemType);
2316 AAMDNodes OldAAMD = LI->getAAMetadata();
2317 NewLoad->setAAMetadata(OldAAMD.adjustForAccess(Offset, ElemType, *DL));
2318 }
2319
2320 replaceValue(*EI, *NewLoad, false);
2321 }
2322
2323 FailureGuard.release();
2324 return true;
2325}
2326
2327/// Try to scalarize vector loads feeding bitcast instructions.
2328bool VectorCombine::scalarizeLoadBitcast(LoadInst *LI, VectorType *VecTy,
2329 Value *Ptr) {
2330 InstructionCost OriginalCost =
2331 TTI.getMemoryOpCost(Instruction::Load, VecTy, LI->getAlign(),
2332 LI->getPointerAddressSpace(), CostKind);
2333
2334 if (!isa<FixedVectorType>(VecTy))
2335 return false;
2336
2337 Type *TargetScalarType = nullptr;
2338 unsigned VecBitWidth = DL->getTypeSizeInBits(VecTy);
2339
2340 for (User *U : LI->users()) {
2341 auto *BC = cast<BitCastInst>(U);
2342
2343 Type *DestTy = BC->getDestTy();
2344 if (!DestTy->isIntegerTy() && !DestTy->isFloatingPointTy())
2345 return false;
2346
2347 unsigned DestBitWidth = DL->getTypeSizeInBits(DestTy);
2348 if (DestBitWidth != VecBitWidth)
2349 return false;
2350
2351 // All bitcasts must target the same scalar type.
2352 if (!TargetScalarType)
2353 TargetScalarType = DestTy;
2354 else if (TargetScalarType != DestTy)
2355 return false;
2356
2357 OriginalCost +=
2358 TTI.getCastInstrCost(Instruction::BitCast, TargetScalarType, VecTy,
2359 TTI.getCastContextHint(BC), CostKind, BC);
2360 }
2361
2362 if (!TargetScalarType)
2363 return false;
2364
2365 assert(!LI->user_empty() && "Unexpected load without bitcast users");
2366 InstructionCost ScalarizedCost =
2367 TTI.getMemoryOpCost(Instruction::Load, TargetScalarType, LI->getAlign(),
2368 LI->getPointerAddressSpace(), CostKind);
2369
2370 LLVM_DEBUG(dbgs() << "Found vector load feeding only bitcasts: " << *LI
2371 << "\n OriginalCost: " << OriginalCost
2372 << " vs ScalarizedCost: " << ScalarizedCost << "\n");
2373
2374 if (ScalarizedCost >= OriginalCost)
2375 return false;
2376
2377 // Ensure we add the load back to the worklist BEFORE its users so they can
2378 // erased in the correct order.
2379 Worklist.push(LI);
2380
2381 Builder.SetInsertPoint(LI);
2382 auto *ScalarLoad =
2383 Builder.CreateLoad(TargetScalarType, Ptr, LI->getName() + ".scalar");
2384 ScalarLoad->setAlignment(LI->getAlign());
2385 ScalarLoad->copyMetadata(*LI);
2386
2387 // Replace all bitcast users with the scalar load.
2388 for (User *U : LI->users()) {
2389 auto *BC = cast<BitCastInst>(U);
2390 replaceValue(*BC, *ScalarLoad, false);
2391 }
2392
2393 return true;
2394}
2395
2396bool VectorCombine::scalarizeExtExtract(Instruction &I) {
2398 return false;
2399 auto *Ext = dyn_cast<ZExtInst>(&I);
2400 if (!Ext)
2401 return false;
2402
2403 // Try to convert a vector zext feeding only extracts to a set of scalar
2404 // (Src << ExtIdx *Size) & (Size -1)
2405 // if profitable .
2406 auto *SrcTy = dyn_cast<FixedVectorType>(Ext->getOperand(0)->getType());
2407 if (!SrcTy)
2408 return false;
2409 auto *DstTy = cast<FixedVectorType>(Ext->getType());
2410
2411 Type *ScalarDstTy = DstTy->getElementType();
2412 if (DL->getTypeSizeInBits(SrcTy) != DL->getTypeSizeInBits(ScalarDstTy))
2413 return false;
2414
2415 InstructionCost VectorCost =
2416 TTI.getCastInstrCost(Instruction::ZExt, DstTy, SrcTy,
2417 TTI::CastContextHint::None, CostKind, Ext);
2418 unsigned ExtCnt = 0;
2419 bool ExtLane0 = false;
2420 for (User *U : Ext->users()) {
2421 uint64_t Idx;
2422 if (!match(U, m_ExtractElt(m_Value(), m_ConstantInt(Idx))))
2423 return false;
2424 // An out-of-bounds extractelement produces poison; bail out rather
2425 // than computing a shift amount that overflows the packed type.
2426 if (Idx >= SrcTy->getNumElements())
2427 return false;
2428 if (cast<Instruction>(U)->use_empty())
2429 continue;
2430 ExtCnt += 1;
2431 ExtLane0 |= !Idx;
2432 VectorCost += TTI.getVectorInstrCost(Instruction::ExtractElement, DstTy,
2433 CostKind, Idx, U);
2434 }
2435
2436 InstructionCost ScalarCost =
2437 ExtCnt * TTI.getArithmeticInstrCost(
2438 Instruction::And, ScalarDstTy, CostKind,
2441 (ExtCnt - ExtLane0) *
2443 Instruction::LShr, ScalarDstTy, CostKind,
2446 if (ScalarCost > VectorCost)
2447 return false;
2448
2449 Value *ScalarV = Ext->getOperand(0);
2450 if (!isGuaranteedNotToBePoison(ScalarV, SQ.AC, dyn_cast<Instruction>(ScalarV),
2451 SQ.DT)) {
2452 // Check wether all lanes are extracted, all extracts trigger UB
2453 // on poison, and the last extract (and hence all previous ones)
2454 // are guaranteed to execute if Ext executes. If so, we do not
2455 // need to insert a freeze.
2456 SmallDenseSet<ConstantInt *, 8> ExtractedLanes;
2457 bool AllExtractsTriggerUB = true;
2458 ExtractElementInst *LastExtract = nullptr;
2459 BasicBlock *ExtBB = Ext->getParent();
2460 for (User *U : Ext->users()) {
2461 auto *Extract = cast<ExtractElementInst>(U);
2462 if (Extract->getParent() != ExtBB || !programUndefinedIfPoison(Extract)) {
2463 AllExtractsTriggerUB = false;
2464 break;
2465 }
2466 ExtractedLanes.insert(cast<ConstantInt>(Extract->getIndexOperand()));
2467 if (!LastExtract || LastExtract->comesBefore(Extract))
2468 LastExtract = Extract;
2469 }
2470 if (ExtractedLanes.size() != DstTy->getNumElements() ||
2471 !AllExtractsTriggerUB ||
2473 LastExtract->getIterator()))
2474 ScalarV = Builder.CreateFreeze(ScalarV);
2475 }
2476 ScalarV = Builder.CreateBitCast(
2477 ScalarV,
2478 IntegerType::get(SrcTy->getContext(), DL->getTypeSizeInBits(SrcTy)));
2479 uint64_t SrcEltSizeInBits = DL->getTypeSizeInBits(SrcTy->getElementType());
2480 uint64_t TotalBits = DL->getTypeSizeInBits(SrcTy);
2481 APInt EltBitMask = APInt::getLowBitsSet(TotalBits, SrcEltSizeInBits);
2482 Type *PackedTy = IntegerType::get(SrcTy->getContext(), TotalBits);
2483 Value *Mask = ConstantInt::get(PackedTy, EltBitMask);
2484 for (User *U : Ext->users()) {
2485 auto *Extract = cast<ExtractElementInst>(U);
2486 uint64_t Idx =
2487 cast<ConstantInt>(Extract->getIndexOperand())->getZExtValue();
2488 uint64_t ShiftAmt =
2489 DL->isBigEndian()
2490 ? (TotalBits - SrcEltSizeInBits - Idx * SrcEltSizeInBits)
2491 : (Idx * SrcEltSizeInBits);
2492 Value *LShr = Builder.CreateLShr(ScalarV, ShiftAmt);
2493 Value *And = Builder.CreateAnd(LShr, Mask);
2494 U->replaceAllUsesWith(And);
2495 }
2496 return true;
2497}
2498
2499/// Try to fold "(or (zext (bitcast X)), (shl (zext (bitcast Y)), C))"
2500/// to "(bitcast (concat X, Y))"
2501/// where X/Y are bitcasted from i1 mask vectors.
2502bool VectorCombine::foldConcatOfBoolMasks(Instruction &I) {
2503 Type *Ty = I.getType();
2504 if (!Ty->isIntegerTy())
2505 return false;
2506
2507 // TODO: Add big endian test coverage
2508 if (DL->isBigEndian())
2509 return false;
2510
2511 // Restrict to disjoint cases so the mask vectors aren't overlapping.
2512 Instruction *X, *Y;
2514 return false;
2515
2516 // Allow both sources to contain shl, to handle more generic pattern:
2517 // "(or (shl (zext (bitcast X)), C1), (shl (zext (bitcast Y)), C2))"
2518 Value *SrcX;
2519 uint64_t ShAmtX = 0;
2520 if (!match(X, m_OneUse(m_ZExt(m_OneUse(m_BitCast(m_Value(SrcX)))))) &&
2521 !match(X, m_OneUse(
2523 m_ConstantInt(ShAmtX)))))
2524 return false;
2525
2526 Value *SrcY;
2527 uint64_t ShAmtY = 0;
2528 if (!match(Y, m_OneUse(m_ZExt(m_OneUse(m_BitCast(m_Value(SrcY)))))) &&
2529 !match(Y, m_OneUse(
2531 m_ConstantInt(ShAmtY)))))
2532 return false;
2533
2534 // Canonicalize larger shift to the RHS.
2535 if (ShAmtX > ShAmtY) {
2536 std::swap(X, Y);
2537 std::swap(SrcX, SrcY);
2538 std::swap(ShAmtX, ShAmtY);
2539 }
2540
2541 // Ensure both sources are matching vXi1 bool mask types, and that the shift
2542 // difference is the mask width so they can be easily concatenated together.
2543 uint64_t ShAmtDiff = ShAmtY - ShAmtX;
2544 unsigned NumSHL = (ShAmtX > 0) + (ShAmtY > 0);
2545 unsigned BitWidth = Ty->getPrimitiveSizeInBits();
2546 auto *MaskTy = dyn_cast<FixedVectorType>(SrcX->getType());
2547 if (!MaskTy || SrcX->getType() != SrcY->getType() ||
2548 !MaskTy->getElementType()->isIntegerTy(1) ||
2549 MaskTy->getNumElements() != ShAmtDiff ||
2550 MaskTy->getNumElements() > (BitWidth / 2))
2551 return false;
2552
2553 auto *ConcatTy = FixedVectorType::getDoubleElementsVectorType(MaskTy);
2554 auto *ConcatIntTy =
2555 Type::getIntNTy(Ty->getContext(), ConcatTy->getNumElements());
2556 auto *MaskIntTy = Type::getIntNTy(Ty->getContext(), ShAmtDiff);
2557
2558 SmallVector<int, 32> ConcatMask(ConcatTy->getNumElements());
2559 std::iota(ConcatMask.begin(), ConcatMask.end(), 0);
2560
2561 // TODO: Is it worth supporting multi use cases?
2562 InstructionCost OldCost = 0;
2563 OldCost += TTI.getArithmeticInstrCost(Instruction::Or, Ty, CostKind);
2564 OldCost +=
2565 NumSHL * TTI.getArithmeticInstrCost(Instruction::Shl, Ty, CostKind);
2566 OldCost += 2 * TTI.getCastInstrCost(Instruction::ZExt, Ty, MaskIntTy,
2567 TTI::CastContextHint::None, CostKind);
2568 OldCost += 2 * TTI.getCastInstrCost(Instruction::BitCast, MaskIntTy, MaskTy,
2569 TTI::CastContextHint::None, CostKind);
2570
2571 InstructionCost NewCost = 0;
2573 MaskTy, CostKind, ConcatMask);
2574 NewCost += TTI.getCastInstrCost(Instruction::BitCast, ConcatIntTy, ConcatTy,
2575 TTI::CastContextHint::None, CostKind);
2576 if (Ty != ConcatIntTy)
2577 NewCost += TTI.getCastInstrCost(Instruction::ZExt, Ty, ConcatIntTy,
2578 TTI::CastContextHint::None, CostKind);
2579 if (ShAmtX > 0)
2580 NewCost += TTI.getArithmeticInstrCost(Instruction::Shl, Ty, CostKind);
2581
2582 LLVM_DEBUG(dbgs() << "Found a concatenation of bitcasted bool masks: " << I
2583 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
2584 << "\n");
2585
2586 if (NewCost > OldCost)
2587 return false;
2588
2589 // Build bool mask concatenation, bitcast back to scalar integer, and perform
2590 // any residual zero-extension or shifting.
2591 Value *Concat = Builder.CreateShuffleVector(SrcX, SrcY, ConcatMask);
2592
2593 Value *Result = Builder.CreateBitCast(Concat, ConcatIntTy);
2594
2595 if (Ty != ConcatIntTy) {
2596 Result = Builder.CreateZExt(Result, Ty);
2597 }
2598
2599 if (ShAmtX > 0) {
2600 Result = Builder.CreateShl(Result, ShAmtX);
2601 }
2602
2603 replaceValue(I, *Result);
2604 return true;
2605}
2606
2607/// Try to convert "shuffle (binop (shuffle, shuffle)), undef"
2608/// --> "binop (shuffle), (shuffle)".
2609bool VectorCombine::foldPermuteOfBinops(Instruction &I) {
2610 BinaryOperator *BinOp;
2611 ArrayRef<int> OuterMask;
2612 if (!match(&I, m_Shuffle(m_BinOp(BinOp), m_Undef(), m_Mask(OuterMask))))
2613 return false;
2614
2615 // Don't introduce poison into div/rem.
2616 if (BinOp->isIntDivRem() && llvm::is_contained(OuterMask, PoisonMaskElem))
2617 return false;
2618
2619 Value *Op00, *Op01, *Op10, *Op11;
2620 ArrayRef<int> Mask0, Mask1;
2621 bool Match0 = match(BinOp->getOperand(0),
2622 m_Shuffle(m_Value(Op00), m_Value(Op01), m_Mask(Mask0)));
2623 bool Match1 = match(BinOp->getOperand(1),
2624 m_Shuffle(m_Value(Op10), m_Value(Op11), m_Mask(Mask1)));
2625 if (!Match0 && !Match1)
2626 return false;
2627
2628 Op00 = Match0 ? Op00 : BinOp->getOperand(0);
2629 Op01 = Match0 ? Op01 : BinOp->getOperand(0);
2630 Op10 = Match1 ? Op10 : BinOp->getOperand(1);
2631 Op11 = Match1 ? Op11 : BinOp->getOperand(1);
2632
2633 Instruction::BinaryOps Opcode = BinOp->getOpcode();
2634 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
2635 auto *BinOpTy = dyn_cast<FixedVectorType>(BinOp->getType());
2636 auto *Op0Ty = dyn_cast<FixedVectorType>(Op00->getType());
2637 auto *Op1Ty = dyn_cast<FixedVectorType>(Op10->getType());
2638 if (!ShuffleDstTy || !BinOpTy || !Op0Ty || !Op1Ty)
2639 return false;
2640
2641 unsigned NumSrcElts = BinOpTy->getNumElements();
2642
2643 // Don't accept shuffles that reference the second operand in
2644 // div/rem or if its an undef arg.
2645 if ((BinOp->isIntDivRem() || !isa<PoisonValue>(I.getOperand(1))) &&
2646 any_of(OuterMask, [NumSrcElts](int M) { return M >= (int)NumSrcElts; }))
2647 return false;
2648
2649 // Merge outer / inner (or identity if no match) shuffles.
2650 SmallVector<int> NewMask0, NewMask1;
2651 for (int M : OuterMask) {
2652 if (M < 0 || M >= (int)NumSrcElts) {
2653 NewMask0.push_back(PoisonMaskElem);
2654 NewMask1.push_back(PoisonMaskElem);
2655 } else {
2656 NewMask0.push_back(Match0 ? Mask0[M] : M);
2657 NewMask1.push_back(Match1 ? Mask1[M] : M);
2658 }
2659 }
2660
2661 unsigned NumOpElts = Op0Ty->getNumElements();
2662 bool IsIdentity0 = ShuffleDstTy == Op0Ty &&
2663 all_of(NewMask0, [NumOpElts](int M) { return M < (int)NumOpElts; }) &&
2664 ShuffleVectorInst::isIdentityMask(NewMask0, NumOpElts);
2665 bool IsIdentity1 = ShuffleDstTy == Op1Ty &&
2666 all_of(NewMask1, [NumOpElts](int M) { return M < (int)NumOpElts; }) &&
2667 ShuffleVectorInst::isIdentityMask(NewMask1, NumOpElts);
2668
2669 InstructionCost NewCost = 0;
2670 // Try to merge shuffles across the binop if the new shuffles are not costly.
2671 InstructionCost BinOpCost =
2672 TTI.getArithmeticInstrCost(Opcode, BinOpTy, CostKind);
2673 InstructionCost OldCost =
2675 ShuffleDstTy, BinOpTy, CostKind, OuterMask,
2676 0, nullptr, {BinOp}, &I);
2677 if (!BinOp->hasOneUse())
2678 NewCost += BinOpCost;
2679
2680 if (Match0) {
2682 TargetTransformInfo::SK_PermuteTwoSrc, BinOpTy, Op0Ty, CostKind, Mask0,
2683 0, nullptr, {Op00, Op01}, cast<Instruction>(BinOp->getOperand(0)));
2684 OldCost += Shuf0Cost;
2685 if (!BinOp->hasOneUse() || !BinOp->getOperand(0)->hasOneUse())
2686 NewCost += Shuf0Cost;
2687 }
2688 if (Match1) {
2690 TargetTransformInfo::SK_PermuteTwoSrc, BinOpTy, Op1Ty, CostKind, Mask1,
2691 0, nullptr, {Op10, Op11}, cast<Instruction>(BinOp->getOperand(1)));
2692 OldCost += Shuf1Cost;
2693 if (!BinOp->hasOneUse() || !BinOp->getOperand(1)->hasOneUse())
2694 NewCost += Shuf1Cost;
2695 }
2696
2697 NewCost += TTI.getArithmeticInstrCost(Opcode, ShuffleDstTy, CostKind);
2698
2699 if (!IsIdentity0)
2700 NewCost +=
2702 Op0Ty, CostKind, NewMask0, 0, nullptr, {Op00, Op01});
2703 if (!IsIdentity1)
2704 NewCost +=
2706 Op1Ty, CostKind, NewMask1, 0, nullptr, {Op10, Op11});
2707
2708 LLVM_DEBUG(dbgs() << "Found a shuffle feeding a shuffled binop: " << I
2709 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
2710 << "\n");
2711
2712 // If costs are equal, still fold as we reduce instruction count.
2713 if (NewCost > OldCost)
2714 return false;
2715
2716 Value *LHS =
2717 IsIdentity0 ? Op00 : Builder.CreateShuffleVector(Op00, Op01, NewMask0);
2718 Value *RHS =
2719 IsIdentity1 ? Op10 : Builder.CreateShuffleVector(Op10, Op11, NewMask1);
2720 Value *NewBO = Builder.CreateBinOp(Opcode, LHS, RHS);
2721
2722 // Intersect flags from the old binops.
2723 if (auto *NewInst = dyn_cast<Instruction>(NewBO))
2724 NewInst->copyIRFlags(BinOp);
2725
2726 replaceValue(I, *NewBO);
2727 return true;
2728}
2729
2730/// Try to convert "shuffle (binop), (binop)" into "binop (shuffle), (shuffle)".
2731/// Try to convert "shuffle (cmpop), (cmpop)" into "cmpop (shuffle), (shuffle)".
2732bool VectorCombine::foldShuffleOfBinops(Instruction &I) {
2733 ArrayRef<int> OldMask;
2734 Instruction *LHS, *RHS;
2736 m_Mask(OldMask))))
2737 return false;
2738
2739 // TODO: Add support for addlike etc.
2740 if (LHS->getOpcode() != RHS->getOpcode())
2741 return false;
2742
2743 Value *X, *Y, *Z, *W;
2744 bool IsCommutative = false;
2745 CmpPredicate PredLHS = CmpInst::BAD_ICMP_PREDICATE;
2746 CmpPredicate PredRHS = CmpInst::BAD_ICMP_PREDICATE;
2747 if (match(LHS, m_BinOp(m_Value(X), m_Value(Y))) &&
2748 match(RHS, m_BinOp(m_Value(Z), m_Value(W)))) {
2749 auto *BO = cast<BinaryOperator>(LHS);
2750 // Don't introduce poison into div/rem.
2751 if (llvm::is_contained(OldMask, PoisonMaskElem) && BO->isIntDivRem())
2752 return false;
2753 IsCommutative = BinaryOperator::isCommutative(BO->getOpcode());
2754 } else if (match(LHS, m_Cmp(PredLHS, m_Value(X), m_Value(Y))) &&
2755 match(RHS, m_Cmp(PredRHS, m_Value(Z), m_Value(W))) &&
2756 (CmpInst::Predicate)PredLHS == (CmpInst::Predicate)PredRHS) {
2757 IsCommutative = cast<CmpInst>(LHS)->isCommutative();
2758 } else
2759 return false;
2760
2761 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
2762 auto *BinResTy = dyn_cast<FixedVectorType>(LHS->getType());
2763 auto *BinOpTy = dyn_cast<FixedVectorType>(X->getType());
2764 if (!ShuffleDstTy || !BinResTy || !BinOpTy || X->getType() != Z->getType())
2765 return false;
2766
2767 bool SameBinOp = LHS == RHS;
2768 unsigned NumSrcElts = BinOpTy->getNumElements();
2769
2770 // If we have something like "add X, Y" and "add Z, X", swap ops to match.
2771 if (IsCommutative && X != Z && Y != W && (X == W || Y == Z))
2772 std::swap(X, Y);
2773
2774 auto ConvertToUnary = [NumSrcElts](int &M) {
2775 if (M >= (int)NumSrcElts)
2776 M -= NumSrcElts;
2777 };
2778
2779 SmallVector<int> NewMask0(OldMask);
2781 TTI::OperandValueInfo Op0Info = TTI.commonOperandInfo(X, Z);
2782 if (X == Z) {
2783 llvm::for_each(NewMask0, ConvertToUnary);
2785 Z = PoisonValue::get(BinOpTy);
2786 }
2787
2788 SmallVector<int> NewMask1(OldMask);
2790 TTI::OperandValueInfo Op1Info = TTI.commonOperandInfo(Y, W);
2791 if (Y == W) {
2792 llvm::for_each(NewMask1, ConvertToUnary);
2794 W = PoisonValue::get(BinOpTy);
2795 }
2796
2797 // Try to replace a binop with a shuffle if the shuffle is not costly.
2798 // When SameBinOp, only count the binop cost once.
2799 InstructionCost LHSCost = TTI.getInstructionCost(LHS, CostKind);
2800 InstructionCost RHSCost = TTI.getInstructionCost(RHS, CostKind);
2801
2802 InstructionCost OldCost = LHSCost;
2803 if (!SameBinOp) {
2804 OldCost += RHSCost;
2805 }
2807 ShuffleDstTy, BinResTy, CostKind, OldMask, 0,
2808 nullptr, {LHS, RHS}, &I);
2809
2810 // Handle shuffle(binop(shuffle(x),y),binop(z,shuffle(w))) style patterns
2811 // where one use shuffles have gotten split across the binop/cmp. These
2812 // often allow a major reduction in total cost that wouldn't happen as
2813 // individual folds.
2814 auto MergeInner = [&](Value *&Op, int Offset, MutableArrayRef<int> Mask,
2815 TTI::TargetCostKind CostKind,
2816 Instruction *BinOp) -> bool {
2817 Value *InnerOp;
2818 ArrayRef<int> InnerMask;
2819 if (match(Op, m_OneUse(m_Shuffle(m_Value(InnerOp), m_Undef(),
2820 m_Mask(InnerMask)))) &&
2821 InnerOp->getType() == Op->getType() &&
2822 all_of(InnerMask,
2823 [NumSrcElts](int M) { return M < (int)NumSrcElts; })) {
2824 for (int &M : Mask)
2825 if (Offset <= M && M < (int)(Offset + NumSrcElts)) {
2826 M = InnerMask[M - Offset];
2827 M = 0 <= M ? M + Offset : M;
2828 }
2829 // Op is only removed if the binop using it is removed too.
2830 bool Removed = BinOp->hasOneUser();
2831 if (Removed)
2832 OldCost += TTI.getInstructionCost(cast<Instruction>(Op), CostKind);
2833 Op = InnerOp;
2834 return Removed;
2835 }
2836 return false;
2837 };
2838 bool ReducedInstCount = false;
2839 ReducedInstCount |= MergeInner(X, 0, NewMask0, CostKind, LHS);
2840 ReducedInstCount |= MergeInner(Y, 0, NewMask1, CostKind, LHS);
2841 ReducedInstCount |= MergeInner(Z, NumSrcElts, NewMask0, CostKind, RHS);
2842 ReducedInstCount |= MergeInner(W, NumSrcElts, NewMask1, CostKind, RHS);
2843 bool SingleSrcBinOp = (X == Y) && (Z == W) && (NewMask0 == NewMask1);
2844 // SingleSrcBinOp only reduces instruction count if we also eliminate the
2845 // original binop(s). If binops have multiple uses, they won't be eliminated.
2846 ReducedInstCount |= SingleSrcBinOp && LHS->hasOneUser() && RHS->hasOneUser();
2847
2848 // For concat shuffles of i1 vectors where both binops are one-use, the
2849 // transform keeps the same instruction count but canonicalises to a single
2850 // wider binop, enabling downstream folds (e.g. NOT(XOR(concat(a,b),
2851 // concat(c,d))) -> XNOR(concat(a,b),concat(c,d)) on AVX-512 mask regs).
2852 // Restrict to BinaryOperator (not CmpInst) since narrow comparisons may
2853 // be cheaper than wide ones on some targets (e.g. AVX-512 vpcmpeq).
2854 ReducedInstCount |= cast<ShuffleVectorInst>(&I)->isConcat() &&
2855 I.getType()->getScalarType()->isIntegerTy(1) &&
2857 RHS->hasOneUser();
2858
2859 auto *ShuffleCmpTy =
2860 FixedVectorType::get(BinOpTy->getElementType(), ShuffleDstTy);
2862 SK0, ShuffleCmpTy, BinOpTy, CostKind, NewMask0, 0, nullptr, {X, Z});
2863 if (!SingleSrcBinOp)
2864 NewCost += TTI.getShuffleCost(SK1, ShuffleCmpTy, BinOpTy, CostKind,
2865 NewMask1, 0, nullptr, {Y, W});
2866
2867 if (PredLHS == CmpInst::BAD_ICMP_PREDICATE) {
2868 NewCost += TTI.getArithmeticInstrCost(LHS->getOpcode(), ShuffleDstTy,
2869 CostKind, Op0Info, Op1Info);
2870 } else {
2871 NewCost +=
2872 TTI.getCmpSelInstrCost(LHS->getOpcode(), ShuffleCmpTy, ShuffleDstTy,
2873 PredLHS, CostKind, Op0Info, Op1Info);
2874 }
2875 // If LHS/RHS have other uses, we need to account for the cost of keeping
2876 // the original instructions. When SameBinOp, only add the cost once.
2877 if (!LHS->hasOneUser())
2878 NewCost += LHSCost;
2879 if (!SameBinOp && !RHS->hasOneUser())
2880 NewCost += RHSCost;
2881
2882 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two binops: " << I
2883 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
2884 << "\n");
2885
2886 // If either shuffle will constant fold away, then fold for the same cost as
2887 // we will reduce the instruction count.
2888 ReducedInstCount |= (isa<Constant>(X) && isa<Constant>(Z)) ||
2889 (isa<Constant>(Y) && isa<Constant>(W));
2890 if (ReducedInstCount ? (NewCost > OldCost) : (NewCost >= OldCost))
2891 return false;
2892
2893 Value *Shuf0 = Builder.CreateShuffleVector(X, Z, NewMask0);
2894 Value *Shuf1 =
2895 SingleSrcBinOp ? Shuf0 : Builder.CreateShuffleVector(Y, W, NewMask1);
2896 Value *NewBO = PredLHS == CmpInst::BAD_ICMP_PREDICATE
2897 ? Builder.CreateBinOp(
2898 cast<BinaryOperator>(LHS)->getOpcode(), Shuf0, Shuf1)
2899 : Builder.CreateCmp(PredLHS, Shuf0, Shuf1);
2900
2901 // Intersect flags from the old binops.
2902 if (auto *NewInst = dyn_cast<Instruction>(NewBO)) {
2903 NewInst->copyIRFlags(LHS);
2904 NewInst->andIRFlags(RHS);
2905 }
2906
2907 replaceValue(I, *NewBO);
2908 return true;
2909}
2910
2911/// Try to convert,
2912/// (shuffle(select(c1,t1,f1)), (select(c2,t2,f2)), m) into
2913/// (select (shuffle c1,c2,m), (shuffle t1,t2,m), (shuffle f1,f2,m))
2914bool VectorCombine::foldShuffleOfSelects(Instruction &I) {
2915 ArrayRef<int> Mask;
2916 Value *C1, *T1, *F1, *C2, *T2, *F2;
2918 m_Select(m_Value(C2), m_Value(T2), m_Value(F2)),
2919 m_Mask(Mask))))
2920 return false;
2921
2922 auto *Sel1 = cast<Instruction>(I.getOperand(0));
2923 auto *Sel2 = cast<Instruction>(I.getOperand(1));
2924
2925 auto *C1VecTy = dyn_cast<FixedVectorType>(C1->getType());
2926 auto *C2VecTy = dyn_cast<FixedVectorType>(C2->getType());
2927 if (!C1VecTy || !C2VecTy || C1VecTy != C2VecTy)
2928 return false;
2929
2930 auto *SI0FOp = dyn_cast<FPMathOperator>(I.getOperand(0));
2931 auto *SI1FOp = dyn_cast<FPMathOperator>(I.getOperand(1));
2932 // SelectInsts must have the same FMF.
2933 if (((SI0FOp == nullptr) != (SI1FOp == nullptr)) ||
2934 ((SI0FOp != nullptr) &&
2935 (SI0FOp->getFastMathFlags() != SI1FOp->getFastMathFlags())))
2936 return false;
2937
2938 auto *SrcVecTy = cast<FixedVectorType>(T1->getType());
2939 auto *DstVecTy = cast<FixedVectorType>(I.getType());
2941 auto SelOp = Instruction::Select;
2942
2944 SelOp, SrcVecTy, C1VecTy, CmpInst::BAD_ICMP_PREDICATE, CostKind);
2946 SelOp, SrcVecTy, C2VecTy, CmpInst::BAD_ICMP_PREDICATE, CostKind);
2947
2948 InstructionCost OldCost =
2949 CostSel1 + CostSel2 +
2950 TTI.getShuffleCost(SK, DstVecTy, SrcVecTy, CostKind, Mask, 0, nullptr,
2951 {I.getOperand(0), I.getOperand(1)}, &I);
2952
2954 SK, FixedVectorType::get(C1VecTy->getScalarType(), Mask.size()), C1VecTy,
2955 CostKind, Mask, 0, nullptr, {C1, C2});
2956 NewCost += TTI.getShuffleCost(SK, DstVecTy, SrcVecTy, CostKind, Mask, 0,
2957 nullptr, {T1, T2});
2958 NewCost += TTI.getShuffleCost(SK, DstVecTy, SrcVecTy, CostKind, Mask, 0,
2959 nullptr, {F1, F2});
2960 auto *C1C2ShuffledVecTy = FixedVectorType::get(
2961 Type::getInt1Ty(I.getContext()), DstVecTy->getNumElements());
2962 NewCost += TTI.getCmpSelInstrCost(SelOp, DstVecTy, C1C2ShuffledVecTy,
2963 CmpInst::BAD_ICMP_PREDICATE, CostKind);
2964
2965 if (!Sel1->hasOneUse())
2966 NewCost += CostSel1;
2967 if (!Sel2->hasOneUse())
2968 NewCost += CostSel2;
2969
2970 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two selects: " << I
2971 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
2972 << "\n");
2973 if (NewCost > OldCost)
2974 return false;
2975
2976 Value *ShuffleCmp = Builder.CreateShuffleVector(C1, C2, Mask);
2977 Value *ShuffleTrue = Builder.CreateShuffleVector(T1, T2, Mask);
2978 Value *ShuffleFalse = Builder.CreateShuffleVector(F1, F2, Mask);
2979 Value *NewSel;
2980 // We presuppose that the SelectInsts have the same FMF.
2981 if (SI0FOp)
2982 NewSel = Builder.CreateSelectFMF(ShuffleCmp, ShuffleTrue, ShuffleFalse,
2983 SI0FOp->getFastMathFlags());
2984 else
2985 NewSel = Builder.CreateSelect(ShuffleCmp, ShuffleTrue, ShuffleFalse);
2986
2987 replaceValue(I, *NewSel);
2988 return true;
2989}
2990
2991/// Try to convert "shuffle (castop), (castop)" with a shared castop operand
2992/// into "castop (shuffle)".
2993bool VectorCombine::foldShuffleOfCastops(Instruction &I) {
2994 Value *V0, *V1;
2995 ArrayRef<int> OldMask;
2996 if (!match(&I, m_Shuffle(m_Value(V0), m_Value(V1), m_Mask(OldMask))))
2997 return false;
2998
2999 // Check whether this is a binary shuffle.
3000 bool IsBinaryShuffle = !isa<UndefValue>(V1);
3001
3002 auto *C0 = dyn_cast<CastInst>(V0);
3003 auto *C1 = dyn_cast<CastInst>(V1);
3004 if (!C0 || (IsBinaryShuffle && !C1))
3005 return false;
3006
3007 Instruction::CastOps Opcode = C0->getOpcode();
3008
3009 // If this is allowed, foldShuffleOfCastops can get stuck in a loop
3010 // with foldBitcastOfShuffle. Reject in favor of foldBitcastOfShuffle.
3011 if (!IsBinaryShuffle && Opcode == Instruction::BitCast)
3012 return false;
3013
3014 if (IsBinaryShuffle) {
3015 if (C0->getSrcTy() != C1->getSrcTy())
3016 return false;
3017 // Handle shuffle(zext_nneg(x), sext(y)) -> sext(shuffle(x,y)) folds.
3018 if (Opcode != C1->getOpcode()) {
3020 Opcode = Instruction::SExt;
3021 else
3022 return false;
3023 }
3024 }
3025
3026 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
3027 auto *CastDstTy = dyn_cast<FixedVectorType>(C0->getDestTy());
3028 auto *CastSrcTy = dyn_cast<FixedVectorType>(C0->getSrcTy());
3029 if (!ShuffleDstTy || !CastDstTy || !CastSrcTy)
3030 return false;
3031
3032 unsigned NumSrcElts = CastSrcTy->getNumElements();
3033 unsigned NumDstElts = CastDstTy->getNumElements();
3034 assert((NumDstElts == NumSrcElts || Opcode == Instruction::BitCast) &&
3035 "Only bitcasts expected to alter src/dst element counts");
3036
3037 // Check for bitcasting of unscalable vector types.
3038 // e.g. <32 x i40> -> <40 x i32>
3039 if (NumDstElts != NumSrcElts && (NumSrcElts % NumDstElts) != 0 &&
3040 (NumDstElts % NumSrcElts) != 0)
3041 return false;
3042
3043 SmallVector<int, 16> NewMask;
3044 if (NumSrcElts >= NumDstElts) {
3045 // The bitcast is from wide to narrow/equal elements. The shuffle mask can
3046 // always be expanded to the equivalent form choosing narrower elements.
3047 assert(NumSrcElts % NumDstElts == 0 && "Unexpected shuffle mask");
3048 unsigned ScaleFactor = NumSrcElts / NumDstElts;
3049 narrowShuffleMaskElts(ScaleFactor, OldMask, NewMask);
3050 } else {
3051 // The bitcast is from narrow elements to wide elements. The shuffle mask
3052 // must choose consecutive elements to allow casting first.
3053 assert(NumDstElts % NumSrcElts == 0 && "Unexpected shuffle mask");
3054 unsigned ScaleFactor = NumDstElts / NumSrcElts;
3055 if (!widenShuffleMaskElts(ScaleFactor, OldMask, NewMask))
3056 return false;
3057 }
3058
3059 auto *NewShuffleDstTy =
3060 FixedVectorType::get(CastSrcTy->getScalarType(), NewMask.size());
3061
3062 // Try to replace a castop with a shuffle if the shuffle is not costly.
3063 InstructionCost CostC0 =
3064 TTI.getCastInstrCost(C0->getOpcode(), CastDstTy, CastSrcTy,
3065 TTI::CastContextHint::None, CostKind, C0);
3066
3068 if (IsBinaryShuffle)
3070 else
3072
3073 InstructionCost OldCost = CostC0;
3074 OldCost += TTI.getShuffleCost(ShuffleKind, ShuffleDstTy, CastDstTy, CostKind,
3075 OldMask, 0, nullptr, {}, &I);
3076
3077 InstructionCost NewCost = TTI.getShuffleCost(ShuffleKind, NewShuffleDstTy,
3078 CastSrcTy, CostKind, NewMask);
3079 NewCost += TTI.getCastInstrCost(Opcode, ShuffleDstTy, NewShuffleDstTy,
3080 TTI::CastContextHint::None, CostKind);
3081 if (!C0->hasOneUse())
3082 NewCost += CostC0;
3083 if (IsBinaryShuffle) {
3084 InstructionCost CostC1 =
3085 TTI.getCastInstrCost(C1->getOpcode(), CastDstTy, CastSrcTy,
3086 TTI::CastContextHint::None, CostKind, C1);
3087 OldCost += CostC1;
3088 if (!C1->hasOneUse())
3089 NewCost += CostC1;
3090 }
3091
3092 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two casts: " << I
3093 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
3094 << "\n");
3095 if (NewCost > OldCost)
3096 return false;
3097
3098 Value *Shuf;
3099 if (IsBinaryShuffle)
3100 Shuf = Builder.CreateShuffleVector(C0->getOperand(0), C1->getOperand(0),
3101 NewMask);
3102 else
3103 Shuf = Builder.CreateShuffleVector(C0->getOperand(0), NewMask);
3104
3105 Value *Cast = Builder.CreateCast(Opcode, Shuf, ShuffleDstTy);
3106
3107 // Intersect flags from the old casts.
3108 if (auto *NewInst = dyn_cast<Instruction>(Cast)) {
3109 NewInst->copyIRFlags(C0);
3110 if (IsBinaryShuffle)
3111 NewInst->andIRFlags(C1);
3112 }
3113
3114 replaceValue(I, *Cast);
3115 return true;
3116}
3117
3118/// Try to convert any of:
3119/// "shuffle (shuffle x, y), (shuffle y, x)"
3120/// "shuffle (shuffle x, undef), (shuffle y, undef)"
3121/// "shuffle (shuffle x, undef), y"
3122/// "shuffle x, (shuffle y, undef)"
3123/// into "shuffle x, y".
3124bool VectorCombine::foldShuffleOfShuffles(Instruction &I) {
3125 ArrayRef<int> OuterMask;
3126 Value *OuterV0, *OuterV1;
3127 if (!match(&I,
3128 m_Shuffle(m_Value(OuterV0), m_Value(OuterV1), m_Mask(OuterMask))))
3129 return false;
3130
3131 ArrayRef<int> InnerMask0, InnerMask1;
3132 Value *X0, *X1, *Y0, *Y1;
3133 bool Match0 =
3134 match(OuterV0, m_Shuffle(m_Value(X0), m_Value(Y0), m_Mask(InnerMask0)));
3135 bool Match1 =
3136 match(OuterV1, m_Shuffle(m_Value(X1), m_Value(Y1), m_Mask(InnerMask1)));
3137 if (!Match0 && !Match1)
3138 return false;
3139
3140 // If the outer shuffle is a permute, then create a fake inner all-poison
3141 // shuffle. This is easier than accounting for length-changing shuffles below.
3142 SmallVector<int, 16> PoisonMask1;
3143 if (!Match1 && isa<PoisonValue>(OuterV1)) {
3144 X1 = X0;
3145 Y1 = Y0;
3146 PoisonMask1.append(InnerMask0.size(), PoisonMaskElem);
3147 InnerMask1 = PoisonMask1;
3148 Match1 = true; // fake match
3149 }
3150
3151 X0 = Match0 ? X0 : OuterV0;
3152 Y0 = Match0 ? Y0 : OuterV0;
3153 X1 = Match1 ? X1 : OuterV1;
3154 Y1 = Match1 ? Y1 : OuterV1;
3155 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
3156 auto *ShuffleSrcTy = dyn_cast<FixedVectorType>(X0->getType());
3157 auto *ShuffleImmTy = dyn_cast<FixedVectorType>(OuterV0->getType());
3158 if (!ShuffleDstTy || !ShuffleSrcTy || !ShuffleImmTy ||
3159 X0->getType() != X1->getType())
3160 return false;
3161
3162 unsigned NumSrcElts = ShuffleSrcTy->getNumElements();
3163 unsigned NumImmElts = ShuffleImmTy->getNumElements();
3164
3165 // Attempt to merge shuffles, matching upto 2 source operands.
3166 // Replace index to a poison arg with PoisonMaskElem.
3167 // Bail if either inner masks reference an undef arg.
3168 SmallVector<int, 16> NewMask(OuterMask);
3169 Value *NewX = nullptr, *NewY = nullptr;
3170 for (int &M : NewMask) {
3171 Value *Src = nullptr;
3172 if (0 <= M && M < (int)NumImmElts) {
3173 Src = OuterV0;
3174 if (Match0) {
3175 M = InnerMask0[M];
3176 Src = M >= (int)NumSrcElts ? Y0 : X0;
3177 M = M >= (int)NumSrcElts ? (M - NumSrcElts) : M;
3178 }
3179 } else if (M >= (int)NumImmElts) {
3180 Src = OuterV1;
3181 M -= NumImmElts;
3182 if (Match1) {
3183 M = InnerMask1[M];
3184 Src = M >= (int)NumSrcElts ? Y1 : X1;
3185 M = M >= (int)NumSrcElts ? (M - NumSrcElts) : M;
3186 }
3187 }
3188 if (Src && M != PoisonMaskElem) {
3189 assert(0 <= M && M < (int)NumSrcElts && "Unexpected shuffle mask index");
3190 if (isa<UndefValue>(Src)) {
3191 // We've referenced an undef element - if its poison, update the shuffle
3192 // mask, else bail.
3193 if (!isa<PoisonValue>(Src))
3194 return false;
3195 M = PoisonMaskElem;
3196 continue;
3197 }
3198 if (!NewX || NewX == Src) {
3199 NewX = Src;
3200 continue;
3201 }
3202 if (!NewY || NewY == Src) {
3203 M += NumSrcElts;
3204 NewY = Src;
3205 continue;
3206 }
3207 return false;
3208 }
3209 }
3210
3211 if (!NewX) {
3212 replaceValue(I, *PoisonValue::get(ShuffleDstTy));
3213 return true;
3214 }
3215
3216 if (!NewY)
3217 NewY = PoisonValue::get(ShuffleSrcTy);
3218
3219 // Have we folded to an Identity shuffle?
3220 if (ShuffleVectorInst::isIdentityMask(NewMask, NumSrcElts)) {
3221 replaceValue(I, *NewX);
3222 return true;
3223 }
3224
3225 // Try to merge the shuffles if the new shuffle is not costly.
3226 InstructionCost InnerCost0 = 0;
3227 if (Match0)
3228 InnerCost0 = TTI.getInstructionCost(cast<User>(OuterV0), CostKind);
3229
3230 InstructionCost InnerCost1 = 0;
3231 if (Match1)
3232 InnerCost1 = TTI.getInstructionCost(cast<User>(OuterV1), CostKind);
3233
3234 InstructionCost OuterCost = TTI.getInstructionCost(&I, CostKind);
3235
3236 InstructionCost OldCost = InnerCost0 + InnerCost1 + OuterCost;
3237
3238 bool IsUnary = all_of(NewMask, [&](int M) { return M < (int)NumSrcElts; });
3242 InstructionCost NewCost =
3243 TTI.getShuffleCost(SK, ShuffleDstTy, ShuffleSrcTy, CostKind, NewMask, 0,
3244 nullptr, {NewX, NewY});
3245 if (!OuterV0->hasOneUse())
3246 NewCost += InnerCost0;
3247 if (!OuterV1->hasOneUse())
3248 NewCost += InnerCost1;
3249
3250 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two shuffles: " << I
3251 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
3252 << "\n");
3253 if (NewCost > OldCost)
3254 return false;
3255
3256 Value *Shuf = Builder.CreateShuffleVector(NewX, NewY, NewMask);
3257 replaceValue(I, *Shuf);
3258 return true;
3259}
3260
3261/// Try to convert a chain of length-preserving shuffles that are fed by
3262/// length-changing shuffles from the same source, e.g. a chain of length 3:
3263///
3264/// "shuffle (shuffle (shuffle x, (shuffle y, undef)),
3265/// (shuffle y, undef)),
3266// (shuffle y, undef)"
3267///
3268/// into a single shuffle fed by a length-changing shuffle:
3269///
3270/// "shuffle x, (shuffle y, undef)"
3271///
3272/// Such chains arise e.g. from folding extract/insert sequences.
3273bool VectorCombine::foldShufflesOfLengthChangingShuffles(Instruction &I) {
3274 FixedVectorType *TrunkType = dyn_cast<FixedVectorType>(I.getType());
3275 if (!TrunkType)
3276 return false;
3277
3278 unsigned ChainLength = 0;
3279 SmallVector<int> Mask;
3280 SmallVector<int> YMask;
3281 InstructionCost OldCost = 0;
3282 InstructionCost NewCost = 0;
3283 Value *Trunk = &I;
3284 unsigned NumTrunkElts = TrunkType->getNumElements();
3285 Value *Y = nullptr;
3286
3287 for (;;) {
3288 // Match the current trunk against (commutations of) the pattern
3289 // "shuffle trunk', (shuffle y, undef)"
3290 ArrayRef<int> OuterMask;
3291 Value *OuterV0, *OuterV1;
3292 if (ChainLength != 0 && !Trunk->hasOneUse())
3293 break;
3294 if (!match(Trunk, m_Shuffle(m_Value(OuterV0), m_Value(OuterV1),
3295 m_Mask(OuterMask))))
3296 break;
3297 if (OuterV0->getType() != TrunkType) {
3298 // This shuffle is not length-preserving, so it cannot be part of the
3299 // chain.
3300 break;
3301 }
3302
3303 ArrayRef<int> InnerMask0, InnerMask1;
3304 Value *A0, *A1, *B0, *B1;
3305 bool Match0 =
3306 match(OuterV0, m_Shuffle(m_Value(A0), m_Value(B0), m_Mask(InnerMask0)));
3307 bool Match1 =
3308 match(OuterV1, m_Shuffle(m_Value(A1), m_Value(B1), m_Mask(InnerMask1)));
3309 bool Match0Leaf = Match0 && A0->getType() != I.getType();
3310 bool Match1Leaf = Match1 && A1->getType() != I.getType();
3311 if (Match0Leaf == Match1Leaf) {
3312 // Only handle the case of exactly one leaf in each step. The "two leaves"
3313 // case is handled by foldShuffleOfShuffles.
3314 break;
3315 }
3316
3317 SmallVector<int> CommutedOuterMask;
3318 if (Match0Leaf) {
3319 std::swap(OuterV0, OuterV1);
3320 std::swap(InnerMask0, InnerMask1);
3321 std::swap(A0, A1);
3322 std::swap(B0, B1);
3323 llvm::append_range(CommutedOuterMask, OuterMask);
3324 for (int &M : CommutedOuterMask) {
3325 if (M == PoisonMaskElem)
3326 continue;
3327 if (M < (int)NumTrunkElts)
3328 M += NumTrunkElts;
3329 else
3330 M -= NumTrunkElts;
3331 }
3332 OuterMask = CommutedOuterMask;
3333 }
3334 if (!OuterV1->hasOneUse())
3335 break;
3336
3337 if (!isa<UndefValue>(A1)) {
3338 if (!Y)
3339 Y = A1;
3340 else if (Y != A1)
3341 break;
3342 }
3343 if (!isa<UndefValue>(B1)) {
3344 if (!Y)
3345 Y = B1;
3346 else if (Y != B1)
3347 break;
3348 }
3349
3350 auto *YType = cast<FixedVectorType>(A1->getType());
3351 int NumLeafElts = YType->getNumElements();
3352 SmallVector<int> LocalYMask(InnerMask1);
3353 for (int &M : LocalYMask) {
3354 if (M >= NumLeafElts)
3355 M -= NumLeafElts;
3356 }
3357
3358 InstructionCost LocalOldCost =
3359 TTI.getInstructionCost(cast<User>(Trunk), CostKind) +
3360 TTI.getInstructionCost(cast<User>(OuterV1), CostKind);
3361
3362 // Handle the initial (start of chain) case.
3363 if (!ChainLength) {
3364 Mask.assign(OuterMask);
3365 YMask.assign(LocalYMask);
3366 OldCost = NewCost = LocalOldCost;
3367 Trunk = OuterV0;
3368 ChainLength++;
3369 continue;
3370 }
3371
3372 // For the non-root case, first attempt to combine masks.
3373 SmallVector<int> NewYMask(YMask);
3374 bool Valid = true;
3375 for (auto [CombinedM, LeafM] : llvm::zip(NewYMask, LocalYMask)) {
3376 if (LeafM == -1 || CombinedM == LeafM)
3377 continue;
3378 if (CombinedM == -1) {
3379 CombinedM = LeafM;
3380 } else {
3381 Valid = false;
3382 break;
3383 }
3384 }
3385 if (!Valid)
3386 break;
3387
3388 SmallVector<int> NewMask;
3389 NewMask.reserve(NumTrunkElts);
3390 for (int M : Mask) {
3391 if (M < 0 || M >= static_cast<int>(NumTrunkElts))
3392 NewMask.push_back(M);
3393 else
3394 NewMask.push_back(OuterMask[M]);
3395 }
3396
3397 // Break the chain if adding this new step complicates the shuffles such
3398 // that it would increase the new cost by more than the old cost of this
3399 // step.
3400 InstructionCost LocalNewCost =
3402 YType, CostKind, NewYMask) +
3404 TrunkType, CostKind, NewMask);
3405
3406 if (LocalNewCost >= NewCost && LocalOldCost < LocalNewCost - NewCost)
3407 break;
3408
3409 LLVM_DEBUG({
3410 if (ChainLength == 1) {
3411 dbgs() << "Found chain of shuffles fed by length-changing shuffles: "
3412 << I << '\n';
3413 }
3414 dbgs() << " next chain link: " << *Trunk << '\n'
3415 << " old cost: " << (OldCost + LocalOldCost)
3416 << " new cost: " << LocalNewCost << '\n';
3417 });
3418
3419 Mask = NewMask;
3420 YMask = NewYMask;
3421 OldCost += LocalOldCost;
3422 NewCost = LocalNewCost;
3423 Trunk = OuterV0;
3424 ChainLength++;
3425 }
3426 if (ChainLength <= 1)
3427 return false;
3428
3429 // Bail out if all leaves were poison.
3430 if (!Y)
3431 return false;
3432
3433 if (llvm::all_of(Mask, [&](int M) {
3434 return M < 0 || M >= static_cast<int>(NumTrunkElts);
3435 })) {
3436 // Produce a canonical simplified form if all elements are sourced from Y.
3437 for (int &M : Mask) {
3438 if (M >= static_cast<int>(NumTrunkElts))
3439 M = YMask[M - NumTrunkElts];
3440 }
3441 Value *Root =
3442 Builder.CreateShuffleVector(Y, PoisonValue::get(Y->getType()), Mask);
3443 replaceValue(I, *Root);
3444 return true;
3445 }
3446
3447 Value *Leaf =
3448 Builder.CreateShuffleVector(Y, PoisonValue::get(Y->getType()), YMask);
3449 Value *Root = Builder.CreateShuffleVector(Trunk, Leaf, Mask);
3450 replaceValue(I, *Root);
3451 return true;
3452}
3453
3454/// Try to convert
3455/// "shuffle (intrinsic), (intrinsic)" into "intrinsic (shuffle), (shuffle)".
3456bool VectorCombine::foldShuffleOfIntrinsics(Instruction &I) {
3457 Value *V0, *V1;
3458 ArrayRef<int> OldMask;
3459 if (!match(&I, m_Shuffle(m_Value(V0), m_Value(V1), m_Mask(OldMask))))
3460 return false;
3461
3462 auto *II0 = dyn_cast<IntrinsicInst>(V0);
3463 auto *II1 = dyn_cast<IntrinsicInst>(V1);
3464 if (!II0 || !II1)
3465 return false;
3466
3467 Intrinsic::ID IID = II0->getIntrinsicID();
3468 if (IID != II1->getIntrinsicID())
3469 return false;
3470 InstructionCost CostII0 =
3471 TTI.getIntrinsicInstrCost(IntrinsicCostAttributes(IID, *II0), CostKind);
3472 InstructionCost CostII1 =
3473 TTI.getIntrinsicInstrCost(IntrinsicCostAttributes(IID, *II1), CostKind);
3474
3475 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
3476 auto *II0Ty = dyn_cast<FixedVectorType>(II0->getType());
3477 if (!ShuffleDstTy || !II0Ty)
3478 return false;
3479
3480 if (!isTriviallyVectorizable(IID))
3481 return false;
3482
3483 for (unsigned Idx = 0, E = II0->arg_size(); Idx != E; ++Idx) {
3484 Value *Arg0 = II0->getArgOperand(Idx);
3485 Value *Arg1 = II1->getArgOperand(Idx);
3486 if (isVectorIntrinsicWithScalarOpAtArg(IID, Idx, &TTI)) {
3487 // Scalar operands must be identical.
3488 if (Arg0 != Arg1)
3489 return false;
3490 } else if (Arg0->getType() != Arg1->getType()) {
3491 // The corresponding vector operands are shuffled together, so they must
3492 // share the same type. For intrinsics overloaded on their operand type
3493 // (e.g. llvm.fptosi.sat), two calls can produce the same result type
3494 // from different operand types; shuffling those would be invalid.
3495 return false;
3496 }
3497 }
3498
3499 InstructionCost OldCost =
3500 CostII0 + CostII1 +
3502 II0Ty, CostKind, OldMask, 0, nullptr, {II0, II1}, &I);
3503
3504 SmallVector<Type *> NewArgsTy;
3505 InstructionCost NewCost = 0;
3506 SmallDenseSet<std::pair<Value *, Value *>> SeenOperandPairs;
3507 for (unsigned Idx = 0, E = II0->arg_size(); Idx != E; ++Idx) {
3508 if (isVectorIntrinsicWithScalarOpAtArg(IID, Idx, &TTI)) {
3509 NewArgsTy.push_back(II0->getArgOperand(Idx)->getType());
3510 } else {
3511 auto *VecTy = cast<FixedVectorType>(II0->getArgOperand(Idx)->getType());
3512 auto *ArgTy = FixedVectorType::get(VecTy->getElementType(),
3513 ShuffleDstTy->getNumElements());
3514 NewArgsTy.push_back(ArgTy);
3515 std::pair<Value *, Value *> OperandPair =
3516 std::make_pair(II0->getArgOperand(Idx), II1->getArgOperand(Idx));
3517 if (!SeenOperandPairs.insert(OperandPair).second) {
3518 // We've already computed the cost for this operand pair.
3519 continue;
3520 }
3521 NewCost += TTI.getShuffleCost(
3522 TargetTransformInfo::SK_PermuteTwoSrc, ArgTy, VecTy, CostKind,
3523 OldMask, 0, nullptr,
3524 {II0->getArgOperand(Idx), II1->getArgOperand(Idx)});
3525 }
3526 }
3527 IntrinsicCostAttributes NewAttr(IID, ShuffleDstTy, NewArgsTy);
3528
3529 NewCost += TTI.getIntrinsicInstrCost(NewAttr, CostKind);
3530 if (!II0->hasOneUse())
3531 NewCost += CostII0;
3532 if (II1 != II0 && !II1->hasOneUse())
3533 NewCost += CostII1;
3534
3535 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two intrinsics: " << I
3536 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
3537 << "\n");
3538
3539 if (NewCost > OldCost)
3540 return false;
3541
3542 SmallVector<Value *> NewArgs;
3543 SmallDenseMap<std::pair<Value *, Value *>, Value *> ShuffleCache;
3544 for (unsigned Idx = 0, E = II0->arg_size(); Idx != E; ++Idx) {
3545 if (isVectorIntrinsicWithScalarOpAtArg(IID, Idx, &TTI)) {
3546 NewArgs.push_back(II0->getArgOperand(Idx));
3547 } else {
3548 std::pair<Value *, Value *> OperandPair =
3549 std::make_pair(II0->getArgOperand(Idx), II1->getArgOperand(Idx));
3550 auto It = ShuffleCache.find(OperandPair);
3551 if (It != ShuffleCache.end()) {
3552 // Reuse previously created shuffle for this operand pair.
3553 NewArgs.push_back(It->second);
3554 continue;
3555 }
3556 Value *Shuf = Builder.CreateShuffleVector(
3557 II0->getArgOperand(Idx), II1->getArgOperand(Idx), OldMask);
3558 ShuffleCache[OperandPair] = Shuf;
3559 NewArgs.push_back(Shuf);
3560 }
3561 }
3562 Value *NewIntrinsic = Builder.CreateIntrinsic(ShuffleDstTy, IID, NewArgs);
3563
3564 // Intersect flags from the old intrinsics.
3565 if (auto *NewInst = dyn_cast<Instruction>(NewIntrinsic)) {
3566 NewInst->copyIRFlags(II0);
3567 NewInst->andIRFlags(II1);
3568 }
3569
3570 replaceValue(I, *NewIntrinsic);
3571 return true;
3572}
3573
3574/// Try to convert
3575/// "shuffle (intrinsic), (poison/undef)" into "intrinsic (shuffle)".
3576bool VectorCombine::foldPermuteOfIntrinsic(Instruction &I) {
3577 Value *V0;
3578 ArrayRef<int> Mask;
3579 if (!match(&I, m_Shuffle(m_Value(V0), m_Undef(), m_Mask(Mask))))
3580 return false;
3581
3582 auto *II0 = dyn_cast<IntrinsicInst>(V0);
3583 if (!II0)
3584 return false;
3585
3586 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
3587 auto *IntrinsicSrcTy = dyn_cast<FixedVectorType>(II0->getType());
3588 if (!ShuffleDstTy || !IntrinsicSrcTy)
3589 return false;
3590
3591 // Validate it's a pure permute, mask should only reference the first vector
3592 unsigned NumSrcElts = IntrinsicSrcTy->getNumElements();
3593 if (any_of(Mask, [NumSrcElts](int M) { return M >= (int)NumSrcElts; }))
3594 return false;
3595
3596 Intrinsic::ID IID = II0->getIntrinsicID();
3597 if (!isTriviallyVectorizable(IID))
3598 return false;
3599
3600 // Cost analysis
3602 TTI.getIntrinsicInstrCost(IntrinsicCostAttributes(IID, *II0), CostKind);
3603 InstructionCost OldCost =
3606 IntrinsicSrcTy, CostKind, Mask, 0, nullptr, {V0}, &I);
3607
3608 SmallVector<Type *> NewArgsTy;
3609 InstructionCost NewCost = 0;
3610 for (unsigned I = 0, E = II0->arg_size(); I != E; ++I) {
3612 NewArgsTy.push_back(II0->getArgOperand(I)->getType());
3613 } else {
3614 auto *VecTy = cast<FixedVectorType>(II0->getArgOperand(I)->getType());
3615 auto *ArgTy = FixedVectorType::get(VecTy->getElementType(),
3616 ShuffleDstTy->getNumElements());
3617 NewArgsTy.push_back(ArgTy);
3619 ArgTy, VecTy, CostKind, Mask, 0, nullptr,
3620 {II0->getArgOperand(I)});
3621 }
3622 }
3623 IntrinsicCostAttributes NewAttr(IID, ShuffleDstTy, NewArgsTy);
3624 NewCost += TTI.getIntrinsicInstrCost(NewAttr, CostKind);
3625
3626 // If the intrinsic has multiple uses, we need to account for the cost of
3627 // keeping the original intrinsic around.
3628 if (!II0->hasOneUse())
3629 NewCost += IntrinsicCost;
3630
3631 LLVM_DEBUG(dbgs() << "Found a permute of intrinsic: " << I << "\n OldCost: "
3632 << OldCost << " vs NewCost: " << NewCost << "\n");
3633
3634 if (NewCost > OldCost)
3635 return false;
3636
3637 // Transform
3638 SmallVector<Value *> NewArgs;
3639 for (unsigned I = 0, E = II0->arg_size(); I != E; ++I) {
3641 NewArgs.push_back(II0->getArgOperand(I));
3642 } else {
3643 Value *Shuf = Builder.CreateShuffleVector(II0->getArgOperand(I), Mask);
3644 NewArgs.push_back(Shuf);
3645 }
3646 }
3647
3648 Value *NewIntrinsic = Builder.CreateIntrinsic(ShuffleDstTy, IID, NewArgs);
3649
3650 if (auto *NewInst = dyn_cast<Instruction>(NewIntrinsic))
3651 NewInst->copyIRFlags(II0);
3652
3653 replaceValue(I, *NewIntrinsic);
3654 return true;
3655}
3656
3657using InstLane = std::pair<Value *, int>;
3658
3660 while (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
3661 unsigned NumElts =
3662 cast<FixedVectorType>(SV->getOperand(0)->getType())->getNumElements();
3663 int M = SV->getMaskValue(Lane);
3664 if (M < 0)
3665 return {nullptr, PoisonMaskElem};
3666 if (static_cast<unsigned>(M) < NumElts) {
3667 V = SV->getOperand(0);
3668 Lane = M;
3669 } else {
3670 V = SV->getOperand(1);
3671 Lane = M - NumElts;
3672 }
3673 }
3674 return InstLane{V, Lane};
3675}
3676
3680 for (InstLane IL : Item) {
3681 auto [U, Lane] = IL;
3682 InstLane OpLane =
3683 U ? lookThroughShuffles(cast<Instruction>(U)->getOperand(Op), Lane)
3684 : InstLane{nullptr, PoisonMaskElem};
3685 NItem.emplace_back(OpLane);
3686 }
3687 return NItem;
3688}
3689
3690/// Detect concat of multiple values into a vector
3692 const TargetTransformInfo &TTI) {
3693 auto *Ty = cast<FixedVectorType>(Item.front().first->getType());
3694 unsigned NumElts = Ty->getNumElements();
3695 if (Item.size() == NumElts || NumElts == 1 || Item.size() % NumElts != 0)
3696 return false;
3697
3698 // Check that the concat is free, usually meaning that the type will be split
3699 // during legalization.
3700 SmallVector<int, 16> ConcatMask(NumElts * 2);
3701 std::iota(ConcatMask.begin(), ConcatMask.end(), 0);
3702 if (TTI.getShuffleCost(TTI::SK_PermuteTwoSrc,
3703 FixedVectorType::get(Ty->getScalarType(), NumElts * 2),
3704 Ty, CostKind, ConcatMask) != 0)
3705 return false;
3706
3707 unsigned NumSlices = Item.size() / NumElts;
3708 // Currently we generate a tree of shuffles for the concats, which limits us
3709 // to a power2.
3710 if (!isPowerOf2_32(NumSlices))
3711 return false;
3712 for (unsigned Slice = 0; Slice < NumSlices; ++Slice) {
3713 Value *SliceV = Item[Slice * NumElts].first;
3714 if (!SliceV || SliceV->getType() != Ty)
3715 return false;
3716 for (unsigned Elt = 0; Elt < NumElts; ++Elt) {
3717 auto [V, Lane] = Item[Slice * NumElts + Elt];
3718 if (Lane != static_cast<int>(Elt) || SliceV != V)
3719 return false;
3720 }
3721 }
3722 return true;
3723}
3724
3725static Value *
3727 const DenseSet<std::pair<Value *, Use *>> &IdentityLeafs,
3728 const DenseSet<std::pair<Value *, Use *>> &SplatLeafs,
3729 const DenseSet<std::pair<Value *, Use *>> &ConcatLeafs,
3730 IRBuilderBase &Builder, InstructionWorklist &WorkList,
3731 const TargetTransformInfo *TTI) {
3732 auto [FrontV, FrontLane] = Item.front();
3733
3734 if (IdentityLeafs.contains(std::make_pair(FrontV, From))) {
3735 return FrontV;
3736 }
3737 if (SplatLeafs.contains(std::make_pair(FrontV, From))) {
3738 SmallVector<int, 16> Mask(Item.size(), FrontLane);
3739 return Builder.CreateShuffleVector(FrontV, Mask);
3740 }
3741 if (ConcatLeafs.contains(std::make_pair(FrontV, From))) {
3742 unsigned NumElts =
3743 cast<FixedVectorType>(FrontV->getType())->getNumElements();
3744 SmallVector<Value *> Values(Item.size() / NumElts, nullptr);
3745 for (unsigned S = 0; S < Values.size(); ++S)
3746 Values[S] = Item[S * NumElts].first;
3747
3748 while (Values.size() > 1) {
3749 NumElts *= 2;
3750 SmallVector<int, 16> Mask(NumElts, 0);
3751 std::iota(Mask.begin(), Mask.end(), 0);
3752 SmallVector<Value *> NewValues(Values.size() / 2, nullptr);
3753 for (unsigned S = 0; S < NewValues.size(); ++S)
3754 NewValues[S] =
3755 Builder.CreateShuffleVector(Values[S * 2], Values[S * 2 + 1], Mask);
3756 Values = NewValues;
3757 }
3758 return Values[0];
3759 }
3760
3761 auto *I = cast<Instruction>(FrontV);
3762
3763 // Handle vector bitcasts that change element count. We cannot use
3764 // generateInstLaneVectorFromOperand for these because the lane indices
3765 // don't map 1:1 through the bitcast.
3766 if (auto *BitCast = dyn_cast<BitCastInst>(I)) {
3767 auto *BCDstTy = dyn_cast<FixedVectorType>(BitCast->getDestTy());
3768 auto *BCSrcTy = dyn_cast<FixedVectorType>(BitCast->getSrcTy());
3769 if (BCDstTy && BCSrcTy &&
3770 BCDstTy->getElementCount() != BCSrcTy->getElementCount()) {
3771 unsigned DstElts = BCDstTy->getNumElements();
3772 unsigned SrcElts = BCSrcTy->getNumElements();
3773 SmallVector<InstLane> NewItem;
3774 if (DstElts > SrcElts) {
3775 // Widening: compress operand Item.
3776 unsigned R = DstElts / SrcElts;
3777 if (Item.size() % R != 0)
3778 return nullptr;
3779 for (unsigned Idx = 0, E = Item.size(); Idx < E; Idx += R) {
3780 auto [V, Lane] = Item[Idx];
3781 if (!V) {
3782 NewItem.push_back({nullptr, PoisonMaskElem});
3783 continue;
3784 }
3785 NewItem.push_back(
3786 lookThroughShuffles(cast<Operator>(V)->getOperand(0), Lane / R));
3787 }
3788 } else {
3789 // Narrowing: expand operand Item.
3790 unsigned R = SrcElts / DstElts;
3791 for (auto [V, Lane] : Item) {
3792 if (!V) {
3793 NewItem.append(R, {nullptr, PoisonMaskElem});
3794 continue;
3795 }
3796 Value *Op = cast<Operator>(V)->getOperand(0);
3797 for (unsigned J = 0; J < R; ++J)
3798 NewItem.push_back(lookThroughShuffles(Op, Lane * R + J));
3799 }
3800 }
3801 Value *Op = generateNewInstTree(NewItem, &BitCast->getOperandUse(0),
3802 IdentityLeafs, SplatLeafs, ConcatLeafs,
3803 Builder, WorkList, TTI);
3804 return Builder.CreateBitCast(
3805 Op, FixedVectorType::get(BCDstTy->getScalarType(), Item.size()));
3806 }
3807 }
3808 auto *II = dyn_cast<IntrinsicInst>(I);
3809 unsigned NumOps = I->getNumOperands() - (II ? 1 : 0);
3811 for (unsigned Idx = 0; Idx < NumOps; Idx++) {
3812 if (II &&
3813 isVectorIntrinsicWithScalarOpAtArg(II->getIntrinsicID(), Idx, TTI)) {
3814 Ops[Idx] = II->getOperand(Idx);
3815 continue;
3816 }
3817 Ops[Idx] = generateNewInstTree(
3818 generateInstLaneVectorFromOperand(Item, Idx), &I->getOperandUse(Idx),
3819 IdentityLeafs, SplatLeafs, ConcatLeafs, Builder, WorkList, TTI);
3820 // Don't re-queue the operand of a bitcast we just regenerated. Doing so
3821 // lets foldBitcastShuffle sink the bitcast back into a shuffle(bitcast),
3822 // which foldShuffleToIdentity then re-matches as the same superfluous
3823 // identity - an infinite loop between the two folds.
3824 // TODO: we should fix algorithms in foldBitcastShuffle and
3825 // foldShuffleToIdentity instead of workaround the problem in worklist.
3826 if (isa<BitCastInst>(I) && isa<Instruction>(Ops[Idx]))
3827 WorkList.remove(cast<Instruction>(Ops[Idx]));
3828 }
3829
3830 SmallVector<Value *, 8> ValueList;
3831 for (const auto &Lane : Item)
3832 if (Lane.first)
3833 ValueList.push_back(Lane.first);
3834
3835 Type *DstTy =
3836 FixedVectorType::get(I->getType()->getScalarType(), Item.size());
3837 if (auto *BI = dyn_cast<BinaryOperator>(I)) {
3838 auto *Value = Builder.CreateBinOp((Instruction::BinaryOps)BI->getOpcode(),
3839 Ops[0], Ops[1]);
3840 propagateIRFlags(Value, ValueList);
3841 return Value;
3842 }
3843 if (auto *CI = dyn_cast<CmpInst>(I)) {
3844 auto *Value = Builder.CreateCmp(CI->getPredicate(), Ops[0], Ops[1]);
3845 propagateIRFlags(Value, ValueList);
3846 return Value;
3847 }
3848 if (auto *SI = dyn_cast<SelectInst>(I)) {
3849 auto *Value = Builder.CreateSelect(Ops[0], Ops[1], Ops[2], "", SI);
3850 propagateIRFlags(Value, ValueList);
3851 return Value;
3852 }
3853 if (auto *CI = dyn_cast<CastInst>(I)) {
3854 auto *Value = Builder.CreateCast(CI->getOpcode(), Ops[0], DstTy);
3855 propagateIRFlags(Value, ValueList);
3856 return Value;
3857 }
3858 if (II) {
3859 auto *Value = Builder.CreateIntrinsic(DstTy, II->getIntrinsicID(), Ops);
3860 propagateIRFlags(Value, ValueList);
3861 return Value;
3862 }
3863 assert(isa<UnaryInstruction>(I) && "Unexpected instruction type in Generate");
3864 auto *Value =
3865 Builder.CreateUnOp((Instruction::UnaryOps)I->getOpcode(), Ops[0]);
3866 propagateIRFlags(Value, ValueList);
3867 return Value;
3868}
3869
3870// Starting from a shuffle, look up through operands tracking the shuffled index
3871// of each lane. If we can simplify away the shuffles to identities then
3872// do so.
3873bool VectorCombine::foldShuffleToIdentity(Instruction &I) {
3874 auto *Ty = dyn_cast<FixedVectorType>(I.getType());
3875 if (!Ty || I.use_empty())
3876 return false;
3877
3878 SmallVector<InstLane> Start(Ty->getNumElements());
3879 for (unsigned M = 0, E = Ty->getNumElements(); M < E; ++M)
3880 Start[M] = lookThroughShuffles(&I, M);
3881
3883 Candidates.push_back(std::make_pair(Start, &*I.use_begin()));
3884 DenseSet<std::pair<Value *, Use *>> IdentityLeafs, SplatLeafs, ConcatLeafs;
3885 unsigned NumVisited = 0;
3886 bool TraversedElCountChangingBitcast = false;
3887
3888 while (!Candidates.empty()) {
3889 if (++NumVisited > Opts.vector_combine_max_scan_instrs)
3890 return false;
3891
3892 auto ItemFrom = Candidates.pop_back_val();
3893 auto Item = ItemFrom.first;
3894 auto From = ItemFrom.second;
3895 auto [FrontV, FrontLane] = Item.front();
3896
3897 // If we found an undef first lane then bail out to keep things simple.
3898 if (!FrontV)
3899 return false;
3900
3901 // Look for an identity value.
3902 if (FrontLane == 0 &&
3903 cast<FixedVectorType>(FrontV->getType())->getNumElements() ==
3904 Item.size() &&
3905 all_of(drop_begin(enumerate(Item)), [Item](const auto &E) {
3906 Value *FrontV = Item.front().first;
3907 return !E.value().first || (isEquivBitcast(E.value().first, FrontV) &&
3908 E.value().second == (int)E.index());
3909 })) {
3910 IdentityLeafs.insert(std::make_pair(FrontV, From));
3911 continue;
3912 }
3913 // Look for constants, for the moment only supporting constant splats.
3914 if (auto *C = dyn_cast<Constant>(FrontV);
3915 C && C->getSplatValue() &&
3916 all_of(drop_begin(Item), [Item](InstLane &IL) {
3917 Value *FrontV = Item.front().first;
3918 Value *V = IL.first;
3919 return !V || (isa<Constant>(V) &&
3920 cast<Constant>(V)->getSplatValue() ==
3921 cast<Constant>(FrontV)->getSplatValue());
3922 })) {
3923 SplatLeafs.insert(std::make_pair(FrontV, From));
3924 continue;
3925 }
3926 // Look for a splat value.
3927 if (all_of(drop_begin(Item), [Item](InstLane &IL) {
3928 auto [FrontV, FrontLane] = Item.front();
3929 auto [V, Lane] = IL;
3930 return !V || (V == FrontV && Lane == FrontLane);
3931 })) {
3932 SplatLeafs.insert(std::make_pair(FrontV, From));
3933 continue;
3934 }
3935
3936 // We need each element to be the same type of value, and check that each
3937 // element has a single use.
3938 auto CheckLaneIsEquivalentToFirst = [Item](InstLane IL) {
3939 Value *FrontV = Item.front().first;
3940 if (!IL.first)
3941 return true;
3942 Value *V = IL.first;
3943 if (auto *I = dyn_cast<Instruction>(V); I && !I->hasOneUser())
3944 return false;
3945 if (V->getValueID() != FrontV->getValueID())
3946 return false;
3947 if (auto *CI = dyn_cast<CmpInst>(V))
3948 if (CI->getPredicate() != cast<CmpInst>(FrontV)->getPredicate())
3949 return false;
3950 if (auto *CI = dyn_cast<CastInst>(V))
3951 if (CI->getSrcTy()->getScalarType() !=
3952 cast<CastInst>(FrontV)->getSrcTy()->getScalarType())
3953 return false;
3954 if (auto *SI = dyn_cast<SelectInst>(V))
3955 if (!isa<VectorType>(SI->getOperand(0)->getType()) ||
3956 SI->getOperand(0)->getType() !=
3957 cast<SelectInst>(FrontV)->getOperand(0)->getType())
3958 return false;
3960 return false;
3961 auto *II = dyn_cast<IntrinsicInst>(V);
3962 return !II || (isa<IntrinsicInst>(FrontV) &&
3963 II->getIntrinsicID() ==
3964 cast<IntrinsicInst>(FrontV)->getIntrinsicID() &&
3965 !II->hasOperandBundles());
3966 };
3967 if (all_of(drop_begin(Item), CheckLaneIsEquivalentToFirst)) {
3968 // Check the operator is one that we support.
3969 if (isa<BinaryOperator, CmpInst>(FrontV)) {
3970 // We exclude div/rem in case they hit UB from poison lanes.
3971 if (auto *BO = dyn_cast<BinaryOperator>(FrontV);
3972 BO && BO->isIntDivRem())
3973 return false;
3975 &cast<Instruction>(FrontV)->getOperandUse(0));
3977 &cast<Instruction>(FrontV)->getOperandUse(1));
3978 continue;
3979 } else if (isa<UnaryOperator, TruncInst, ZExtInst, SExtInst, FPToSIInst,
3980 FPToUIInst, SIToFPInst, UIToFPInst>(FrontV)) {
3982 &cast<Instruction>(FrontV)->getOperandUse(0));
3983 continue;
3984 } else if (auto *BitCast = dyn_cast<BitCastInst>(FrontV)) {
3985 auto *BCDstTy = dyn_cast<FixedVectorType>(BitCast->getDestTy());
3986 auto *BCSrcTy = dyn_cast<FixedVectorType>(BitCast->getSrcTy());
3987 if (BCDstTy && BCSrcTy) {
3988 ElementCount DstEC = BCDstTy->getElementCount();
3989 ElementCount SrcEC = BCSrcTy->getElementCount();
3990 if (DstEC == SrcEC) {
3991 // Same element count - simple pass-through.
3993 &BitCast->getOperandUse(0));
3994 continue;
3995 }
3996 unsigned DstElts = DstEC.getFixedValue();
3997 unsigned SrcElts = SrcEC.getFixedValue();
3998 if (DstElts > SrcElts && DstElts % SrcElts == 0) {
3999 // Widening bitcast (e.g. <2 x i32> -> <4 x i16>). Compress
4000 // consecutive groups of R destination lanes into one source
4001 // lane.
4002 unsigned R = DstElts / SrcElts;
4004 bool Valid = Item.size() % R == 0;
4005 for (unsigned Idx = 0, E = Item.size(); Valid && Idx < E;
4006 Idx += R) {
4007 auto [V0, L0] = Item[Idx];
4008 if (!V0) {
4009 if (any_of(ArrayRef(Item).slice(Idx + 1, R - 1),
4010 [](InstLane IL) { return IL.first != nullptr; })) {
4011 Valid = false;
4012 break;
4013 }
4014 NItem.push_back({nullptr, PoisonMaskElem});
4015 continue;
4016 }
4017 if (L0 % R != 0) {
4018 Valid = false;
4019 break;
4020 }
4021 for (unsigned J = 1; J < R; ++J) {
4022 auto [VJ, LJ] = Item[Idx + J];
4023 if (!VJ || VJ != V0 || LJ != L0 + (int)J) {
4024 Valid = false;
4025 break;
4026 }
4027 }
4028 if (!Valid)
4029 break;
4031 cast<Operator>(V0)->getOperand(0), L0 / R));
4032 }
4033 if (Valid) {
4034 TraversedElCountChangingBitcast = true;
4035 Candidates.emplace_back(NItem, &BitCast->getOperandUse(0));
4036 continue;
4037 }
4038 } else if (SrcElts > DstElts && SrcElts % DstElts == 0) {
4039 // Narrowing bitcast (e.g. <4 x i16> -> <2 x i32>). Expand
4040 // each destination lane into R source lanes.
4041 unsigned R = SrcElts / DstElts;
4043 for (auto [V, Lane] : Item) {
4044 if (!V) {
4045 NItem.append(R, {nullptr, PoisonMaskElem});
4046 continue;
4047 }
4048 Value *Op = cast<Operator>(V)->getOperand(0);
4049 for (unsigned J = 0; J < R; ++J)
4050 NItem.push_back(lookThroughShuffles(Op, Lane * R + J));
4051 }
4052 TraversedElCountChangingBitcast = true;
4053 Candidates.emplace_back(NItem, &BitCast->getOperandUse(0));
4054 continue;
4055 }
4056 }
4057 } else if (auto *Sel = dyn_cast<SelectInst>(FrontV)) {
4059 &Sel->getOperandUse(0));
4061 &Sel->getOperandUse(1));
4063 &Sel->getOperandUse(2));
4064 continue;
4065 } else if (auto *II = dyn_cast<IntrinsicInst>(FrontV);
4066 II && isTriviallyVectorizable(II->getIntrinsicID()) &&
4067 !II->hasOperandBundles()) {
4068 for (unsigned Op = 0, E = II->getNumOperands() - 1; Op < E; Op++) {
4069 if (isVectorIntrinsicWithScalarOpAtArg(II->getIntrinsicID(), Op,
4070 &TTI)) {
4071 if (!all_of(drop_begin(Item), [Item, Op](InstLane &IL) {
4072 Value *FrontV = Item.front().first;
4073 Value *V = IL.first;
4074 return !V || (cast<Instruction>(V)->getOperand(Op) ==
4075 cast<Instruction>(FrontV)->getOperand(Op));
4076 }))
4077 return false;
4078 continue;
4079 }
4080 Candidates.emplace_back(
4082 &cast<Instruction>(FrontV)->getOperandUse(Op));
4083 }
4084 continue;
4085 }
4086 }
4087
4088 if (isFreeConcat(Item, CostKind, TTI)) {
4089 ConcatLeafs.insert(std::make_pair(FrontV, From));
4090 continue;
4091 }
4092
4093 return false;
4094 }
4095
4096 if (NumVisited <= 1)
4097 return false;
4098
4099 // If the only non-leaf node traversed was a single bitcast that changes
4100 // element count, the fold would just commute the bitcast and shuffle.
4101 // foldBitcastShuffle does the reverse transform, causing an infinite loop.
4102 if (NumVisited == 2 && TraversedElCountChangingBitcast)
4103 return false;
4104
4105 LLVM_DEBUG(dbgs() << "Found a superfluous identity shuffle: " << I << "\n");
4106
4107 // If we got this far, we know the shuffles are superfluous and can be
4108 // removed. Scan through again and generate the new tree of instructions.
4109 Builder.SetInsertPoint(&I);
4110 Value *V =
4111 generateNewInstTree(Start, &*I.use_begin(), IdentityLeafs, SplatLeafs,
4112 ConcatLeafs, Builder, Worklist, &TTI);
4113 replaceValue(I, *V);
4114 return true;
4115}
4116
4117/// Given a commutative reduction, the order of the input lanes does not alter
4118/// the results. We can use this to remove certain shuffles feeding the
4119/// reduction, removing the need to shuffle at all.
4120bool VectorCombine::foldShuffleFromReductions(Instruction &I) {
4121 auto *II = dyn_cast<IntrinsicInst>(&I);
4122 if (!II)
4123 return false;
4124 switch (II->getIntrinsicID()) {
4125 case Intrinsic::vector_reduce_add:
4126 case Intrinsic::vector_reduce_mul:
4127 case Intrinsic::vector_reduce_and:
4128 case Intrinsic::vector_reduce_or:
4129 case Intrinsic::vector_reduce_xor:
4130 case Intrinsic::vector_reduce_smin:
4131 case Intrinsic::vector_reduce_smax:
4132 case Intrinsic::vector_reduce_umin:
4133 case Intrinsic::vector_reduce_umax:
4134 break;
4135 default:
4136 return false;
4137 }
4138
4139 // Find all the inputs when looking through operations that do not alter the
4140 // lane order (binops, for example). Currently we look for a single shuffle,
4141 // and can ignore splat values.
4142 std::queue<Value *> Worklist;
4143 SmallPtrSet<Value *, 4> Visited;
4144 ShuffleVectorInst *Shuffle = nullptr;
4145 if (auto *Op = dyn_cast<Instruction>(I.getOperand(0)))
4146 Worklist.push(Op);
4147
4148 while (!Worklist.empty()) {
4149 Value *CV = Worklist.front();
4150 Worklist.pop();
4151 if (Visited.contains(CV))
4152 continue;
4153
4154 // Splats don't change the order, so can be safely ignored.
4155 if (isSplatValue(CV))
4156 continue;
4157
4158 Visited.insert(CV);
4159
4160 if (auto *CI = dyn_cast<Instruction>(CV)) {
4161 if (CI->isBinaryOp()) {
4162 for (auto *Op : CI->operand_values())
4163 Worklist.push(Op);
4164 continue;
4165 } else if (auto *SV = dyn_cast<ShuffleVectorInst>(CI)) {
4166 if (Shuffle && Shuffle != SV)
4167 return false;
4168 Shuffle = SV;
4169 continue;
4170 }
4171 }
4172
4173 // Anything else is currently an unknown node.
4174 return false;
4175 }
4176
4177 if (!Shuffle)
4178 return false;
4179
4180 // Check all uses of the binary ops and shuffles are also included in the
4181 // lane-invariant operations (Visited should be the list of lanewise
4182 // instructions, including the shuffle that we found).
4183 for (auto *V : Visited)
4184 for (auto *U : V->users())
4185 if (!Visited.contains(U) && U != &I)
4186 return false;
4187
4188 FixedVectorType *VecType =
4189 dyn_cast<FixedVectorType>(II->getOperand(0)->getType());
4190 if (!VecType)
4191 return false;
4192 FixedVectorType *ShuffleInputType =
4194 if (!ShuffleInputType)
4195 return false;
4196 unsigned NumInputElts = ShuffleInputType->getNumElements();
4197
4198 // Find the mask from sorting the lanes into order. This is most likely to
4199 // become a identity or concat mask. Undef elements are pushed to the end.
4200 SmallVector<int> ConcatMask;
4201 Shuffle->getShuffleMask(ConcatMask);
4202 sort(ConcatMask, [](int X, int Y) { return (unsigned)X < (unsigned)Y; });
4203 bool UsesSecondVec =
4204 any_of(ConcatMask, [&](int M) { return M >= (int)NumInputElts; });
4205
4207 UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
4208 ShuffleInputType, CostKind, Shuffle->getShuffleMask());
4210 UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
4211 ShuffleInputType, CostKind, ConcatMask);
4212
4213 LLVM_DEBUG(dbgs() << "Found a reduction feeding from a shuffle: " << *Shuffle
4214 << "\n");
4215 LLVM_DEBUG(dbgs() << " OldCost: " << OldCost << " vs NewCost: " << NewCost
4216 << "\n");
4217 bool MadeChanges = false;
4218 if (NewCost < OldCost) {
4219 Builder.SetInsertPoint(Shuffle);
4220 Value *NewShuffle = Builder.CreateShuffleVector(
4221 Shuffle->getOperand(0), Shuffle->getOperand(1), ConcatMask);
4222 LLVM_DEBUG(dbgs() << "Created new shuffle: " << *NewShuffle << "\n");
4223 replaceValue(*Shuffle, *NewShuffle);
4224 return true;
4225 }
4226
4227 // See if we can re-use foldSelectShuffle, getting it to reduce the size of
4228 // the shuffle into a nicer order, as it can ignore the order of the shuffles.
4229 MadeChanges |= foldSelectShuffle(*Shuffle, true);
4230 return MadeChanges;
4231}
4232
4233/// Try to fold a chain of shuffles and ops feeding extractelement(..., 0)
4234/// into llvm.vector.reduce.*, by tracking which lanes contribute to the
4235/// extracted lane and reducing the widest vector whose lanes each contribute
4236/// once.
4237///
4238/// For example:
4239///
4240/// %lo = shufflevector <4 x i32> %a, poison, <2 x i32> <i32 0, i32 1>
4241/// %hi = shufflevector <4 x i32> %a, poison, <2 x i32> <i32 2, i32 3>
4242/// %s = add <2 x i32> %lo, %hi
4243/// %sh = shufflevector <2 x i32> %s, poison, <2 x i32> <i32 1, i32 poison>
4244/// %r = add <2 x i32> %s, %sh
4245/// %e = extractelement <2 x i32> %r, i64 0
4246///
4247/// transforms to:
4248///
4249/// %e = call i32 @llvm.vector.reduce.add.v4i32(<4 x i32> %a)
4250bool VectorCombine::foldShuffleChainsToReduce(Instruction &I) {
4251 Value *VecOpEE;
4252 if (!match(&I, m_ExtractElt(m_Value(VecOpEE), m_Zero())))
4253 return false;
4254
4255 auto *FVT = dyn_cast<FixedVectorType>(VecOpEE->getType());
4256 if (!FVT)
4257 return false;
4258
4259 if (FVT->getNumElements() < 2)
4260 return false;
4261
4262 std::optional<Instruction::BinaryOps> CommonBinOp;
4263 std::optional<Intrinsic::ID> CommonCallOp;
4264
4265 if (auto *BO = dyn_cast<BinaryOperator>(VecOpEE)) {
4266 if (!getReductionForBinop(BO->getOpcode()))
4267 return false;
4268 CommonBinOp = BO->getOpcode();
4269 } else if (auto *MMI = dyn_cast<MinMaxIntrinsic>(VecOpEE)) {
4270 CommonCallOp = MMI->getIntrinsicID();
4271 } else {
4272 return false;
4273 }
4274
4275 // For floating-point reductions, track FMF intersection across all binops.
4276 FastMathFlags CommonFMF;
4277 bool IsFloatReduction = false;
4278
4279 // A chain node is one we walk through, either a matching-opcode binop/min-max
4280 // or a single-source shuffle. Anything else is a leaf source.
4281 auto IsChainNode = [&](Value *V) {
4282 if (auto *BO = dyn_cast<BinaryOperator>(V))
4283 return CommonBinOp && BO->getOpcode() == *CommonBinOp;
4284 if (auto *MMI = dyn_cast<MinMaxIntrinsic>(V))
4285 return CommonCallOp && MMI->getIntrinsicID() == *CommonCallOp;
4286 if (auto *SVI = dyn_cast<ShuffleVectorInst>(V))
4287 return isa<PoisonValue>(SVI->getOperand(1));
4288 return false;
4289 };
4290
4291 // Collect the chain, building Nodes in postorder. Bail if the chain is empty
4292 // or exceeds MaxChainNodes.
4293 constexpr unsigned MaxChainNodes = 32;
4294 SmallSetVector<Value *, 16> Nodes;
4295 SmallSetVector<Value *, 4> Sources;
4296 unsigned NumVisited = 0;
4297 auto AddSource = [&](Value *V) {
4298 if (!isa<FixedVectorType>(V->getType()))
4299 return false;
4300 Sources.insert(V);
4301 return true;
4302 };
4303 auto Walk = [&](Value *V, auto &&Walk) -> bool {
4304 if (Nodes.contains(V) || Sources.contains(V))
4305 return true;
4306 if (++NumVisited > MaxChainNodes)
4307 return false;
4308 if (!IsChainNode(V))
4309 return AddSource(V);
4310 // Chain shuffles always have poison as op1, so only op0 matters.
4311 auto *U = cast<Instruction>(V);
4312 unsigned NumOps = isa<ShuffleVectorInst>(U) ? 1 : 2;
4313 for (unsigned I = 0; I != NumOps; ++I)
4314 if (!Walk(U->getOperand(I), Walk))
4315 return false;
4316 if (isa<ShuffleVectorInst>(U) || Nodes.contains(U->getOperand(0)) ||
4317 Nodes.contains(U->getOperand(1))) {
4318 Nodes.insert(V);
4319 return true;
4320 }
4321 // Both operands are leaves so treat this binop as a source rather than
4322 // walking into it.
4323 return AddSource(V);
4324 };
4325 if (!Walk(VecOpEE, Walk) || Nodes.empty())
4326 return false;
4327
4328 bool IsIdempotent =
4329 CommonCallOp || (CommonBinOp && Instruction::isIdempotent(*CommonBinOp));
4330
4331 // For FP reductions, require reassoc on every binop and collect FMF.
4332 for (Value *V : Nodes) {
4333 auto *BinOp = dyn_cast<BinaryOperator>(V);
4334 if (!BinOp || !BinOp->getType()->isFPOrFPVectorTy())
4335 continue;
4336 if (!BinOp->hasAllowReassoc())
4337 return false;
4338 if (!IsFloatReduction) {
4339 CommonFMF = BinOp->getFastMathFlags();
4340 IsFloatReduction = true;
4341 } else {
4342 CommonFMF &= BinOp->getFastMathFlags();
4343 }
4344 }
4345
4346 // Top-down demanded elements. For each chain value, track which lanes feed
4347 // the extracted lane 0 and which feed it more than once. Reverse postorder
4348 // visits every use before its value. A binop forwards its demand to both
4349 // operands and a shuffle follows its mask back to the source lane.
4350 struct Demand {
4351 APInt Lanes;
4352 APInt Duplicates;
4353 };
4354 DenseMap<Value *, Demand> Demands;
4355 auto DemandOf = [&](Value *V) -> Demand & {
4356 unsigned N = cast<FixedVectorType>(V->getType())->getNumElements();
4357 Demand &D = Demands[V];
4358 if (D.Lanes.getBitWidth() != N)
4359 D.Lanes = D.Duplicates = APInt::getZero(N);
4360 return D;
4361 };
4362 DemandOf(VecOpEE).Lanes.setBit(0);
4363 for (Value *V : reverse(Nodes)) {
4364 Demand DV = Demands.lookup(V);
4365 if (DV.Lanes.isZero())
4366 continue;
4367 if (auto *SVI = dyn_cast<ShuffleVectorInst>(V)) {
4368 ArrayRef<int> Mask = SVI->getShuffleMask();
4369 Demand &DS = DemandOf(SVI->getOperand(0));
4370 for (unsigned I = 0, E = Mask.size(); I != E; ++I) {
4371 // Skip lanes that are undemanded or map to poison.
4372 if (!DV.Lanes[I] || Mask[I] < 0 ||
4373 (unsigned)Mask[I] >= DS.Lanes.getBitWidth())
4374 continue;
4375 if (DS.Lanes[Mask[I]] || DV.Duplicates[I])
4376 DS.Duplicates.setBit(Mask[I]);
4377 DS.Lanes.setBit(Mask[I]);
4378 }
4379 } else {
4380 auto *U = cast<User>(V);
4381 for (Value *Op : {U->getOperand(0), U->getOperand(1)}) {
4382 Demand &DOp = DemandOf(Op);
4383 // Lanes demanded through more than one path accumulate in Duplicates.
4384 DOp.Duplicates |= DV.Duplicates | (DOp.Lanes & DV.Lanes);
4385 DOp.Lanes |= DV.Lanes;
4386 }
4387 }
4388 }
4389
4390 // Reducing V replaces the entire chain, so every contribution to the result
4391 // must flow through V. Reject if anything above V reads outside the chain.
4392 auto CoversChain = [&](Value *V) {
4393 SmallVector<Value *, 8> Worklist(1, VecOpEE);
4394 SmallPtrSet<Value *, 8> Seen;
4395 Seen.insert(VecOpEE);
4396 while (!Worklist.empty()) {
4397 auto *U = cast<Instruction>(Worklist.pop_back_val());
4398 unsigned NumOps = isa<ShuffleVectorInst>(U) ? 1 : 2;
4399 for (unsigned I = 0; I != NumOps; ++I) {
4400 Value *Op = U->getOperand(I);
4401 if (Op == V || !Seen.insert(Op).second)
4402 continue;
4403 if (!Nodes.contains(Op))
4404 return false;
4405 Worklist.push_back(Op);
4406 }
4407 }
4408 return true;
4409 };
4410
4411 // Reduce a single cleanly demanded source if there is one, otherwise the
4412 // deepest intermediate that covers the chain.
4413 struct ReductionCut {
4414 Value *Src;
4415 APInt Elts;
4416 };
4417 std::optional<ReductionCut> Cut;
4418 for (Value *S : Sources) {
4419 auto It = Demands.find(S);
4420 if (It == Demands.end() || It->second.Lanes.isZero())
4421 continue;
4422 if (!IsIdempotent && !It->second.Duplicates.isZero()) {
4423 Cut.reset();
4424 break;
4425 }
4426 if (!Cut) {
4427 Cut = ReductionCut{S, It->second.Lanes};
4428 continue;
4429 }
4430 if (!isEquivBitcast(Cut->Src, S)) {
4431 Cut.reset();
4432 break;
4433 }
4434 if (!IsIdempotent && !(Cut->Elts & It->second.Lanes).isZero()) {
4435 Cut.reset();
4436 break;
4437 }
4438 Cut->Elts |= It->second.Lanes;
4439 }
4440 if (!Cut) {
4441 for (Value *V : Nodes) {
4443 continue;
4444 auto It = Demands.find(V);
4445 if (It == Demands.end() || !It->second.Lanes.isAllOnes())
4446 continue;
4447 if (!IsIdempotent && !It->second.Duplicates.isZero())
4448 continue;
4449 if (!CoversChain(V))
4450 continue;
4451 Cut = ReductionCut{V, It->second.Lanes};
4452 break;
4453 }
4454 }
4455 // Reducing one lane is just an extract and can refold forever.
4456 if (!Cut || Cut->Elts.popcount() < 2)
4457 return false;
4458
4459 Intrinsic::ID ReducedOp =
4460 (CommonCallOp ? getMinMaxReductionIntrinsicID(*CommonCallOp)
4461 : getReductionForBinop(*CommonBinOp));
4462 if (!ReducedOp)
4463 return false;
4464
4465 InstructionCost OrigCost = 0;
4466 for (Value *V : Nodes)
4467 OrigCost += TTI.getInstructionCost(cast<Instruction>(V), CostKind);
4468
4469 auto *SrcVT = cast<FixedVectorType>(Cut->Src->getType());
4470 bool IsPartialReduction = !Cut->Elts.isAllOnes();
4471 FixedVectorType *ReduceVecTy =
4472 IsPartialReduction
4473 ? FixedVectorType::get(FVT->getElementType(), Cut->Elts.popcount())
4474 : SrcVT;
4475
4476 SmallVector<int> ExtractMask;
4477 InstructionCost NewCost = 0;
4478 if (IsPartialReduction) {
4479 for (unsigned I = 0, E = Cut->Elts.getBitWidth(); I != E; ++I)
4480 if (Cut->Elts[I])
4481 ExtractMask.push_back(I);
4482 unsigned SubIdx = 0, SubLen;
4483 auto SK = Cut->Elts.isShiftedMask(SubIdx, SubLen)
4486 NewCost += TTI.getShuffleCost(SK, ReduceVecTy, SrcVT, CostKind, ExtractMask,
4487 SubIdx, ReduceVecTy);
4488 }
4489
4490 IntrinsicCostAttributes ICA(
4491 ReducedOp, ReduceVecTy->getElementType(),
4492 IsFloatReduction
4493 ? SmallVector<Type *, 2>{ReduceVecTy->getElementType(), ReduceVecTy}
4494 : SmallVector<Type *, 2>{ReduceVecTy},
4495 IsFloatReduction ? CommonFMF : FastMathFlags());
4496 NewCost += TTI.getIntrinsicInstrCost(ICA, CostKind);
4497
4498 LLVM_DEBUG(dbgs() << "Found reduction shuffle chain: " << I << "\n OldCost : "
4499 << OrigCost << " vs NewCost: " << NewCost << "\n");
4500
4501 if (!OrigCost.isValid() || !NewCost.isValid())
4502 return false;
4503
4504 if (VecOpEE->hasOneUse() ? (NewCost > OrigCost) : (NewCost >= OrigCost))
4505 return false;
4506
4507 Value *ReduceInput = Cut->Src;
4508 if (IsPartialReduction)
4509 ReduceInput = Builder.CreateShuffleVector(Cut->Src, ExtractMask);
4510
4511 Value *ReducedResult;
4512 if (IsFloatReduction) {
4514 *CommonBinOp, ReduceVecTy->getElementType(), /*AllowRHSConstant=*/false,
4515 CommonFMF.noSignedZeros());
4516 ReducedResult = Builder.CreateIntrinsic(ReducedOp, {ReduceVecTy},
4517 {Identity, ReduceInput}, CommonFMF);
4518 } else {
4519 ReducedResult =
4520 Builder.CreateIntrinsic(ReducedOp, {ReduceVecTy}, {ReduceInput});
4521 }
4522 replaceValue(I, *ReducedResult);
4523
4524 return true;
4525}
4526
4527/// Determine if its more efficient to fold:
4528/// reduce(trunc(x)) -> trunc(reduce(x)).
4529/// reduce(sext(x)) -> sext(reduce(x)).
4530/// reduce(zext(x)) -> zext(reduce(x)).
4531bool VectorCombine::foldCastFromReductions(Instruction &I) {
4532 auto *II = dyn_cast<IntrinsicInst>(&I);
4533 if (!II)
4534 return false;
4535
4536 bool TruncOnly = false;
4537 Intrinsic::ID IID = II->getIntrinsicID();
4538 switch (IID) {
4539 case Intrinsic::vector_reduce_add:
4540 case Intrinsic::vector_reduce_mul:
4541 TruncOnly = true;
4542 break;
4543 case Intrinsic::vector_reduce_and:
4544 case Intrinsic::vector_reduce_or:
4545 case Intrinsic::vector_reduce_xor:
4546 break;
4547 default:
4548 return false;
4549 }
4550
4551 unsigned ReductionOpc = getArithmeticReductionInstruction(IID);
4552 Value *ReductionSrc = I.getOperand(0);
4553
4554 Value *Src;
4555 if (!match(ReductionSrc, m_OneUse(m_Trunc(m_Value(Src)))) &&
4556 (TruncOnly || !match(ReductionSrc, m_OneUse(m_ZExtOrSExt(m_Value(Src))))))
4557 return false;
4558
4559 auto CastOpc =
4560 (Instruction::CastOps)cast<Instruction>(ReductionSrc)->getOpcode();
4561
4562 auto *SrcTy = cast<VectorType>(Src->getType());
4563 auto *ReductionSrcTy = cast<VectorType>(ReductionSrc->getType());
4564 Type *ResultTy = I.getType();
4565
4567 ReductionOpc, ReductionSrcTy, std::nullopt, CostKind);
4568 OldCost += TTI.getCastInstrCost(CastOpc, ReductionSrcTy, SrcTy,
4570 cast<CastInst>(ReductionSrc));
4571 InstructionCost NewCost =
4572 TTI.getArithmeticReductionCost(ReductionOpc, SrcTy, std::nullopt,
4573 CostKind) +
4574 TTI.getCastInstrCost(CastOpc, ResultTy, ReductionSrcTy->getScalarType(),
4575 TTI::CastContextHint::None, CostKind);
4576
4577 if (OldCost <= NewCost || !NewCost.isValid())
4578 return false;
4579
4580 Value *NewReduction = Builder.CreateIntrinsic(SrcTy->getScalarType(),
4581 II->getIntrinsicID(), {Src});
4582 Value *NewCast = Builder.CreateCast(CastOpc, NewReduction, ResultTy);
4583 replaceValue(I, *NewCast);
4584 return true;
4585}
4586
4587/// Fold:
4588/// icmp pred (reduce.{add,or,and,umax,umin}(signbit_extract(x))), C
4589/// into:
4590/// icmp sgt/slt (reduce.{or,umax,and,umin}(x)), -1/0
4591///
4592/// Sign-bit reductions produce values with known semantics:
4593/// - reduce.{or,umax}: 0 if no element is negative, 1 if any is
4594/// - reduce.{and,umin}: 1 if all elements are negative, 0 if any isn't
4595/// - reduce.add: count of negative elements (0 to NumElts)
4596///
4597/// Both lshr and ashr are supported:
4598/// - lshr produces 0 or 1, so reduce.add range is [0, N]
4599/// - ashr produces 0 or -1, so reduce.add range is [-N, 0]
4600///
4601/// The fold generalizes to multiple source vectors combined with the same
4602/// operation as the reduction. For example:
4603/// reduce.or(or(shr A, shr B)) conceptually extends the vector
4604/// For reduce.add, this changes the count to M*N where M is the number of
4605/// source vectors.
4606///
4607/// We transform to a direct sign check on the original vector using
4608/// reduce.{or,umax} or reduce.{and,umin}.
4609///
4610/// In spirit, it's similar to foldSignBitCheck in InstCombine.
4611bool VectorCombine::foldSignBitReductionCmp(Instruction &I) {
4612 CmpPredicate Pred;
4613 IntrinsicInst *ReduceOp;
4614 const APInt *CmpVal;
4615 if (!match(&I,
4616 m_ICmp(Pred, m_OneUse(m_AnyIntrinsic(ReduceOp)), m_APInt(CmpVal))))
4617 return false;
4618
4619 Intrinsic::ID OrigIID = ReduceOp->getIntrinsicID();
4620 switch (OrigIID) {
4621 case Intrinsic::vector_reduce_or:
4622 case Intrinsic::vector_reduce_umax:
4623 case Intrinsic::vector_reduce_and:
4624 case Intrinsic::vector_reduce_umin:
4625 case Intrinsic::vector_reduce_add:
4626 break;
4627 default:
4628 return false;
4629 }
4630
4631 Value *ReductionSrc = ReduceOp->getArgOperand(0);
4632 auto *VecTy = dyn_cast<FixedVectorType>(ReductionSrc->getType());
4633 if (!VecTy)
4634 return false;
4635
4636 unsigned BitWidth = VecTy->getScalarSizeInBits();
4637 if (BitWidth == 1)
4638 return false;
4639
4640 unsigned NumElts = VecTy->getNumElements();
4641
4642 // Determine the expected tree opcode for multi-vector patterns.
4643 // The tree opcode must match the reduction's underlying operation.
4644 //
4645 // TODO: for pairs of equivalent operators, we should match both,
4646 // not only the most common.
4647 Instruction::BinaryOps TreeOpcode;
4648 switch (OrigIID) {
4649 case Intrinsic::vector_reduce_or:
4650 case Intrinsic::vector_reduce_umax:
4651 TreeOpcode = Instruction::Or;
4652 break;
4653 case Intrinsic::vector_reduce_and:
4654 case Intrinsic::vector_reduce_umin:
4655 TreeOpcode = Instruction::And;
4656 break;
4657 case Intrinsic::vector_reduce_add:
4658 TreeOpcode = Instruction::Add;
4659 break;
4660 default:
4661 llvm_unreachable("Unexpected intrinsic");
4662 }
4663
4664 // Collect sign-bit extraction leaves from an associative tree of TreeOpcode.
4665 // The tree conceptually extends the vector being reduced.
4666 SmallVector<Value *, 8> Worklist;
4667 SmallVector<Value *, 8> Sources; // Original vectors (X in shr X, BW-1)
4668 Worklist.push_back(ReductionSrc);
4669 std::optional<bool> IsAShr;
4670 constexpr unsigned MaxSources = 8;
4671
4672 // Calculate old cost: all shifts + tree ops + reduction
4673 InstructionCost OldCost = TTI.getInstructionCost(ReduceOp, CostKind);
4674
4675 while (!Worklist.empty() && Worklist.size() <= MaxSources &&
4676 Sources.size() <= MaxSources) {
4677 Value *V = Worklist.pop_back_val();
4678
4679 // Try to match sign-bit extraction: shr X, (bitwidth-1)
4680 Value *X;
4682 auto *Shr = cast<Instruction>(V);
4683
4684 // All shifts must be the same type (all lshr or all ashr)
4685 bool ThisIsAShr = Shr->getOpcode() == Instruction::AShr;
4686 if (!IsAShr)
4687 IsAShr = ThisIsAShr;
4688 else if (*IsAShr != ThisIsAShr)
4689 return false;
4690
4691 Sources.push_back(X);
4692
4693 // As part of the fold, we remove all of the shifts, so we need to keep
4694 // track of their costs.
4695 OldCost += TTI.getInstructionCost(Shr, CostKind);
4696
4697 continue;
4698 }
4699
4700 // Try to extend through a tree node of the expected opcode
4701 Value *A, *B;
4702 if (!match(V, m_OneUse(m_BinOp(TreeOpcode, m_Value(A), m_Value(B)))))
4703 return false;
4704
4705 // We are potentially replacing these operations as well, so we add them
4706 // to the costs.
4707 OldCost += TTI.getInstructionCost(cast<Instruction>(V), CostKind);
4708
4709 Worklist.push_back(A);
4710 Worklist.push_back(B);
4711 }
4712
4713 // Must have at least one source and not exceed limit
4714 if (Sources.empty() || Sources.size() > MaxSources ||
4715 Worklist.size() > MaxSources || !IsAShr)
4716 return false;
4717
4718 unsigned NumSources = Sources.size();
4719
4720 // For reduce.add, the total count must fit as a signed integer.
4721 // Range is [0, M*N] for lshr or [-M*N, 0] for ashr.
4722 if (OrigIID == Intrinsic::vector_reduce_add &&
4723 !isIntN(BitWidth, NumSources * NumElts))
4724 return false;
4725
4726 // Compute the boundary value when all elements are negative:
4727 // - Per-element contribution: 1 for lshr, -1 for ashr
4728 // - For add: M*N (total elements across all sources); for others: just 1
4729 unsigned Count =
4730 (OrigIID == Intrinsic::vector_reduce_add) ? NumSources * NumElts : 1;
4731 APInt NegativeVal(CmpVal->getBitWidth(), Count);
4732 if (*IsAShr)
4733 NegativeVal.negate();
4734
4735 // Range is [min(0, AllNegVal), max(0, AllNegVal)]
4736 APInt Zero = APInt::getZero(CmpVal->getBitWidth());
4737 APInt RangeLow = APIntOps::smin(Zero, NegativeVal);
4738 APInt RangeHigh = APIntOps::smax(Zero, NegativeVal);
4739
4740 // Determine comparison semantics:
4741 // - IsEq: true for equality test, false for inequality
4742 // - TestsNegative: true if testing against AllNegVal, false for zero
4743 //
4744 // In addition to EQ/NE against 0 or AllNegVal, we support inequalities
4745 // that fold to boundary tests given the narrow value range:
4746 // < RangeHigh -> != RangeHigh
4747 // > RangeHigh-1 -> == RangeHigh
4748 // > RangeLow -> != RangeLow
4749 // < RangeLow+1 -> == RangeLow
4750 //
4751 // For inequalities, we work with signed predicates only. Unsigned predicates
4752 // are canonicalized to signed when the range is non-negative (where they are
4753 // equivalent). When the range includes negative values, unsigned predicates
4754 // would have different semantics due to wrap-around, so we reject them.
4755 if (!ICmpInst::isEquality(Pred) && !ICmpInst::isSigned(Pred)) {
4756 if (RangeLow.isNegative())
4757 return false;
4759 }
4760
4761 bool IsEq;
4762 bool TestsNegative;
4764 if (CmpVal->isZero()) {
4765 TestsNegative = false;
4766 } else if (*CmpVal == NegativeVal) {
4767 TestsNegative = true;
4768 } else {
4769 return false;
4770 }
4771 IsEq = Pred == ICmpInst::ICMP_EQ;
4772 } else if (Pred == ICmpInst::ICMP_SLT && *CmpVal == RangeHigh) {
4773 IsEq = false;
4774 TestsNegative = (RangeHigh == NegativeVal);
4775 } else if (Pred == ICmpInst::ICMP_SGT && *CmpVal == RangeHigh - 1) {
4776 IsEq = true;
4777 TestsNegative = (RangeHigh == NegativeVal);
4778 } else if (Pred == ICmpInst::ICMP_SGT && *CmpVal == RangeLow) {
4779 IsEq = false;
4780 TestsNegative = (RangeLow == NegativeVal);
4781 } else if (Pred == ICmpInst::ICMP_SLT && *CmpVal == RangeLow + 1) {
4782 IsEq = true;
4783 TestsNegative = (RangeLow == NegativeVal);
4784 } else {
4785 return false;
4786 }
4787
4788 // For this fold we support four types of checks:
4789 //
4790 // 1. All lanes are negative - AllNeg
4791 // 2. All lanes are non-negative - AllNonNeg
4792 // 3. At least one negative lane - AnyNeg
4793 // 4. At least one non-negative lane - AnyNonNeg
4794 //
4795 // For each case, we can generate the following code:
4796 //
4797 // 1. AllNeg - reduce.and/umin(X) < 0
4798 // 2. AllNonNeg - reduce.or/umax(X) > -1
4799 // 3. AnyNeg - reduce.or/umax(X) < 0
4800 // 4. AnyNonNeg - reduce.and/umin(X) > -1
4801 //
4802 // The table below shows the aggregation of all supported cases
4803 // using these four cases.
4804 //
4805 // Reduction | == 0 | != 0 | == MAX | != MAX
4806 // ------------+-----------+-----------+-----------+-----------
4807 // or/umax | AllNonNeg | AnyNeg | AnyNeg | AllNonNeg
4808 // and/umin | AnyNonNeg | AllNeg | AllNeg | AnyNonNeg
4809 // add | AllNonNeg | AnyNeg | AllNeg | AnyNonNeg
4810 //
4811 // NOTE: MAX = 1 for or/and/umax/umin, and the vector size N for add
4812 //
4813 // For easier codegen and check inversion, we use the following encoding:
4814 //
4815 // 1. Bit-3 === requires or/umax (1) or and/umin (0) check
4816 // 2. Bit-2 === checks < 0 (1) or > -1 (0)
4817 // 3. Bit-1 === universal (1) or existential (0) check
4818 //
4819 // AnyNeg = 0b110: uses or/umax, checks negative, any-check
4820 // AllNonNeg = 0b101: uses or/umax, checks non-neg, all-check
4821 // AnyNonNeg = 0b000: uses and/umin, checks non-neg, any-check
4822 // AllNeg = 0b011: uses and/umin, checks negative, all-check
4823 //
4824 // XOR with 0b011 inverts the check (swaps all/any and neg/non-neg).
4825 //
4826 enum CheckKind : unsigned {
4827 AnyNonNeg = 0b000,
4828 AllNeg = 0b011,
4829 AllNonNeg = 0b101,
4830 AnyNeg = 0b110,
4831 };
4832 // Return true if we fold this check into or/umax and false for and/umin
4833 auto RequiresOr = [](CheckKind C) -> bool { return C & 0b100; };
4834 // Return true if we should check if result is negative and false otherwise
4835 auto IsNegativeCheck = [](CheckKind C) -> bool { return C & 0b010; };
4836 // Logically invert the check
4837 auto Invert = [](CheckKind C) { return CheckKind(C ^ 0b011); };
4838
4839 CheckKind Base;
4840 switch (OrigIID) {
4841 case Intrinsic::vector_reduce_or:
4842 case Intrinsic::vector_reduce_umax:
4843 Base = TestsNegative ? AnyNeg : AllNonNeg;
4844 break;
4845 case Intrinsic::vector_reduce_and:
4846 case Intrinsic::vector_reduce_umin:
4847 Base = TestsNegative ? AllNeg : AnyNonNeg;
4848 break;
4849 case Intrinsic::vector_reduce_add:
4850 Base = TestsNegative ? AllNeg : AllNonNeg;
4851 break;
4852 default:
4853 llvm_unreachable("Unexpected intrinsic");
4854 }
4855
4856 CheckKind Check = IsEq ? Base : Invert(Base);
4857
4858 auto PickCheaper = [&](Intrinsic::ID Arith, Intrinsic::ID MinMax) {
4859 InstructionCost ArithCost =
4861 VecTy, std::nullopt, CostKind);
4862 InstructionCost MinMaxCost =
4864 FastMathFlags(), CostKind);
4865 return ArithCost <= MinMaxCost ? std::make_pair(Arith, ArithCost)
4866 : std::make_pair(MinMax, MinMaxCost);
4867 };
4868
4869 // Choose output reduction based on encoding's MSB
4870 auto [NewIID, NewCost] = RequiresOr(Check)
4871 ? PickCheaper(Intrinsic::vector_reduce_or,
4872 Intrinsic::vector_reduce_umax)
4873 : PickCheaper(Intrinsic::vector_reduce_and,
4874 Intrinsic::vector_reduce_umin);
4875
4876 // Add cost of combining multiple sources with or/and
4877 if (NumSources > 1) {
4878 unsigned CombineOpc =
4879 RequiresOr(Check) ? Instruction::Or : Instruction::And;
4880 NewCost += TTI.getArithmeticInstrCost(CombineOpc, VecTy, CostKind) *
4881 (NumSources - 1);
4882 }
4883
4884 LLVM_DEBUG(dbgs() << "Found sign-bit reduction cmp: " << I << "\n OldCost: "
4885 << OldCost << " vs NewCost: " << NewCost << "\n");
4886
4887 if (NewCost > OldCost)
4888 return false;
4889
4890 // Generate the combined input and reduction
4891 Builder.SetInsertPoint(&I);
4892 Type *ScalarTy = VecTy->getScalarType();
4893
4894 Value *Input;
4895 if (NumSources == 1) {
4896 Input = Sources[0];
4897 } else {
4898 // Combine sources with or/and based on check type
4899 Input = RequiresOr(Check) ? Builder.CreateOr(Sources)
4900 : Builder.CreateAnd(Sources);
4901 }
4902
4903 Value *NewReduce = Builder.CreateIntrinsic(ScalarTy, NewIID, {Input});
4904 Value *NewCmp = IsNegativeCheck(Check) ? Builder.CreateIsNeg(NewReduce)
4905 : Builder.CreateIsNotNeg(NewReduce);
4906 replaceValue(I, *NewCmp);
4907 return true;
4908}
4909
4910/// Fold a zero test of reduce.or or reduce.umax into a boolean reduction.
4911///
4912/// Vectorization may produce IR that compares the result of a scalar reduction
4913/// with zero. Depending on the target, lowering a reduction and a scalar
4914/// comparison separately can cost more than reducing lane-wise comparison
4915/// results. This fold creates the latter form only when it is not costlier.
4916///
4917/// Before:
4918/// %r = call iT @llvm.vector.reduce.or.vNiT(<N x iT> %x)
4919/// %cmp = icmp ne iT %r, 0
4920///
4921/// After:
4922/// %lane.cmp = icmp ne <N x iT> %x, zeroinitializer
4923/// %cmp = call i1 @llvm.vector.reduce.or.vNi1(<N x i1> %lane.cmp)
4924///
4925/// `reduce.or` and `reduce.umax` are non-zero when at least one lane is
4926/// non-zero. Therefore, `icmp ne` uses the existential `reduce.or` test.
4927/// Conversely, `icmp eq` must check that every lane is zero, so it uses the
4928/// universal `reduce.and` test.
4929///
4930/// Before:
4931/// %r = call iT @llvm.vector.reduce.umax.vNiT(<N x iT> %x)
4932/// %cmp = icmp eq iT %r, 0
4933///
4934/// After:
4935/// %lane.cmp = icmp eq <N x iT> %x, zeroinitializer
4936/// %cmp = call i1 @llvm.vector.reduce.and.vNi1(<N x i1> %lane.cmp)
4937bool VectorCombine::foldReductionZeroTest(Instruction &I) {
4938 CmpPredicate Pred;
4939 Value *Op;
4940
4941 if (!match(&I, m_c_ICmp(Pred, m_Value(Op), m_Zero())) ||
4943 return false;
4944
4945 auto *II = dyn_cast<IntrinsicInst>(Op);
4946 if (!II || !II->hasOneUse())
4947 return false;
4948
4949 auto ReduceID = II->getIntrinsicID();
4950 if (ReduceID != Intrinsic::vector_reduce_or &&
4951 ReduceID != Intrinsic::vector_reduce_umax)
4952 return false;
4953
4954 Value *Vec = II->getArgOperand(0);
4955 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
4956 if (!VecTy || !VecTy->getElementType()->isIntegerTy())
4957 return false;
4958
4959 // Map the scalar zero test to an any-lane or all-lane boolean reduction.
4960 Intrinsic::ID NewIID = (Pred == ICmpInst::ICMP_NE)
4961 ? Intrinsic::vector_reduce_or
4962 : Intrinsic::vector_reduce_and;
4963
4964 // This is not an unconditional canonicalization: compare the cost of the
4965 // original scalar reduction and compare with the vector compare and i1
4966 // reduction replacement for both reduce.or and reduce.umax.
4967 InstructionCost OldCost = TTI.getInstructionCost(II, CostKind) +
4968 TTI.getInstructionCost(&I, CostKind);
4969
4970 auto *CmpTy = cast<VectorType>(CmpInst::makeCmpResultType(VecTy));
4971 InstructionCost NewCost =
4972 TTI.getCmpSelInstrCost(Instruction::ICmp, VecTy, CmpTy, Pred, CostKind);
4974 getArithmeticReductionInstruction(NewIID), CmpTy, std::nullopt, CostKind);
4975
4976 LLVM_DEBUG(dbgs() << "Found a reduction zero test: " << I << "\n OldCost: "
4977 << OldCost << " vs NewCost: " << NewCost << "\n");
4978
4979 if (!OldCost.isValid() || !NewCost.isValid() || NewCost > OldCost)
4980 return false;
4981
4982 Builder.SetInsertPoint(&I);
4983 Value *NewCmp = Builder.CreateICmp(Pred, Vec, Constant::getNullValue(VecTy));
4984 Value *NewReduce = Builder.CreateIntrinsic(NewIID, {CmpTy}, {NewCmp});
4985 replaceValue(I, *NewReduce);
4986 return true;
4987}
4988
4989/// vector.reduce.OP f(X_i) == 0 -> vector.reduce.OP X_i == 0
4990///
4991/// We can prove it for cases when:
4992///
4993/// 1. OP X_i == 0 <=> \forall i \in [1, N] X_i == 0
4994/// 1'. OP X_i == 0 <=> \exists j \in [1, N] X_j == 0
4995/// 2. f(x) == 0 <=> x == 0
4996///
4997/// From 1 and 2 (or 1' and 2), we can infer that
4998///
4999/// OP f(X_i) == 0 <=> OP X_i == 0.
5000///
5001/// (1)
5002/// OP f(X_i) == 0 <=> \forall i \in [1, N] f(X_i) == 0
5003/// (2)
5004/// <=> \forall i \in [1, N] X_i == 0
5005/// (1)
5006/// <=> OP(X_i) == 0
5007///
5008/// For some of the OP's and f's, we need to have domain constraints on X
5009/// to ensure properties 1 (or 1') and 2.
5010bool VectorCombine::foldICmpEqZeroVectorReduce(Instruction &I) {
5011 CmpPredicate Pred;
5012 Value *Op;
5013 if (!match(&I, m_ICmp(Pred, m_Value(Op), m_Zero())) ||
5015 return false;
5016
5017 auto *II = dyn_cast<IntrinsicInst>(Op);
5018 if (!II)
5019 return false;
5020
5021 switch (II->getIntrinsicID()) {
5022 case Intrinsic::vector_reduce_add:
5023 case Intrinsic::vector_reduce_or:
5024 case Intrinsic::vector_reduce_umin:
5025 case Intrinsic::vector_reduce_umax:
5026 case Intrinsic::vector_reduce_smin:
5027 case Intrinsic::vector_reduce_smax:
5028 break;
5029 default:
5030 return false;
5031 }
5032
5033 Value *InnerOp = II->getArgOperand(0);
5034
5035 // TODO: fixed vector type might be too restrictive
5036 if (!II->hasOneUse() || !isa<FixedVectorType>(InnerOp->getType()))
5037 return false;
5038
5039 Value *X = nullptr;
5040
5041 // Check for zero-preserving operations where f(x) = 0 <=> x = 0
5042 //
5043 // 1. f(x) = shl nuw x, y for arbitrary y
5044 // 2. f(x) = mul nuw x, c for defined c != 0
5045 // 3. f(x) = zext x
5046 // 4. f(x) = sext x
5047 // 5. f(x) = neg x
5048 //
5049 if (!(match(InnerOp, m_NUWShl(m_Value(X), m_Value())) || // Case 1
5050 match(InnerOp, m_NUWMul(m_Value(X), m_NonZeroInt())) || // Case 2
5051 match(InnerOp, m_ZExt(m_Value(X))) || // Case 3
5052 match(InnerOp, m_SExt(m_Value(X))) || // Case 4
5053 match(InnerOp, m_Neg(m_Value(X))) // Case 5
5054 ))
5055 return false;
5056
5057 SimplifyQuery S = SQ.getWithInstruction(&I);
5058 auto *XTy = cast<FixedVectorType>(X->getType());
5059
5060 // Check for domain constraints for all supported reductions.
5061 //
5062 // a. OR X_i - has property 1 for every X
5063 // b. UMAX X_i - has property 1 for every X
5064 // c. UMIN X_i - has property 1' for every X
5065 // d. SMAX X_i - has property 1 for X >= 0
5066 // e. SMIN X_i - has property 1' for X >= 0
5067 // f. ADD X_i - has property 1 for X >= 0 && ADD X_i doesn't sign wrap
5068 //
5069 // In order for the proof to work, we need 1 (or 1') to be true for both
5070 // OP f(X_i) and OP X_i and that's why below we check constraints twice.
5071 //
5072 // NOTE: ADD X_i holds property 1 for a mirror case as well, i.e. when
5073 // X <= 0 && ADD X_i doesn't sign wrap. However, due to the nature
5074 // of known bits, we can't reasonably hold knowledge of "either 0
5075 // or negative".
5076 switch (II->getIntrinsicID()) {
5077 case Intrinsic::vector_reduce_add: {
5078 // We need to check that both X_i and f(X_i) have enough leading
5079 // zeros to not overflow.
5080 KnownBits KnownX = computeKnownBits(X, S);
5081 KnownBits KnownFX = computeKnownBits(InnerOp, S);
5082 unsigned NumElems = XTy->getNumElements();
5083 // Adding N elements loses at most ceil(log2(N)) leading bits.
5084 unsigned LostBits = Log2_32_Ceil(NumElems);
5085 unsigned LeadingZerosX = KnownX.countMinLeadingZeros();
5086 unsigned LeadingZerosFX = KnownFX.countMinLeadingZeros();
5087 // Need at least one leading zero left after summation to ensure no overflow
5088 if (LeadingZerosX <= LostBits || LeadingZerosFX <= LostBits)
5089 return false;
5090
5091 // We are not checking whether X or f(X) are positive explicitly because
5092 // we implicitly checked for it when we checked if both cases have enough
5093 // leading zeros to not wrap addition.
5094 break;
5095 }
5096 case Intrinsic::vector_reduce_smin:
5097 case Intrinsic::vector_reduce_smax:
5098 // Check whether X >= 0 and f(X) >= 0
5099 if (!isKnownNonNegative(InnerOp, S) || !isKnownNonNegative(X, S))
5100 return false;
5101
5102 break;
5103 default:
5104 break;
5105 };
5106
5107 LLVM_DEBUG(dbgs() << "Found a reduction to 0 comparison with removable op: "
5108 << *II << "\n");
5109
5110 // For zext/sext, check if the transform is profitable using cost model.
5111 // For other operations (shl, mul, neg), we're removing an instruction
5112 // while keeping the same reduction type, so it's always profitable.
5113 if (isa<ZExtInst>(InnerOp) || isa<SExtInst>(InnerOp)) {
5114 auto *FXTy = cast<FixedVectorType>(InnerOp->getType());
5115 Intrinsic::ID IID = II->getIntrinsicID();
5116
5118 cast<CastInst>(InnerOp)->getOpcode(), FXTy, XTy,
5119 TTI::CastContextHint::None, CostKind, cast<CastInst>(InnerOp));
5120
5121 InstructionCost OldReduceCost, NewReduceCost;
5122 switch (IID) {
5123 case Intrinsic::vector_reduce_add:
5124 case Intrinsic::vector_reduce_or:
5125 OldReduceCost = TTI.getArithmeticReductionCost(
5126 getArithmeticReductionInstruction(IID), FXTy, std::nullopt, CostKind);
5127 NewReduceCost = TTI.getArithmeticReductionCost(
5128 getArithmeticReductionInstruction(IID), XTy, std::nullopt, CostKind);
5129 break;
5130 case Intrinsic::vector_reduce_umin:
5131 case Intrinsic::vector_reduce_umax:
5132 case Intrinsic::vector_reduce_smin:
5133 case Intrinsic::vector_reduce_smax:
5134 OldReduceCost = TTI.getMinMaxReductionCost(
5135 getMinMaxReductionIntrinsicOp(IID), FXTy, FastMathFlags(), CostKind);
5136 NewReduceCost = TTI.getMinMaxReductionCost(
5137 getMinMaxReductionIntrinsicOp(IID), XTy, FastMathFlags(), CostKind);
5138 break;
5139 default:
5140 llvm_unreachable("Unexpected reduction");
5141 }
5142
5143 InstructionCost OldCost = OldReduceCost + ExtCost;
5144 InstructionCost NewCost =
5145 NewReduceCost + (InnerOp->hasOneUse() ? 0 : ExtCost);
5146
5147 LLVM_DEBUG(dbgs() << "Found a removable extension before reduction: "
5148 << *InnerOp << "\n OldCost: " << OldCost
5149 << " vs NewCost: " << NewCost << "\n");
5150
5151 // We consider transformation to still be potentially beneficial even
5152 // when the costs are the same because we might remove a use from f(X)
5153 // and unlock other optimizations. Equal costs would just mean that we
5154 // didn't make it worse in the worst case.
5155 if (NewCost > OldCost)
5156 return false;
5157 }
5158
5159 // Since we support zext and sext as f, we might change the scalar type
5160 // of the intrinsic.
5161 Type *Ty = XTy->getScalarType();
5162 Value *NewReduce = Builder.CreateIntrinsic(Ty, II->getIntrinsicID(), {X});
5163 Value *NewCmp =
5164 Builder.CreateICmp(Pred, NewReduce, ConstantInt::getNullValue(Ty));
5165 replaceValue(I, *NewCmp);
5166 return true;
5167}
5168
5169/// Fold comparisons of reduce.or/reduce.and with reduce.umax/reduce.umin
5170/// based on cost, preserving the comparison semantics.
5171///
5172/// We use two fundamental properties for each pair:
5173///
5174/// 1. or(X) == 0 <=> umax(X) == 0
5175/// 2. or(X) == 1 <=> umax(X) == 1
5176/// 3. sign(or(X)) == sign(umax(X))
5177///
5178/// 1. and(X) == -1 <=> umin(X) == -1
5179/// 2. and(X) == -2 <=> umin(X) == -2
5180/// 3. sign(and(X)) == sign(umin(X))
5181///
5182/// From these we can infer the following transformations:
5183/// a. or(X) ==/!= 0 <-> umax(X) ==/!= 0
5184/// b. or(X) s< 0 <-> umax(X) s< 0
5185/// c. or(X) s> -1 <-> umax(X) s> -1
5186/// d. or(X) s< 1 <-> umax(X) s< 1
5187/// e. or(X) ==/!= 1 <-> umax(X) ==/!= 1
5188/// f. or(X) s< 2 <-> umax(X) s< 2
5189/// g. and(X) ==/!= -1 <-> umin(X) ==/!= -1
5190/// h. and(X) s< 0 <-> umin(X) s< 0
5191/// i. and(X) s> -1 <-> umin(X) s> -1
5192/// j. and(X) s> -2 <-> umin(X) s> -2
5193/// k. and(X) ==/!= -2 <-> umin(X) ==/!= -2
5194/// l. and(X) s> -3 <-> umin(X) s> -3
5195///
5196bool VectorCombine::foldEquivalentReductionCmp(Instruction &I) {
5197 CmpPredicate Pred;
5198 Value *ReduceOp;
5199 const APInt *CmpVal;
5200 if (!match(&I, m_ICmp(Pred, m_Value(ReduceOp), m_APInt(CmpVal))))
5201 return false;
5202
5203 auto *II = dyn_cast<IntrinsicInst>(ReduceOp);
5204 if (!II || !II->hasOneUse())
5205 return false;
5206
5207 const auto IsValidOrUmaxCmp = [&]() {
5208 // or === umax for i1
5209 if (CmpVal->getBitWidth() == 1)
5210 return true;
5211
5212 // Cases a and e
5213 bool IsEquality =
5214 (CmpVal->isZero() || CmpVal->isOne()) && ICmpInst::isEquality(Pred);
5215 // Case c
5216 bool IsPositive = CmpVal->isAllOnes() && Pred == ICmpInst::ICMP_SGT;
5217 // Cases b, d, and f
5218 bool IsNegative = (CmpVal->isZero() || CmpVal->isOne() || *CmpVal == 2) &&
5219 Pred == ICmpInst::ICMP_SLT;
5220 return IsEquality || IsPositive || IsNegative;
5221 };
5222
5223 const auto IsValidAndUminCmp = [&]() {
5224 // and === umin for i1
5225 if (CmpVal->getBitWidth() == 1)
5226 return true;
5227
5228 const auto LeadingOnes = CmpVal->countl_one();
5229
5230 // Cases g and k
5231 bool IsEquality =
5232 (CmpVal->isAllOnes() || LeadingOnes + 1 == CmpVal->getBitWidth()) &&
5234 // Case h
5235 bool IsNegative = CmpVal->isZero() && Pred == ICmpInst::ICMP_SLT;
5236 // Cases i, j, and l
5237 bool IsPositive =
5238 // if the number has at least N - 2 leading ones
5239 // and the two LSBs are:
5240 // - 1 x 1 -> -1
5241 // - 1 x 0 -> -2
5242 // - 0 x 1 -> -3
5243 LeadingOnes + 2 >= CmpVal->getBitWidth() &&
5244 ((*CmpVal)[0] || (*CmpVal)[1]) && Pred == ICmpInst::ICMP_SGT;
5245 return IsEquality || IsNegative || IsPositive;
5246 };
5247
5248 Intrinsic::ID OriginalIID = II->getIntrinsicID();
5249 Intrinsic::ID AlternativeIID;
5250
5251 // Check if this is a valid comparison pattern and determine the alternate
5252 // reduction intrinsic.
5253 switch (OriginalIID) {
5254 case Intrinsic::vector_reduce_or:
5255 if (!IsValidOrUmaxCmp())
5256 return false;
5257 AlternativeIID = Intrinsic::vector_reduce_umax;
5258 break;
5259 case Intrinsic::vector_reduce_umax:
5260 if (!IsValidOrUmaxCmp())
5261 return false;
5262 AlternativeIID = Intrinsic::vector_reduce_or;
5263 break;
5264 case Intrinsic::vector_reduce_and:
5265 if (!IsValidAndUminCmp())
5266 return false;
5267 AlternativeIID = Intrinsic::vector_reduce_umin;
5268 break;
5269 case Intrinsic::vector_reduce_umin:
5270 if (!IsValidAndUminCmp())
5271 return false;
5272 AlternativeIID = Intrinsic::vector_reduce_and;
5273 break;
5274 default:
5275 return false;
5276 }
5277
5278 Value *X = II->getArgOperand(0);
5279 auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
5280 if (!VecTy)
5281 return false;
5282
5283 const auto GetReductionCost = [&](Intrinsic::ID IID) -> InstructionCost {
5284 unsigned ReductionOpc = getArithmeticReductionInstruction(IID);
5285 if (ReductionOpc != Instruction::ICmp)
5286 return TTI.getArithmeticReductionCost(ReductionOpc, VecTy, std::nullopt,
5287 CostKind);
5289 FastMathFlags(), CostKind);
5290 };
5291
5292 InstructionCost OrigCost = GetReductionCost(OriginalIID);
5293 InstructionCost AltCost = GetReductionCost(AlternativeIID);
5294
5295 LLVM_DEBUG(dbgs() << "Found equivalent reduction cmp: " << I
5296 << "\n OrigCost: " << OrigCost
5297 << " vs AltCost: " << AltCost << "\n");
5298
5299 if (AltCost >= OrigCost)
5300 return false;
5301
5302 Builder.SetInsertPoint(&I);
5303 Type *ScalarTy = VecTy->getScalarType();
5304 Value *NewReduce = Builder.CreateIntrinsic(ScalarTy, AlternativeIID, {X});
5305 Value *NewCmp =
5306 Builder.CreateICmp(Pred, NewReduce, ConstantInt::get(ScalarTy, *CmpVal));
5307
5308 replaceValue(I, *NewCmp);
5309 return true;
5310}
5311
5312/// Used by foldReduceAddCmpZero to check if we can prove that a value is
5313/// non-positive.
5314/// KnownBits cannot see sext <? x i1> as non-positive: each top bit equals a
5315/// single unknown input bit, which a per-bit lattice cannot track. The fold's
5316/// target shape is popcount-style sums of <N x i1> valid/invalid masks (e.g.
5317/// ray-intersection hits) tested for any-hit.
5318/// Previous attempts to approximate the known bits of such expressions were
5319/// using a fully recursive value tracking approach to infer a constant range
5320/// but ultimately turned to be too expensive in compile time.
5321static bool isKnownNonPositive(const Value *V, const SimplifyQuery &SQ,
5322 unsigned Depth = 0) {
5323 constexpr unsigned MaxLocalDepth = 2;
5324 if (Depth > MaxLocalDepth)
5325 return false;
5326
5327 auto NumSignBits = [&](const Value *X) {
5328 return ComputeNumSignBits(X, SQ.DL, SQ.AC, SQ.CtxI, SQ.DT);
5329 };
5330 if (NumSignBits(V) == V->getType()->getScalarSizeInBits())
5331 return true;
5332
5333 Value *A, *B;
5334 if (match(V, m_Add(m_Value(A), m_Value(B))))
5335 return NumSignBits(A) >= 2 && NumSignBits(B) >= 2 &&
5336 isKnownNonPositive(A, SQ, Depth + 1) &&
5337 isKnownNonPositive(B, SQ, Depth + 1);
5338
5339 return computeKnownBits(V, SQ).isNonPositive();
5340}
5341
5342/// Fold (icmp pred (reduce.add X), 0) to (icmp pred' (reduce.or X), 0) when X
5343/// has lanes known to all be non-negative or all non-positive, so that
5344/// sum == 0 iff every lane is 0. Falls back to reduce.umax if reduce.or is
5345/// more expensive on the target.
5346bool VectorCombine::foldReduceAddCmpZero(Instruction &I) {
5347 CmpPredicate Pred;
5348 Value *Vec;
5349 if (!match(&I, m_ICmp(Pred,
5351 m_Value(Vec))),
5352 m_Zero())))
5353 return false;
5354
5355 auto *VecTy = dyn_cast<FixedVectorType>(Vec->getType());
5356 if (!VecTy || VecTy->getNumElements() < 2)
5357 return false;
5358
5359 SimplifyQuery Q = SQ.getWithInstruction(&I);
5360 bool IsNonNegative = isKnownNonNegative(Vec, Q);
5361 bool IsNonPositive = !IsNonNegative && isKnownNonPositive(Vec, Q);
5362 if (!IsNonNegative && !IsNonPositive)
5363 return false;
5364
5365 // Summing NumElts lanes can consume up to log2(NumElts) sign bits. Require
5366 // strictly more headroom than that so the sum cannot wrap to zero.
5367 unsigned NumElts = VecTy->getNumElements();
5368 unsigned NumSignBits = ComputeNumSignBits(Vec, *DL, SQ.AC, &I, &DT);
5369 if (Log2_32(NumElts) >= NumSignBits)
5370 return false;
5371
5372 ICmpInst::Predicate NewPred;
5373 switch (Pred) {
5374 case ICmpInst::ICMP_EQ:
5375 case ICmpInst::ICMP_ULE:
5376 case ICmpInst::ICMP_SLE:
5377 case ICmpInst::ICMP_SGE:
5378 NewPred = ICmpInst::ICMP_EQ;
5379 break;
5380 case ICmpInst::ICMP_NE:
5381 case ICmpInst::ICMP_UGT:
5382 case ICmpInst::ICMP_SGT:
5383 case ICmpInst::ICMP_SLT:
5384 NewPred = ICmpInst::ICMP_NE;
5385 break;
5386 default:
5387 return false;
5388 }
5389
5390 // SGT and SLE on a non-positive tree, and SLT and SGE on a non-negative
5391 // tree, are tautologies (always true or always false). Leave those to
5392 // InstCombine rather than mapping them here. Remaining signed inequalities
5393 // also need one extra sign bit so the sum cannot flip sign.
5394 if (!IsNonNegative &&
5395 (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE))
5396 return false;
5397 if (!IsNonPositive &&
5398 (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE))
5399 return false;
5400 if ((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLE ||
5401 Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) &&
5402 Log2_32(NumElts) >= NumSignBits - 1)
5403 return false;
5404
5406 Instruction::Add, VecTy, std::nullopt, CostKind);
5408 Instruction::Or, VecTy, std::nullopt, CostKind);
5410 Intrinsic::umax, VecTy, FastMathFlags(), CostKind);
5411 if (!OrCost.isValid() && !UmaxCost.isValid())
5412 return false;
5413 bool UseOr = OrCost.isValid() && (!UmaxCost.isValid() || OrCost <= UmaxCost);
5414 InstructionCost AltCost = UseOr ? OrCost : UmaxCost;
5415 if (AltCost > OrigCost)
5416 return false;
5417
5418 Builder.SetInsertPoint(&I);
5419 Value *NewReduce = UseOr ? Builder.CreateOrReduce(Vec)
5420 : Builder.CreateIntrinsic(
5421 Intrinsic::vector_reduce_umax, {VecTy}, {Vec});
5422 Value *NewCmp = Builder.CreateICmp(
5423 NewPred, NewReduce, ConstantInt::getNullValue(VecTy->getScalarType()));
5424 replaceValue(I, *NewCmp);
5425 return true;
5426}
5427
5428/// Returns true if this ShuffleVectorInst eventually feeds into a
5429/// vector reduction intrinsic (e.g., vector_reduce_add) by only following
5430/// chains of shuffles and binary operators (in any combination/order).
5431/// The search does not go deeper than the given Depth.
5433 constexpr unsigned MaxVisited = 32;
5436 bool FoundReduction = false;
5437
5438 WorkList.push_back(SVI);
5439 while (!WorkList.empty()) {
5440 Instruction *I = WorkList.pop_back_val();
5441 for (User *U : I->users()) {
5442 auto *UI = cast<Instruction>(U);
5443 if (!UI || !Visited.insert(UI).second)
5444 continue;
5445 if (Visited.size() > MaxVisited)
5446 return false;
5447 if (auto *II = dyn_cast<IntrinsicInst>(UI)) {
5448 // More than one reduction reached
5449 if (FoundReduction)
5450 return false;
5451 switch (II->getIntrinsicID()) {
5452 case Intrinsic::vector_reduce_add:
5453 case Intrinsic::vector_reduce_mul:
5454 case Intrinsic::vector_reduce_and:
5455 case Intrinsic::vector_reduce_or:
5456 case Intrinsic::vector_reduce_xor:
5457 case Intrinsic::vector_reduce_smin:
5458 case Intrinsic::vector_reduce_smax:
5459 case Intrinsic::vector_reduce_umin:
5460 case Intrinsic::vector_reduce_umax:
5461 FoundReduction = true;
5462 continue;
5463 default:
5464 return false;
5465 }
5466 }
5467
5469 return false;
5470
5471 WorkList.emplace_back(UI);
5472 }
5473 }
5474 return FoundReduction;
5475}
5476
5477/// This method looks for groups of shuffles acting on binops, of the form:
5478/// %x = shuffle ...
5479/// %y = shuffle ...
5480/// %a = binop %x, %y
5481/// %b = binop %x, %y
5482/// shuffle %a, %b, selectmask
5483/// We may, especially if the shuffle is wider than legal, be able to convert
5484/// the shuffle to a form where only parts of a and b need to be computed. On
5485/// architectures with no obvious "select" shuffle, this can reduce the total
5486/// number of operations if the target reports them as cheaper.
5487bool VectorCombine::foldSelectShuffle(Instruction &I, bool FromReduction) {
5488 auto *SVI = cast<ShuffleVectorInst>(&I);
5489 auto *VT = cast<FixedVectorType>(I.getType());
5490 auto *Op0 = dyn_cast<Instruction>(SVI->getOperand(0));
5491 auto *Op1 = dyn_cast<Instruction>(SVI->getOperand(1));
5492 if (!Op0 || !Op1 || Op0 == Op1 || !Op0->isBinaryOp() || !Op1->isBinaryOp() ||
5493 VT != Op0->getType())
5494 return false;
5495
5496 auto *SVI0A = dyn_cast<Instruction>(Op0->getOperand(0));
5497 auto *SVI0B = dyn_cast<Instruction>(Op0->getOperand(1));
5498 auto *SVI1A = dyn_cast<Instruction>(Op1->getOperand(0));
5499 auto *SVI1B = dyn_cast<Instruction>(Op1->getOperand(1));
5500 SmallPtrSet<Instruction *, 4> InputShuffles({SVI0A, SVI0B, SVI1A, SVI1B});
5501 auto checkSVNonOpUses = [&](Instruction *I) {
5502 if (!I || I->getOperand(0)->getType() != VT)
5503 return true;
5504 return any_of(I->users(), [&](User *U) {
5505 return U != Op0 && U != Op1 &&
5506 !(isa<ShuffleVectorInst>(U) &&
5507 (InputShuffles.contains(cast<Instruction>(U)) ||
5508 isInstructionTriviallyDead(cast<Instruction>(U))));
5509 });
5510 };
5511 if (checkSVNonOpUses(SVI0A) || checkSVNonOpUses(SVI0B) ||
5512 checkSVNonOpUses(SVI1A) || checkSVNonOpUses(SVI1B))
5513 return false;
5514
5515 // Collect all the uses that are shuffles that we can transform together. We
5516 // may not have a single shuffle, but a group that can all be transformed
5517 // together profitably.
5519 auto collectShuffles = [&](Instruction *I) {
5520 for (auto *U : I->users()) {
5522 if (!SV || SV->getType() != VT)
5523 return false;
5524 if ((SV->getOperand(0) != Op0 && SV->getOperand(0) != Op1) ||
5525 (SV->getOperand(1) != Op0 && SV->getOperand(1) != Op1))
5526 return false;
5527 if (!llvm::is_contained(Shuffles, SV))
5528 Shuffles.push_back(SV);
5529 }
5530 return true;
5531 };
5532 if (!collectShuffles(Op0) || !collectShuffles(Op1))
5533 return false;
5534 // From a reduction, we need to be processing a single shuffle, otherwise the
5535 // other uses will not be lane-invariant.
5536 if (FromReduction && Shuffles.size() > 1)
5537 return false;
5538
5539 // Add any shuffle uses for the shuffles we have found, to include them in our
5540 // cost calculations.
5541 if (!FromReduction) {
5542 for (size_t Idx = 0, E = Shuffles.size(); Idx != E; ++Idx) {
5543 for (auto *U : Shuffles[Idx]->users()) {
5544 ShuffleVectorInst *SSV = dyn_cast<ShuffleVectorInst>(U);
5545 if (SSV && isa<UndefValue>(SSV->getOperand(1)) && SSV->getType() == VT)
5546 Shuffles.push_back(SSV);
5547 }
5548 }
5549 }
5550
5551 // For each of the output shuffles, we try to sort all the first vector
5552 // elements to the beginning, followed by the second array elements at the
5553 // end. If the binops are legalized to smaller vectors, this may reduce total
5554 // number of binops. We compute the ReconstructMask mask needed to convert
5555 // back to the original lane order.
5557 SmallVector<SmallVector<int>> OrigReconstructMasks;
5558 int MaxV1Elt = 0, MaxV2Elt = 0;
5559 unsigned NumElts = VT->getNumElements();
5560 for (ShuffleVectorInst *SVN : Shuffles) {
5561 SmallVector<int> Mask;
5562 SVN->getShuffleMask(Mask);
5563
5564 // Check the operands are the same as the original, or reversed (in which
5565 // case we need to commute the mask).
5566 Value *SVOp0 = SVN->getOperand(0);
5567 Value *SVOp1 = SVN->getOperand(1);
5568 if (isa<UndefValue>(SVOp1)) {
5569 auto *SSV = cast<ShuffleVectorInst>(SVOp0);
5570 SVOp0 = SSV->getOperand(0);
5571 SVOp1 = SSV->getOperand(1);
5572 for (int &Elem : Mask) {
5573 if (Elem >= static_cast<int>(SSV->getShuffleMask().size()))
5574 return false;
5575 Elem = Elem < 0 ? Elem : SSV->getMaskValue(Elem);
5576 }
5577 }
5578 if (SVOp0 == Op1 && SVOp1 == Op0) {
5579 std::swap(SVOp0, SVOp1);
5581 }
5582 if (SVOp0 != Op0 || SVOp1 != Op1)
5583 return false;
5584
5585 // Calculate the reconstruction mask for this shuffle, as the mask needed to
5586 // take the packed values from Op0/Op1 and reconstructing to the original
5587 // order.
5588 SmallVector<int> ReconstructMask;
5589 for (unsigned I = 0; I < Mask.size(); I++) {
5590 if (Mask[I] < 0) {
5591 ReconstructMask.push_back(-1);
5592 } else if (Mask[I] < static_cast<int>(NumElts)) {
5593 MaxV1Elt = std::max(MaxV1Elt, Mask[I]);
5594 auto It = find_if(V1, [&](const std::pair<int, int> &A) {
5595 return Mask[I] == A.first;
5596 });
5597 if (It != V1.end())
5598 ReconstructMask.push_back(It - V1.begin());
5599 else {
5600 ReconstructMask.push_back(V1.size());
5601 V1.emplace_back(Mask[I], V1.size());
5602 }
5603 } else {
5604 MaxV2Elt = std::max<int>(MaxV2Elt, Mask[I] - NumElts);
5605 auto It = find_if(V2, [&](const std::pair<int, int> &A) {
5606 return Mask[I] - static_cast<int>(NumElts) == A.first;
5607 });
5608 if (It != V2.end())
5609 ReconstructMask.push_back(NumElts + It - V2.begin());
5610 else {
5611 ReconstructMask.push_back(NumElts + V2.size());
5612 V2.emplace_back(Mask[I] - NumElts, NumElts + V2.size());
5613 }
5614 }
5615 }
5616
5617 // For reductions, we know that the lane ordering out doesn't alter the
5618 // result. In-order can help simplify the shuffle away.
5619 if (FromReduction)
5620 sort(ReconstructMask);
5621 OrigReconstructMasks.push_back(std::move(ReconstructMask));
5622 }
5623
5624 // If the Maximum element used from V1 and V2 are not larger than the new
5625 // vectors, the vectors are already packes and performing the optimization
5626 // again will likely not help any further. This also prevents us from getting
5627 // stuck in a cycle in case the costs do not also rule it out.
5628 if (V1.empty() || V2.empty() ||
5629 (MaxV1Elt == static_cast<int>(V1.size()) - 1 &&
5630 MaxV2Elt == static_cast<int>(V2.size()) - 1))
5631 return false;
5632
5633 // GetBaseMaskValue takes one of the inputs, which may either be a shuffle, a
5634 // shuffle of another shuffle, or not a shuffle (that is treated like a
5635 // identity shuffle).
5636 auto GetBaseMaskValue = [&](Instruction *I, int M) {
5638 if (!SV)
5639 return M;
5640 if (isa<UndefValue>(SV->getOperand(1)))
5641 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
5642 if (InputShuffles.contains(SSV))
5643 return SSV->getMaskValue(SV->getMaskValue(M));
5644 return SV->getMaskValue(M);
5645 };
5646
5647 // Attempt to sort the inputs my ascending mask values to make simpler input
5648 // shuffles and push complex shuffles down to the uses. We sort on the first
5649 // of the two input shuffle orders, to try and get at least one input into a
5650 // nice order.
5651 auto SortBase = [&](Instruction *A, std::pair<int, int> X,
5652 std::pair<int, int> Y) {
5653 int MXA = GetBaseMaskValue(A, X.first);
5654 int MYA = GetBaseMaskValue(A, Y.first);
5655 return MXA < MYA;
5656 };
5657 stable_sort(V1, [&](std::pair<int, int> A, std::pair<int, int> B) {
5658 return SortBase(SVI0A, A, B);
5659 });
5660 stable_sort(V2, [&](std::pair<int, int> A, std::pair<int, int> B) {
5661 return SortBase(SVI1A, A, B);
5662 });
5663 // Calculate our ReconstructMasks from the OrigReconstructMasks and the
5664 // modified order of the input shuffles.
5665 SmallVector<SmallVector<int>> ReconstructMasks;
5666 for (const auto &Mask : OrigReconstructMasks) {
5667 SmallVector<int> ReconstructMask;
5668 for (int M : Mask) {
5669 auto FindIndex = [](const SmallVector<std::pair<int, int>> &V, int M) {
5670 auto It = find_if(V, [M](auto A) { return A.second == M; });
5671 assert(It != V.end() && "Expected all entries in Mask");
5672 return std::distance(V.begin(), It);
5673 };
5674 if (M < 0)
5675 ReconstructMask.push_back(-1);
5676 else if (M < static_cast<int>(NumElts)) {
5677 ReconstructMask.push_back(FindIndex(V1, M));
5678 } else {
5679 ReconstructMask.push_back(NumElts + FindIndex(V2, M));
5680 }
5681 }
5682 ReconstructMasks.push_back(std::move(ReconstructMask));
5683 }
5684
5685 // Calculate the masks needed for the new input shuffles, which get padded
5686 // with undef
5687 SmallVector<int> V1A, V1B, V2A, V2B;
5688 for (unsigned I = 0; I < V1.size(); I++) {
5689 V1A.push_back(GetBaseMaskValue(SVI0A, V1[I].first));
5690 V1B.push_back(GetBaseMaskValue(SVI0B, V1[I].first));
5691 }
5692 for (unsigned I = 0; I < V2.size(); I++) {
5693 V2A.push_back(GetBaseMaskValue(SVI1A, V2[I].first));
5694 V2B.push_back(GetBaseMaskValue(SVI1B, V2[I].first));
5695 }
5696 while (V1A.size() < NumElts) {
5699 }
5700 while (V2A.size() < NumElts) {
5703 }
5704
5705 auto AddShuffleCost = [&](InstructionCost C, Instruction *I) {
5707 if (!SV)
5708 return C;
5709 return C + TTI.getShuffleCost(isa<UndefValue>(SV->getOperand(1))
5712 VT, VT, CostKind, SV->getShuffleMask());
5713 };
5714 auto AddShuffleMaskCost = [&](InstructionCost C, ArrayRef<int> Mask) {
5715 return C +
5716 TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, VT, VT, CostKind, Mask);
5717 };
5718
5719 unsigned ElementSize = VT->getElementType()->getPrimitiveSizeInBits();
5720 unsigned MaxVectorSize =
5722 unsigned MaxElementsInVector = MaxVectorSize / ElementSize;
5723 if (MaxElementsInVector == 0)
5724 return false;
5725 // When there are multiple shufflevector operations on the same input,
5726 // especially when the vector length is larger than the register size,
5727 // identical shuffle patterns may occur across different groups of elements.
5728 // To avoid overestimating the cost by counting these repeated shuffles more
5729 // than once, we only account for unique shuffle patterns. This adjustment
5730 // prevents inflated costs in the cost model for wide vectors split into
5731 // several register-sized groups.
5732 std::set<SmallVector<int, 4>> UniqueShuffles;
5733 auto AddShuffleMaskAdjustedCost = [&](InstructionCost C, ArrayRef<int> Mask) {
5734 // Compute the cost for performing the shuffle over the full vector.
5735 auto ShuffleCost =
5736 TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, VT, VT, CostKind, Mask);
5737 unsigned NumFullVectors = Mask.size() / MaxElementsInVector;
5738 if (NumFullVectors < 2)
5739 return C + ShuffleCost;
5740 SmallVector<int, 4> SubShuffle(MaxElementsInVector);
5741 unsigned NumUniqueGroups = 0;
5742 unsigned NumGroups = Mask.size() / MaxElementsInVector;
5743 // For each group of MaxElementsInVector contiguous elements,
5744 // collect their shuffle pattern and insert into the set of unique patterns.
5745 for (unsigned I = 0; I < NumFullVectors; ++I) {
5746 for (unsigned J = 0; J < MaxElementsInVector; ++J)
5747 SubShuffle[J] = Mask[MaxElementsInVector * I + J];
5748 if (UniqueShuffles.insert(SubShuffle).second)
5749 NumUniqueGroups += 1;
5750 }
5751 return C + ShuffleCost * NumUniqueGroups / NumGroups;
5752 };
5753 auto AddShuffleAdjustedCost = [&](InstructionCost C, Instruction *I) {
5755 if (!SV)
5756 return C;
5757 SmallVector<int, 16> Mask;
5758 SV->getShuffleMask(Mask);
5759 return AddShuffleMaskAdjustedCost(C, Mask);
5760 };
5761 // Check that input consists of ShuffleVectors applied to the same input
5762 auto AllShufflesHaveSameOperands =
5763 [](SmallPtrSetImpl<Instruction *> &InputShuffles) {
5764 if (InputShuffles.size() < 2)
5765 return false;
5766 ShuffleVectorInst *FirstSV =
5767 dyn_cast<ShuffleVectorInst>(*InputShuffles.begin());
5768 if (!FirstSV)
5769 return false;
5770
5771 Value *In0 = FirstSV->getOperand(0), *In1 = FirstSV->getOperand(1);
5772 return std::all_of(
5773 std::next(InputShuffles.begin()), InputShuffles.end(),
5774 [&](Instruction *I) {
5775 ShuffleVectorInst *SV = dyn_cast<ShuffleVectorInst>(I);
5776 return SV && SV->getOperand(0) == In0 && SV->getOperand(1) == In1;
5777 });
5778 };
5779
5780 // Get the costs of the shuffles + binops before and after with the new
5781 // shuffle masks.
5782 InstructionCost CostBefore =
5783 TTI.getArithmeticInstrCost(Op0->getOpcode(), VT, CostKind) +
5784 TTI.getArithmeticInstrCost(Op1->getOpcode(), VT, CostKind);
5785 CostBefore += std::accumulate(Shuffles.begin(), Shuffles.end(),
5786 InstructionCost(0), AddShuffleCost);
5787 if (AllShufflesHaveSameOperands(InputShuffles)) {
5788 UniqueShuffles.clear();
5789 CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(),
5790 InstructionCost(0), AddShuffleAdjustedCost);
5791 } else {
5792 CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(),
5793 InstructionCost(0), AddShuffleCost);
5794 }
5795
5796 // The new binops will be unused for lanes past the used shuffle lengths.
5797 // These types attempt to get the correct cost for that from the target.
5798 FixedVectorType *Op0SmallVT =
5799 FixedVectorType::get(VT->getScalarType(), V1.size());
5800 FixedVectorType *Op1SmallVT =
5801 FixedVectorType::get(VT->getScalarType(), V2.size());
5802 InstructionCost CostAfter =
5803 TTI.getArithmeticInstrCost(Op0->getOpcode(), Op0SmallVT, CostKind) +
5804 TTI.getArithmeticInstrCost(Op1->getOpcode(), Op1SmallVT, CostKind);
5805 UniqueShuffles.clear();
5806 CostAfter += std::accumulate(ReconstructMasks.begin(), ReconstructMasks.end(),
5807 InstructionCost(0), AddShuffleMaskAdjustedCost);
5808 std::set<SmallVector<int>> OutputShuffleMasks({V1A, V1B, V2A, V2B});
5809 CostAfter +=
5810 std::accumulate(OutputShuffleMasks.begin(), OutputShuffleMasks.end(),
5811 InstructionCost(0), AddShuffleMaskCost);
5812
5813 LLVM_DEBUG(dbgs() << "Found a binop select shuffle pattern: " << I << "\n");
5814 LLVM_DEBUG(dbgs() << " CostBefore: " << CostBefore
5815 << " vs CostAfter: " << CostAfter << "\n");
5816 if (CostBefore < CostAfter ||
5817 (CostBefore == CostAfter && !feedsIntoVectorReduction(SVI)))
5818 return false;
5819
5820 // The cost model has passed, create the new instructions.
5821 auto GetShuffleOperand = [&](Instruction *I, unsigned Op) -> Value * {
5823 if (!SV)
5824 return I;
5825 if (isa<UndefValue>(SV->getOperand(1)))
5826 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
5827 if (InputShuffles.contains(SSV))
5828 return SSV->getOperand(Op);
5829 return SV->getOperand(Op);
5830 };
5831 Builder.SetInsertPoint(*SVI0A->getInsertionPointAfterDef());
5832 Value *NSV0A = Builder.CreateShuffleVector(GetShuffleOperand(SVI0A, 0),
5833 GetShuffleOperand(SVI0A, 1), V1A);
5834 Builder.SetInsertPoint(*SVI0B->getInsertionPointAfterDef());
5835 Value *NSV0B = Builder.CreateShuffleVector(GetShuffleOperand(SVI0B, 0),
5836 GetShuffleOperand(SVI0B, 1), V1B);
5837 Builder.SetInsertPoint(*SVI1A->getInsertionPointAfterDef());
5838 Value *NSV1A = Builder.CreateShuffleVector(GetShuffleOperand(SVI1A, 0),
5839 GetShuffleOperand(SVI1A, 1), V2A);
5840 Builder.SetInsertPoint(*SVI1B->getInsertionPointAfterDef());
5841 Value *NSV1B = Builder.CreateShuffleVector(GetShuffleOperand(SVI1B, 0),
5842 GetShuffleOperand(SVI1B, 1), V2B);
5843 Builder.SetInsertPoint(Op0);
5844 Value *NOp0 = Builder.CreateBinOp((Instruction::BinaryOps)Op0->getOpcode(),
5845 NSV0A, NSV0B);
5846 if (auto *I = dyn_cast<Instruction>(NOp0))
5847 I->copyIRFlags(Op0, true);
5848 Builder.SetInsertPoint(Op1);
5849 Value *NOp1 = Builder.CreateBinOp((Instruction::BinaryOps)Op1->getOpcode(),
5850 NSV1A, NSV1B);
5851 if (auto *I = dyn_cast<Instruction>(NOp1))
5852 I->copyIRFlags(Op1, true);
5853
5854 for (int S = 0, E = ReconstructMasks.size(); S != E; S++) {
5855 Builder.SetInsertPoint(Shuffles[S]);
5856 Value *NSV = Builder.CreateShuffleVector(NOp0, NOp1, ReconstructMasks[S]);
5857 replaceValue(*Shuffles[S], *NSV, false);
5858 }
5859
5860 return true;
5861}
5862
5863/// Check if instruction depends on ZExt and this ZExt can be moved after the
5864/// instruction. Move ZExt if it is profitable. For example:
5865/// logic(zext(x),y) -> zext(logic(x,trunc(y)))
5866/// lshr((zext(x),y) -> zext(lshr(x,trunc(y)))
5867/// Cost model calculations takes into account if zext(x) has other users and
5868/// whether it can be propagated through them too.
5869bool VectorCombine::shrinkType(Instruction &I) {
5870 Value *ZExted, *OtherOperand;
5871 if (!match(&I, m_c_BitwiseLogic(m_ZExt(m_Value(ZExted)),
5872 m_Value(OtherOperand))) &&
5873 !match(&I, m_LShr(m_ZExt(m_Value(ZExted)), m_Value(OtherOperand))))
5874 return false;
5875
5876 Value *ZExtOperand = I.getOperand(I.getOperand(0) == OtherOperand ? 1 : 0);
5877
5878 auto *BigTy = cast<FixedVectorType>(I.getType());
5879 auto *SmallTy = cast<FixedVectorType>(ZExted->getType());
5880 unsigned BW = SmallTy->getElementType()->getPrimitiveSizeInBits();
5881
5882 if (I.getOpcode() == Instruction::LShr) {
5883 // Check that the shift amount is less than the number of bits in the
5884 // smaller type. Otherwise, the smaller lshr will return a poison value.
5885 KnownBits ShAmtKB = computeKnownBits(I.getOperand(1), *DL);
5886 if (ShAmtKB.getMaxValue().uge(BW))
5887 return false;
5888 } else {
5889 // Check that the expression overall uses at most the same number of bits as
5890 // ZExted
5891 KnownBits KB = computeKnownBits(&I, *DL);
5892 if (KB.countMaxActiveBits() > BW)
5893 return false;
5894 }
5895
5896 // Calculate costs of leaving current IR as it is and moving ZExt operation
5897 // later, along with adding truncates if needed
5899 Instruction::ZExt, BigTy, SmallTy,
5900 TargetTransformInfo::CastContextHint::None, CostKind);
5901 InstructionCost CurrentCost = ZExtCost;
5902 InstructionCost ShrinkCost = 0;
5903
5904 // Calculate total cost and check that we can propagate through all ZExt users
5905 for (User *U : ZExtOperand->users()) {
5906 auto *UI = cast<Instruction>(U);
5907 if (UI == &I) {
5908 CurrentCost +=
5909 TTI.getArithmeticInstrCost(UI->getOpcode(), BigTy, CostKind);
5910 ShrinkCost +=
5911 TTI.getArithmeticInstrCost(UI->getOpcode(), SmallTy, CostKind);
5912 ShrinkCost += ZExtCost;
5913 continue;
5914 }
5915
5916 if (!Instruction::isBinaryOp(UI->getOpcode()))
5917 return false;
5918
5919 // Check if we can propagate ZExt through its other users
5920 KnownBits KB = computeKnownBits(UI, *DL);
5921 if (KB.countMaxActiveBits() > BW)
5922 return false;
5923
5924 CurrentCost += TTI.getArithmeticInstrCost(UI->getOpcode(), BigTy, CostKind);
5925 ShrinkCost +=
5926 TTI.getArithmeticInstrCost(UI->getOpcode(), SmallTy, CostKind);
5927 ShrinkCost += ZExtCost;
5928 }
5929
5930 // If the other instruction operand is not a constant, we'll need to
5931 // generate a truncate instruction. So we have to adjust cost
5932 if (!isa<Constant>(OtherOperand))
5933 ShrinkCost += TTI.getCastInstrCost(
5934 Instruction::Trunc, SmallTy, BigTy,
5935 TargetTransformInfo::CastContextHint::None, CostKind);
5936
5937 // If the cost of shrinking types and leaving the IR is the same, we'll lean
5938 // towards modifying the IR because shrinking opens opportunities for other
5939 // shrinking optimisations.
5940 if (ShrinkCost > CurrentCost)
5941 return false;
5942
5943 Builder.SetInsertPoint(&I);
5944 Value *Op0 = ZExted;
5945 Value *Op1 = Builder.CreateTrunc(OtherOperand, SmallTy);
5946 // Keep the order of operands the same
5947 if (I.getOperand(0) == OtherOperand)
5948 std::swap(Op0, Op1);
5949 Value *NewBinOp =
5950 Builder.CreateBinOp((Instruction::BinaryOps)I.getOpcode(), Op0, Op1);
5951 if (auto *NewBinOpI = dyn_cast<Instruction>(NewBinOp)) {
5952 NewBinOpI->copyIRFlags(&I);
5953 NewBinOpI->copyMetadata(I);
5954 }
5955 Value *NewZExtr = Builder.CreateZExt(NewBinOp, BigTy);
5956 replaceValue(I, *NewZExtr);
5957 return true;
5958}
5959
5960/// insert (DstVec, (extract SrcVec, ExtIdx), InsIdx) -->
5961/// shuffle (DstVec, SrcVec, Mask)
5962bool VectorCombine::foldInsExtVectorToShuffle(Instruction &I) {
5963 Value *DstVec, *SrcVec;
5964 uint64_t ExtIdx, InsIdx;
5965 if (!match(&I,
5966 m_InsertElt(m_Value(DstVec),
5967 m_ExtractElt(m_Value(SrcVec), m_ConstantInt(ExtIdx)),
5968 m_ConstantInt(InsIdx))))
5969 return false;
5970
5971 auto *DstVecTy = dyn_cast<FixedVectorType>(I.getType());
5972 auto *SrcVecTy = dyn_cast<FixedVectorType>(SrcVec->getType());
5973 // We can try combining vectors with different element sizes.
5974 if (!DstVecTy || !SrcVecTy ||
5975 SrcVecTy->getElementType() != DstVecTy->getElementType())
5976 return false;
5977
5978 unsigned NumDstElts = DstVecTy->getNumElements();
5979 unsigned NumSrcElts = SrcVecTy->getNumElements();
5980 if (InsIdx >= NumDstElts || ExtIdx >= NumSrcElts || NumDstElts == 1)
5981 return false;
5982
5983 // Insertion into poison is a cheaper single operand shuffle.
5985 SmallVector<int> Mask(NumDstElts, PoisonMaskElem);
5986
5987 bool NeedExpOrNarrow = NumSrcElts != NumDstElts;
5988 bool NeedDstSrcSwap = isa<PoisonValue>(DstVec) && !isa<UndefValue>(SrcVec);
5989 if (NeedDstSrcSwap) {
5991 Mask[InsIdx] = ExtIdx % NumDstElts;
5992 std::swap(DstVec, SrcVec);
5993 } else {
5995 std::iota(Mask.begin(), Mask.end(), 0);
5996 Mask[InsIdx] = (ExtIdx % NumDstElts) + NumDstElts;
5997 }
5998
5999 // Cost
6000 auto *Ins = cast<InsertElementInst>(&I);
6001 auto *Ext = cast<ExtractElementInst>(I.getOperand(1));
6002 InstructionCost InsCost =
6003 TTI.getVectorInstrCost(*Ins, DstVecTy, CostKind, InsIdx);
6004 InstructionCost ExtCost =
6005 TTI.getVectorInstrCost(*Ext, DstVecTy, CostKind, ExtIdx);
6006 InstructionCost OldCost = ExtCost + InsCost;
6007
6008 InstructionCost NewCost = 0;
6009 SmallVector<int> ExtToVecMask;
6010 if (!NeedExpOrNarrow) {
6011 // Ignore 'free' identity insertion shuffle.
6012 // TODO: getShuffleCost should return TCC_Free for Identity shuffles.
6013 if (!ShuffleVectorInst::isIdentityMask(Mask, NumSrcElts))
6014 NewCost += TTI.getShuffleCost(SK, DstVecTy, DstVecTy, CostKind, Mask, 0,
6015 nullptr, {DstVec, SrcVec});
6016 } else {
6017 // When creating a length-changing-vector, always try to keep the relevant
6018 // element in an equivalent position, so that bulk shuffles are more likely
6019 // to be useful.
6020 ExtToVecMask.assign(NumDstElts, PoisonMaskElem);
6021 ExtToVecMask[ExtIdx % NumDstElts] = ExtIdx;
6022 // Add cost for expanding or narrowing
6024 DstVecTy, SrcVecTy, CostKind, ExtToVecMask);
6025 NewCost += TTI.getShuffleCost(SK, DstVecTy, DstVecTy, CostKind, Mask);
6026 }
6027
6028 if (!Ext->hasOneUse())
6029 NewCost += ExtCost;
6030
6031 LLVM_DEBUG(dbgs() << "Found a insert/extract shuffle-like pair: " << I
6032 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
6033 << "\n");
6034
6035 if (OldCost < NewCost)
6036 return false;
6037
6038 if (NeedExpOrNarrow) {
6039 if (!NeedDstSrcSwap)
6040 SrcVec = Builder.CreateShuffleVector(SrcVec, ExtToVecMask);
6041 else
6042 DstVec = Builder.CreateShuffleVector(DstVec, ExtToVecMask);
6043 }
6044
6045 // Canonicalize undef param to RHS to help further folds.
6046 if (isa<UndefValue>(DstVec) && !isa<UndefValue>(SrcVec)) {
6047 ShuffleVectorInst::commuteShuffleMask(Mask, NumDstElts);
6048 std::swap(DstVec, SrcVec);
6049 }
6050
6051 Value *Shuf = Builder.CreateShuffleVector(DstVec, SrcVec, Mask);
6052 replaceValue(I, *Shuf);
6053
6054 return true;
6055}
6056
6057/// Try to replace a chain of insertelements of parts of the same scalar with a
6058/// bitcast and a shuffle (little endian):
6059/// insert (insert poison, (trunc (lshr X, 32)), 0), (trunc X), 1 -->
6060/// shuffle (bitcast X to <2 x i32>), poison, <1, 0>
6061bool VectorCombine::foldInsertScalarPartsToShuffle(Instruction &I) {
6062 auto *VecTy = dyn_cast<FixedVectorType>(I.getType());
6063 if (!VecTy)
6064 return false;
6065
6066 // Start from the last insertelement of the chain.
6067 if (I.hasOneUse() && isa<InsertElementInst>(I.user_back()))
6068 return false;
6069
6070 Type *EltTy = VecTy->getElementType();
6071 if ((!EltTy->isIntegerTy() && !EltTy->isIEEELikeFPTy()) ||
6072 !DL->typeSizeEqualsStoreSize(EltTy))
6073 return false;
6074 unsigned EltBits = EltTy->getPrimitiveSizeInBits();
6075 unsigned NumElts = VecTy->getNumElements();
6076
6077 Value *Src = nullptr;
6078 unsigned NumSrcElts = 0;
6079 SmallVector<int> Mask(NumElts, PoisonMaskElem);
6080 APInt DemandedElts = APInt::getZero(NumElts);
6081 InstructionCost OldCost = 0;
6082 Value *Vec = &I;
6083 while (auto *Ins = dyn_cast<InsertElementInst>(Vec)) {
6084 if (Ins != &I && !Ins->hasOneUse())
6085 return false;
6086 uint64_t Idx;
6087 if (!match(Ins->getOperand(2), m_ConstantInt(Idx)) || Idx >= NumElts)
6088 return false;
6089 Vec = Ins->getOperand(0);
6090 // A later insert to the same element overrides this one.
6091 if (DemandedElts[Idx])
6092 continue;
6093 DemandedElts.setBit(Idx);
6094
6095 // Match (bitcast (trunc (lshr X, ShAmt))), the bitcast and shift being
6096 // optional.
6097 Value *Elt = Ins->getOperand(1);
6098 Value *Trunc = Elt;
6100 Value *X;
6101 if (!match(Trunc, m_Trunc(m_Value(X))) || !X->getType()->isIntegerTy() ||
6102 Trunc->getType()->getPrimitiveSizeInBits() != EltBits)
6103 return false;
6104 Value *Shift = nullptr;
6105 uint64_t ShAmt = 0;
6106 if (match(X, m_LShr(m_Value(), m_ConstantInt(ShAmt)))) {
6107 Shift = X;
6108 X = cast<Instruction>(Shift)->getOperand(0);
6109 }
6110
6111 if (!Src) {
6112 unsigned SrcBits = X->getType()->getIntegerBitWidth();
6113 if (SrcBits % EltBits)
6114 return false;
6115 Src = X;
6116 NumSrcElts = SrcBits / EltBits;
6117 } else if (X != Src) {
6118 return false;
6119 }
6120 uint64_t Part = ShAmt / EltBits;
6121 if (ShAmt % EltBits || Part >= NumSrcElts)
6122 return false;
6123 Mask[Idx] = DL->isBigEndian() ? NumSrcElts - 1 - Part : Part;
6124
6125 // The scalar ops die with the chain if it is their only user.
6126 for (Value *V : {Elt == Trunc ? nullptr : Elt, Trunc, Shift}) {
6127 if (!V)
6128 continue;
6129 if (!V->hasOneUse())
6130 break;
6131 OldCost += TTI.getInstructionCost(cast<Instruction>(V), CostKind);
6132 }
6133 }
6134 // Elements that are not inserted become poison, so the base must be poison
6135 // unless every element is inserted.
6136 if (!Src || (!isa<PoisonValue>(Vec) && !DemandedElts.isAllOnes()))
6137 return false;
6138 // Inserting a single part is a scalar insert or a splat, whose canonical
6139 // insertelement (+ splat shuffle) form is better left alone.
6140 if (all_equal(
6141 make_filter_range(Mask, [](int M) { return M != PoisonMaskElem; })))
6142 return false;
6143
6144 OldCost += TTI.getScalarizationOverhead(VecTy, DemandedElts, /*Insert=*/true,
6145 /*Extract=*/false, CostKind);
6146
6147 auto *SrcVecTy = FixedVectorType::get(EltTy, NumSrcElts);
6148 InstructionCost NewCost =
6149 TTI.getCastInstrCost(Instruction::BitCast, SrcVecTy, Src->getType(),
6150 TTI::CastContextHint::None, CostKind);
6151 bool IsIdentity = NumSrcElts == NumElts &&
6152 ShuffleVectorInst::isIdentityMask(Mask, NumSrcElts);
6153 if (!IsIdentity)
6154 NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, VecTy, SrcVecTy,
6155 CostKind, Mask);
6156
6157 LLVM_DEBUG(dbgs() << "Found an insertelement chain of scalar parts: " << I
6158 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
6159 << "\n");
6160 if (!OldCost.isValid() || !NewCost.isValid() || NewCost >= OldCost)
6161 return false;
6162
6163 Value *Cast = Builder.CreateBitCast(Src, SrcVecTy);
6164 Value *Shuf = IsIdentity ? Cast : Builder.CreateShuffleVector(Cast, Mask);
6165 replaceValue(I, *Shuf);
6166 return true;
6167}
6168
6169/// Return the number of data operands of \p Inst.
6170static unsigned getNumDataOperands(const Instruction *Inst) {
6171 if (auto *CB = dyn_cast<CallBase>(Inst))
6172 return CB->arg_size(); // Exclude callee operand and bundles.
6173 return Inst->getNumOperands();
6174}
6175
6176/// Return true if \p Inst is an elementwise operation that can be rebuilt at a
6177/// wider element count.
6179 auto *ResultTy = dyn_cast<VectorType>(Inst->getType());
6180 if (!ResultTy || !isSafeToSpeculativelyExecute(Inst))
6181 return false;
6182
6183 if (auto *II = dyn_cast<IntrinsicInst>(Inst)) {
6184 if (II->hasOperandBundles() ||
6185 !isTriviallyVectorizable(II->getIntrinsicID()))
6186 return false;
6188 FreezeInst>(Inst)) {
6189 return false;
6190 }
6191
6192 // Reject operations that change the element-count.
6193 // E.g., bitcast <vscale x 4 x i16> %v to <vscale x 8 x i8>
6194 for (unsigned Op = 0, E = getNumDataOperands(Inst); Op != E; ++Op) {
6195 auto *OperandTy = dyn_cast<VectorType>(Inst->getOperand(Op)->getType());
6196 if (OperandTy &&
6197 OperandTy->getElementCount() != ResultTy->getElementCount())
6198 return false;
6199 }
6200
6201 return true;
6202}
6203
6204/// Return the common splat value of \p Values.
6206 auto GetSplatOrScalar = [](Value *V) {
6207 return isa<VectorType>(V->getType()) ? getSplatValue(V) : V;
6208 };
6209
6210 Value *CommonValue = GetSplatOrScalar(Values.front());
6211 if (!CommonValue)
6212 return nullptr;
6213 for (Value *V : Values.drop_front())
6214 if (GetSplatOrScalar(V) != CommonValue)
6215 return nullptr;
6216 return CommonValue;
6217}
6218
6219/// Return the common deinterleave intrinsic if \p Members are its extracts in
6220/// field order.
6222 IntrinsicInst *Deinterleave = nullptr;
6223 for (const auto &[Index, Member] : enumerate(Members)) {
6224 auto *Extract = dyn_cast<ExtractValueInst>(Member);
6225 if (!Extract || Extract->getNumIndices() != 1 ||
6226 *Extract->idx_begin() != Index)
6227 return nullptr;
6228
6229 auto *Current = dyn_cast<IntrinsicInst>(Extract->getAggregateOperand());
6230 if (!Current || (Deinterleave && Current != Deinterleave))
6231 return nullptr;
6232 Deinterleave = Current;
6233 }
6234 unsigned Factor = Members.size();
6235 if (Deinterleave->hasOperandBundles() ||
6236 getDeinterleaveIntrinsicFactor(Deinterleave->getIntrinsicID()) !=
6237 Factor ||
6238 !Deinterleave->hasNUndroppableUses(Factor))
6239 return nullptr;
6240 return Deinterleave;
6241}
6242
6243/// Return the operand at \p OperandIndex of each \p Members.
6245 unsigned OperandIndex) {
6247 for (Value *Member : Members)
6248 Operands.push_back(cast<Instruction>(Member)->getOperand(OperandIndex));
6249 return Operands;
6250}
6251
6252/// Check whether the tree of elementwise operations each feeding \p Members
6253/// can be rebuilt at the interleaved width.
6255 const VectorizeOptions &Opts, ArrayRef<Value *> Members,
6256 DenseSet<Value *> &Visited, SmallPtrSetImpl<User *> &UndroppableUsers) {
6257 unsigned Factor = Members.size();
6258 if (getCommonDeinterleavedSource(Members))
6259 return true;
6260
6261 if (all_of(Members, [&](Value *V) { return Visited.count(V); }))
6262 return true;
6263
6264 if (Visited.size() + Factor > Opts.vector_combine_max_scan_instrs)
6265 return false;
6266
6267 auto addUndroppableUsers = [&](Value *V) {
6268 for (User *U : V->users()) {
6269 if (U->isDroppable())
6270 continue;
6271 UndroppableUsers.insert(U);
6272 }
6273 };
6274
6275 auto *FirstInst = dyn_cast<Instruction>(Members.front());
6276 if (!FirstInst || !isSupportedElementwise(FirstInst))
6277 return false;
6278 if (Visited.insert(FirstInst).second && !FirstInst->getSingleUndroppableUse())
6279 addUndroppableUsers(FirstInst);
6280
6281 for (Value *Member : Members.drop_front()) {
6282 auto *Inst = dyn_cast<Instruction>(Member);
6283 if (!Inst ||
6284 !FirstInst->isSameOperationAs(Inst, Instruction::CompareCallTargets))
6285 return false;
6286 if (Visited.insert(Inst).second && !Inst->getSingleUndroppableUse())
6287 addUndroppableUsers(Inst);
6288 }
6289
6290 // Scalars operands should be equal among all members.
6291 // Vector operands should be a common splat value or can be widened.
6292 for (unsigned Op = 0, E = getNumDataOperands(FirstInst); Op != E; ++Op) {
6296 UndroppableUsers))
6297 return false;
6298 }
6299 return true;
6300}
6301
6303 ArrayRef<Value *> NewOperands,
6304 VectorType *WideResultTy,
6305 IRBuilderBase &Builder) {
6306 if (isa<BinaryOperator, UnaryOperator>(NarrowInst))
6307 return Builder.CreateNAryOp(NarrowInst->getOpcode(), NewOperands);
6308 if (auto *Cast = dyn_cast<CastInst>(NarrowInst))
6309 return Builder.CreateCast(Cast->getOpcode(), NewOperands[0], WideResultTy);
6310 if (auto *Cmp = dyn_cast<CmpInst>(NarrowInst))
6311 return Builder.CreateCmp(Cmp->getPredicate(), NewOperands[0],
6312 NewOperands[1]);
6313 if (isa<SelectInst>(NarrowInst))
6314 return Builder.CreateSelect(
6315 NewOperands[0], NewOperands[1], NewOperands[2], /*Name=*/"",
6316 ProfcheckDisableMetadataFixes ? nullptr : NarrowInst);
6317 if (isa<FreezeInst>(NarrowInst))
6318 return Builder.CreateFreeze(NewOperands[0]);
6319 if (auto *II = dyn_cast<IntrinsicInst>(NarrowInst))
6320 return Builder.CreateIntrinsic(WideResultTy, II->getIntrinsicID(),
6321 NewOperands);
6322 llvm_unreachable("Unsupported instruction");
6323}
6324
6326 const SmallVector<Value *, 8> &Members, ElementCount WideEC,
6327 IRBuilderBase &Builder,
6328 DenseMap<SmallVector<Value *, 8>, Value *> &WideValueCache) {
6329 if (Value *WideValue = WideValueCache.lookup(Members))
6330 return WideValue;
6331
6332 if (auto *Deinterleave = getCommonDeinterleavedSource(Members)) {
6333 Value *Source = Deinterleave->getArgOperand(0);
6334 assert(cast<VectorType>(Source->getType())->getElementCount() == WideEC &&
6335 "deinterleave source must have the interleaved element count");
6336 WideValueCache[Members] = Source;
6337 return Source;
6338 }
6339
6340 auto *NarrowInst = cast<Instruction>(Members.front());
6341 unsigned NumOperands = getNumDataOperands(NarrowInst);
6342 SmallVector<Value *, 4> NewOperands;
6343 NewOperands.reserve(NumOperands);
6344 for (unsigned Op = 0; Op != NumOperands; ++Op) {
6346 Value *NewOperand = nullptr;
6347 if ((NewOperand = getCommonSplatValue(Operands))) {
6348 if (isa<VectorType>(Operands.front()->getType())) {
6349 Builder.SetCurrentDebugLocation(NarrowInst->getDebugLoc());
6350 NewOperand = Builder.CreateVectorSplat(WideEC, NewOperand);
6351 } else {
6352 assert(all_equal(Operands) && "expected all operands to be equal");
6353 }
6354 } else {
6355 NewOperand = widenDeinterleavedOperations(Operands, WideEC, Builder,
6356 WideValueCache);
6357 }
6358 NewOperands.push_back(NewOperand);
6359 }
6360
6361 Builder.SetCurrentDebugLocation(NarrowInst->getDebugLoc());
6362 auto *WideResultTy =
6363 VectorType::get(NarrowInst->getType()->getScalarType(), WideEC);
6364 Value *NewValue =
6365 createWideInstruction(NarrowInst, NewOperands, WideResultTy, Builder);
6366 if (auto *NewInst = dyn_cast<Instruction>(NewValue)) {
6367 propagateIRFlags(NewInst, Members);
6368 propagateMetadata(NewInst, Members);
6369 }
6370 WideValueCache[Members] = NewValue;
6371 return NewValue;
6372}
6373
6374/// Fold away vector.deinterleave/interleave intrinsics with matching trees of
6375/// elementwise operations between them.
6376///
6377/// For example:
6378/// ```
6379/// %d = call { <2 x i16>, <2 x i16> } @deinterleave2.v4i16(<4 x i16> %v)
6380/// %f0 = extractvalue { <2 x i16>, <2 x i16> } %d, 0
6381/// %f1 = extractvalue { <2 x i16>, <2 x i16> } %d, 1
6382///
6383/// %u0 = add <2 x i16> %f0, splat (i16 3)
6384/// %u1 = add <2 x i16> %f1, splat (i16 3)
6385///
6386/// %r = call <4 x i16> @interleave2.v4i16(<2 x i16> %u0, <2 x i16> %u1)
6387/// ```
6388/// Folds to:
6389/// ```
6390/// %r = add <4 x i16> %v, splat (i16 3)
6391/// ```
6392/// And with two sources:
6393/// ```
6394/// %da = call { <2 x i16>, <2 x i16> } @deinterleave2.v4i16(<4 x i16> %a)
6395/// %a0 = extractvalue { <2 x i16>, <2 x i16> } %da, 0
6396/// %a1 = extractvalue { <2 x i16>, <2 x i16> } %da, 1
6397/// %db = call { <2 x i16>, <2 x i16> } @deinterleave2.v4i16(<4 x i16> %b)
6398/// %b0 = extractvalue { <2 x i16>, <2 x i16> } %db, 0
6399/// %b1 = extractvalue { <2 x i16>, <2 x i16> } %db, 1
6400///
6401/// %m0 = mul <2 x i16> %a0, %b0
6402/// %m1 = mul <2 x i16> %a1, %b1
6403///
6404/// %r = call <4 x i16> @interleave2.v4i16(<2 x i16> %m0, <2 x i16> %m1)
6405/// ```
6406/// Folds to:
6407/// ```
6408/// %r = mul <4 x i16> %a, %b
6409/// ```
6410bool VectorCombine::foldInterleaveOfDeinterleaveChains(Instruction &I) {
6411 auto *Interleave = dyn_cast<IntrinsicInst>(&I);
6412 if (!Interleave)
6413 return false;
6414
6415 unsigned Factor = getInterleaveIntrinsicFactor(Interleave->getIntrinsicID());
6416 if (!Factor || Interleave->hasOperandBundles())
6417 return false;
6418
6419 SmallVector<Value *, 8> RootMembers(Interleave->args());
6420 SmallPtrSet<User *, 4> UndroppableUsers;
6421 DenseSet<Value *> Visited;
6422 if (!canWidenDeinterleavedOperations(Opts, RootMembers, Visited,
6423 UndroppableUsers))
6424 return false;
6425 // Every users should be in the tree.
6426 if (!set_is_subset(UndroppableUsers, Visited))
6427 return false;
6428
6429 ElementCount WideEC = cast<VectorType>(I.getType())->getElementCount();
6430 Builder.SetInsertPoint(Interleave);
6431 // Mapping from members to the new wide value. This avoids emitting redundant
6432 // instructions when a new operand value has more than one use.
6433 DenseMap<SmallVector<Value *, 8>, Value *> WideValueCache;
6434 Value *WideValue = widenDeinterleavedOperations(RootMembers, WideEC, Builder,
6435 WideValueCache);
6436 assert(WideValue->getType() == Interleave->getType());
6437 replaceValue(*Interleave, *WideValue);
6438 return true;
6439}
6440
6441/// If we're interleaving 2 constant splats, for instance `<vscale x 8 x i32>
6442/// <splat of 666>` and `<vscale x 8 x i32> <splat of 777>`, we can create a
6443/// larger splat `<vscale x 8 x i64> <splat of ((777 << 32) | 666)>` first
6444/// before casting it back into `<vscale x 16 x i32>`.
6445bool VectorCombine::foldInterleaveIntrinsics(Instruction &I) {
6446 if (foldInterleaveOfDeinterleaveChains(I))
6447 return true;
6448
6449 const APInt *SplatVal0, *SplatVal1;
6451 m_APInt(SplatVal0), m_APInt(SplatVal1))))
6452 return false;
6453
6454 LLVM_DEBUG(dbgs() << "VC: Folding interleave2 with two splats: " << I
6455 << "\n");
6456
6457 auto *VTy =
6458 cast<VectorType>(cast<IntrinsicInst>(I).getArgOperand(0)->getType());
6459 auto *ExtVTy = VectorType::getExtendedElementVectorType(VTy);
6460 unsigned Width = VTy->getElementType()->getIntegerBitWidth();
6461
6462 // Just in case the cost of interleave2 intrinsic and bitcast are both
6463 // invalid, in which case we want to bail out, we use <= rather
6464 // than < here. Even they both have valid and equal costs, it's probably
6465 // not a good idea to emit a high-cost constant splat.
6466 if (TTI.getInstructionCost(&I, CostKind) <=
6467 TTI.getCastInstrCost(Instruction::BitCast, I.getType(), ExtVTy,
6468 TTI::CastContextHint::None, CostKind)) {
6469 LLVM_DEBUG(dbgs() << "VC: The cost to cast from " << *ExtVTy << " to "
6470 << *I.getType() << " is too high.\n");
6471 return false;
6472 }
6473
6474 // The bitcast puts element 0 of the narrow vector in the low half of each
6475 // wide element on little-endian targets, and in the high half on big-endian
6476 // targets.
6477 const APInt &LowHalf = DL->isLittleEndian() ? *SplatVal0 : *SplatVal1;
6478 const APInt &HighHalf = DL->isLittleEndian() ? *SplatVal1 : *SplatVal0;
6479 APInt NewSplatVal = HighHalf.zext(Width * 2);
6480 NewSplatVal <<= Width;
6481 NewSplatVal |= LowHalf.zext(Width * 2);
6482 auto *NewSplat = ConstantVector::getSplat(
6483 ExtVTy->getElementCount(), ConstantInt::get(F.getContext(), NewSplatVal));
6484
6485 Builder.SetInsertPoint(&I);
6486 replaceValue(I, *Builder.CreateBitCast(NewSplat, I.getType()));
6487 return true;
6488}
6489
6490/// Given this sequence:
6491/// ```
6492/// %d = llvm.vector.deinterleave2 <vscale x 16 x i32> %v
6493/// %f0 = extractvalue { <vscale x 8 x i32>, <vscale x 8 x i32> } %d, 0
6494/// %f1 = extractvalue { <vscale x 8 x i32>, <vscale x 8 x i32> } %d, 1
6495///
6496/// %low0 = and <vscale x 8 x i32> %f0, splat (i32 65535)
6497/// %low1 = shl <vscale x 8 x i32> %f1, splat (i32 16)
6498/// %merge0 = or disjoint <vscale x 8 x i32> %low0, %low1
6499///
6500/// %high0 = and <vscale x 8 x i32> %f1, splat (i32 -65536)
6501/// %high1 = lshr <vscale x 8 x i32> %f0, splat (i32 16)
6502/// %merge1 = or disjoint <vscale x 8 x i32> %high0, %high1
6503/// ```
6504/// It is actually just de-interleaving a 16-bit vector with double the
6505/// vector length. More generally speaking, it's de-interleaving on a vector
6506/// with half the element width as the original vector.
6507///
6508/// Therefore, we can turn it into:
6509/// ```
6510/// %narrow.v = bitcast <vscale x 16 x i32> %v to <vscale x 32 x i16>
6511/// %d = llvm.vector.deinterleave2 <vscale x 32 x i16> %narrow.v
6512/// %f0 = extractvalue { <vscale x 16 x i16>, <vscale x 16 x i16> } %d, 0
6513/// %f1 = extractvalue { <vscale x 16 x i16>, <vscale x 16 x i16> } %d, 1
6514///
6515/// %merge0 = bitcast <vscale x 16 x i16> %f0 to <vscale x 8 x i32>
6516/// %merge1 = bitcast <vscale x 16 x i16> %f1 to <vscale x 8 x i32>
6517/// ```
6518bool VectorCombine::foldDeinterleaveIntrinsics(Instruction &I) {
6519 using namespace PatternMatch;
6520 Value *DeinterleavedVal;
6521 if (!match(&I, m_Deinterleave2(m_Value(DeinterleavedVal))))
6522 return false;
6523
6524 VectorType *VecTy = cast<VectorType>(DeinterleavedVal->getType());
6525 IntegerType *ElementTy = dyn_cast<IntegerType>(VecTy->getElementType());
6526 if (!ElementTy)
6527 return false;
6528 unsigned ElementWidth = ElementTy->getBitWidth();
6529 if (ElementWidth < 2 || !isPowerOf2_32(ElementWidth))
6530 return false;
6531 unsigned HalfElementWidth = ElementWidth / 2;
6532
6533 if (!I.hasNUses(2))
6534 return false;
6535 std::array<ExtractValueInst *, 2> OrigFields{};
6536 for (User *Usr : I.users()) {
6537 auto *E = dyn_cast<ExtractValueInst>(Usr);
6538 // The deinterleave result can only be used by extractions.
6539 if (!E || E->getNumIndices() != 1)
6540 return false;
6541 unsigned Idx = *E->idx_begin();
6542 // A single field cannot be extracted more than once.
6543 if (Idx >= 2 || OrigFields[Idx] || !E->hasNUses(2))
6544 return false;
6545 OrigFields[Idx] = E;
6546 }
6547
6548 if (DL->isBigEndian())
6549 std::swap(OrigFields[0], OrigFields[1]);
6550
6551 // Find the merge instruction (i.e. OR) first.
6552 SmallVector<Instruction *, 2> MergeInsts;
6553 for (auto *FieldUsr : OrigFields[0]->users()) {
6554 if (!FieldUsr->hasOneUse() || !isa<Instruction>(FieldUsr->user_back()))
6555 return false;
6556 MergeInsts.push_back(cast<Instruction>(FieldUsr->user_back()));
6557 }
6558 assert(MergeInsts.size() == 2);
6559
6560 // Pattern match bottom-up from the merge instructions.
6561 auto MatchMerge = [&](void) -> bool {
6562 APInt LoMask = APInt::getLowBitsSet(ElementWidth, HalfElementWidth);
6563 APInt HiMask = APInt::getHighBitsSet(ElementWidth, HalfElementWidth);
6564 return match(MergeInsts[0],
6565 m_c_Or(m_And(m_Specific(OrigFields[0]), m_SpecificInt(LoMask)),
6566 m_Shl(m_Specific(OrigFields[1]),
6567 m_SpecificInt(HalfElementWidth)))) &&
6568 match(MergeInsts[1],
6569 m_c_Or(m_And(m_Specific(OrigFields[1]), m_SpecificInt(HiMask)),
6570 m_LShr(m_Specific(OrigFields[0]),
6571 m_SpecificInt(HalfElementWidth))));
6572 };
6573 if (!MatchMerge()) {
6574 std::swap(MergeInsts[0], MergeInsts[1]);
6575 if (!MatchMerge())
6576 return false;
6577 }
6578
6579 // Profitability check.
6580 InstructionCost OldCost =
6581 TTI.getInstructionCost(MergeInsts[0], CostKind) +
6582 TTI.getInstructionCost(cast<Instruction>(MergeInsts[0]->getOperand(0)),
6583 CostKind) +
6584 TTI.getInstructionCost(cast<Instruction>(MergeInsts[0]->getOperand(1)),
6585 CostKind);
6586 // There are two fields (assuming SHL has the same cost as LSHR).
6587 OldCost *= 2;
6588
6589 auto *NewFieldTy = VecTy->getWithNewBitWidth(HalfElementWidth);
6590 auto *NewVecTy =
6591 VectorType::getDoubleElementsVectorType(cast<VectorType>(NewFieldTy));
6592 InstructionCost NewCost =
6593 TTI.getCastInstrCost(Instruction::BitCast, VecTy, NewVecTy,
6594 TTI::CastContextHint::None, CostKind) +
6595 TTI.getCastInstrCost(Instruction::BitCast, NewFieldTy,
6596 MergeInsts[0]->getType(), TTI::CastContextHint::None,
6597 CostKind) *
6598 2;
6599 if (OldCost <= NewCost || !NewCost.isValid()) {
6600 LLVM_DEBUG(
6601 dbgs() << "VC: New deinterleave2 sequence cost (" << NewCost << ")"
6602 << " is higher than that of the old one (" << OldCost << ")\n");
6603 return false;
6604 }
6605
6606 // Do the replacement.
6607 Builder.SetInsertPoint(&I);
6608 Value *NewVecCast = Builder.CreateBitCast(DeinterleavedVal, NewVecTy);
6609 Value *NewDeinterleave = Builder.CreateIntrinsic(
6610 Intrinsic::vector_deinterleave2, {NewVecTy}, {NewVecCast});
6611 for (auto [Idx, MergeInst] : enumerate(MergeInsts)) {
6612 if (DL->isBigEndian())
6613 Idx ^= 1;
6614 Value *NewField = Builder.CreateExtractValue(NewDeinterleave, Idx);
6615 NewField = Builder.CreateBitCast(NewField, MergeInst->getType());
6616 replaceValue(*MergeInst, *NewField);
6617 }
6618
6619 return true;
6620}
6621
6622bool VectorCombine::foldBitcastOfVPLoad(Instruction &I) {
6623 const DataLayout &DL = I.getDataLayout();
6624 auto *Cast = dyn_cast<CastInst>(&I);
6625 if (!Cast || !Cast->isNoopCast(DL) || !isa<VectorType>(Cast->getDestTy()))
6626 return false;
6627
6628 // Fold away bit casts of the loaded value by loading the desired type,
6629 // if the mask is all-ones.
6630 Value *EVL;
6631 auto *II = dyn_cast<VPIntrinsic>(I.getOperand(0));
6633 m_Value(), m_AllOnes(), m_Value(EVL)))))
6634 return false;
6635
6636 VectorType *OrigVecTy = cast<VectorType>(II->getType());
6637 Align OrigAlign =
6638 DL.getValueOrABITypeAlignment(II->getPointerAlignment(), OrigVecTy);
6639 ElementCount OrigVecCnt = OrigVecTy->getElementCount();
6640 VectorType *NewVecTy = cast<VectorType>(Cast->getDestTy());
6641 ElementCount NewVecCnt = NewVecTy->getElementCount();
6642
6643 // Right now we only support cases where the NewVec is longer, because for
6644 // cases where it's shorter, we have to be sure that EVL can be exactly
6645 // divided, otherwise it might yield incorrect results or even page faults
6646 // (if we round-up during the division).
6647 if (!(OrigVecCnt.isScalable() == NewVecCnt.isScalable() &&
6648 NewVecCnt.hasKnownScalarFactor(OrigVecCnt)))
6649 return false;
6650
6651 InstructionCost OldCost =
6652 TTI.getMemIntrinsicInstrCost({Intrinsic::vp_load, OrigVecTy,
6653 II->getMemoryPointerParam(), false,
6654 OrigAlign},
6655 CostKind) +
6656 TTI.getCastInstrCost(Instruction::BitCast, Cast->getType(), OrigVecTy,
6657 TTI::CastContextHint::None, CostKind);
6659 {Intrinsic::vp_load, NewVecTy, II->getMemoryPointerParam(), false,
6660 OrigAlign},
6661 CostKind);
6662 LLVM_DEBUG(dbgs() << "foldBitcastOfVPLoad: OldCost=" << OldCost
6663 << " NewCost=" << NewCost << "\n");
6664 if (NewCost > OldCost || !NewCost.isValid())
6665 return false;
6666
6667 Builder.SetInsertPoint(II);
6668 unsigned Factor = NewVecCnt.getKnownScalarFactor(OrigVecCnt);
6669 Value *NewEVL = Builder.CreateNUWMul(EVL, Builder.getInt32(Factor));
6670 Value *NewMask = Builder.CreateVectorSplat(NewVecCnt, Builder.getTrue());
6671 CallInst *NewVP = Builder.CreateIntrinsicWithoutFolding(
6672 NewVecTy, Intrinsic::vp_load,
6673 {II->getMemoryPointerParam(), NewMask, NewEVL});
6674 // Preserve the original alignment.
6675 NewVP->addParamAttrs(
6676 0, AttrBuilder(II->getContext()).addAlignmentAttr(OrigAlign));
6677 replaceValue(*Cast, *NewVP);
6678 return true;
6679}
6680/// Fold the following cases into a single byte-level bit-reverse operation
6681/// and accepts bswap and bitreverse intrinsics:
6682/// bswap(bitreverse(x)) --> bitcast(bitreverse(bitcast(x)))
6683/// bitreverse(bswap(x)) <--> bitcast(bitreverse(bitcast(x)))
6684/// The direction of the fold is cost-model driven.
6685/// Also supports:
6686/// bitcast(bitreverse(bitcast(x))) --> bitreverse(fshl(x))
6687bool VectorCombine::foldBitOrderReverseAndSwap(Instruction &I) {
6688 Value *X;
6689
6691 Type *Ty = X->getType();
6692 Type *VecTy = I.getOperand(0)->getType();
6693 // Detect the case when bitreversing every octet in X individually. Then we
6694 // can use bswap to reorder the octets before doing a single bitreverse.
6695 bool CanUseBswap =
6696 Ty->isIntegerTy() && Ty == I.getType() && isa<FixedVectorType>(VecTy) &&
6697 cast<FixedVectorType>(VecTy)->getElementType()->isIntegerTy(8) &&
6698 Ty->getIntegerBitWidth() % 16 == 0;
6699 // Detect the case when bitreversing upper and lower half of X
6700 // individually. Then we can use fshl as a rotate operation, to swap the
6701 // halves before doing a single bitreverse.
6702 bool CanUseFshl =
6703 Ty->isIntegerTy() && Ty == I.getType() && isa<FixedVectorType>(VecTy) &&
6704 cast<FixedVectorType>(VecTy)->getElementType()->isIntegerTy() &&
6705 cast<FixedVectorType>(VecTy)->getNumElements() == 2;
6706 if (CanUseBswap || CanUseFshl) {
6707 auto *InnerCall = dyn_cast<Instruction>(I.getOperand(0));
6708 if (!InnerCall)
6709 return false;
6710 auto *InnerBitCast = dyn_cast<BitCastInst>(InnerCall->getOperand(0));
6711 if (!InnerBitCast)
6712 return false;
6713 Constant *HalfBW = ConstantInt::get(Ty, Ty->getIntegerBitWidth() / 2);
6714 InstructionCost OldCost = TTI.getInstructionCost(InnerBitCast, CostKind) +
6715 TTI.getInstructionCost(InnerCall, CostKind) +
6716 TTI.getInstructionCost(&I, CostKind);
6717 IntrinsicCostAttributes ICABSwap(Intrinsic::bswap, Ty, {Ty});
6718 IntrinsicCostAttributes ICABFshl(Intrinsic::fshl, Ty, {X, X, HalfBW},
6719 {Ty, Ty, Ty});
6720 IntrinsicCostAttributes ICABRev(Intrinsic::bitreverse, Ty, {Ty});
6721 InstructionCost NewCost =
6722 TTI.getIntrinsicInstrCost(CanUseBswap ? ICABSwap : ICABFshl,
6723 CostKind) +
6724 TTI.getIntrinsicInstrCost(ICABRev, CostKind);
6725 if (!InnerCall->hasOneUse())
6726 NewCost += TTI.getInstructionCost(InnerCall, CostKind) +
6727 TTI.getInstructionCost(InnerBitCast, CostKind);
6728 else if (!InnerBitCast->hasOneUse())
6729 NewCost += TTI.getInstructionCost(InnerBitCast, CostKind);
6730 LLVM_DEBUG(dbgs() << "Found bitreverse vector roundtrip: " << I
6731 << "\n OldCost: " << OldCost
6732 << " vs NewCost: " << NewCost << "\n");
6733 if (NewCost.isValid() && NewCost < OldCost) {
6734 Builder.SetInsertPoint(&I);
6735 Value *Swap =
6736 CanUseBswap
6737 ? Builder.CreateUnaryIntrinsic(Intrinsic::bswap, X)
6738 : Builder.CreateIntrinsic(Ty, Intrinsic::fshl, {X, X, HalfBW});
6739 Value *BRev = Builder.CreateUnaryIntrinsic(Intrinsic::bitreverse, Swap);
6740 replaceValue(I, *BRev);
6741 return true;
6742 }
6743 }
6744 }
6745
6746 if (!match(&I, m_BitReverse(m_BSwap(m_Value(X)))) &&
6748 return false;
6749 Type *Ty = I.getType();
6750 Type *I8Ty = Builder.getInt8Ty();
6751 TypeSize ElementSize = DL->getTypeStoreSize(Ty);
6752 ElementCount NewVecCnt = ElementCount::get(ElementSize.getKnownMinValue(),
6753 ElementSize.isScalable());
6754 Type *NewVecTy = VectorType::get(I8Ty, NewVecCnt);
6755 auto *II = cast<IntrinsicInst>(&I);
6756 auto *InnerII = cast<IntrinsicInst>(II->getArgOperand(0));
6757 // OldCost = cost of bitreverse/bswap + cost of bswap/bitreverse
6758 InstructionCost OldCost = TTI.getInstructionCost(II, CostKind) +
6759 TTI.getInstructionCost(InnerII, CostKind);
6760 // NewCost = cost of bitcast to byte vector +
6761 // cost of bitreverse/bswap on byte vector +
6762 // cost of bitcast back to original type
6763 InstructionCost CastToVecCost = TTI.getCastInstrCost(
6764 Instruction::BitCast, NewVecTy, Ty, TTI::CastContextHint::None, CostKind);
6765 InstructionCost CastToOrigCost = TTI.getCastInstrCost(
6766 Instruction::BitCast, Ty, NewVecTy, TTI::CastContextHint::None, CostKind);
6767 IntrinsicCostAttributes ICANew(Intrinsic::bitreverse, NewVecTy, {NewVecTy});
6768 InstructionCost NewIntrinsicCost =
6769 TTI.getIntrinsicInstrCost(ICANew, CostKind);
6770 InstructionCost NewCost = CastToVecCost + NewIntrinsicCost + CastToOrigCost;
6771 if (!InnerII->hasOneUse())
6772 NewCost += TTI.getInstructionCost(InnerII, CostKind);
6773 LLVM_DEBUG(dbgs() << "Found bitorder reverse and swap: " << I
6774 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
6775 << "\n");
6776 if (!NewCost.isValid() || NewCost >= OldCost)
6777 return false;
6778 // Perform transform: bitcast(arg, <N x i8>), bitreverse, bitcast back
6779 Builder.SetInsertPoint(II);
6780 Value *CastToVec = Builder.CreateBitCast(X, NewVecTy);
6781 Value *NewCall =
6782 Builder.CreateUnaryIntrinsic(Intrinsic::bitreverse, CastToVec);
6783 Value *CastToOrig = Builder.CreateBitCast(NewCall, Ty);
6784 replaceValue(I, *CastToOrig);
6785 return true;
6786}
6787
6788/// Given the maximum shuffle index and load vector type, compute the number of
6789/// elements for the shrunk load, rounding up to the next full vector register
6790/// boundary to avoid scalar remainders that legalize poorly.
6791static unsigned getAlignedNumElements(unsigned MaxIdx, FixedVectorType *LoadTy,
6792 const TargetTransformInfo &TTI,
6793 const DataLayout &DL) {
6794 unsigned RawNumElements = MaxIdx + 1u;
6795 Type *ElemTy = LoadTy->getElementType();
6796 // Skip alignment for illegal element types.
6797 if (!TTI.isTypeLegal(ElemTy))
6798 return RawNumElements;
6799
6800 TypeSize ElemSize = DL.getTypeSizeInBits(ElemTy);
6801 if (ElemSize.isScalable() || ElemSize.isZero())
6802 return RawNumElements;
6803
6806 if (RegSize.isScalable() || RegSize.isZero())
6807 return RawNumElements;
6808
6809 unsigned ElemsPerReg = RegSize.getFixedValue() / ElemSize.getFixedValue();
6810 // If the load already fits in a register, keep the exact size.
6811 // Otherwise round up to the next full register boundary.
6812 if (ElemsPerReg == 0 || RawNumElements <= ElemsPerReg)
6813 return RawNumElements;
6814
6815 return alignTo(RawNumElements, ElemsPerReg);
6816}
6817
6818// Attempt to shrink loads that are only used by shufflevector instructions.
6819bool VectorCombine::shrinkLoadForShuffles(Instruction &I) {
6820 auto *OldLoad = dyn_cast<LoadInst>(&I);
6821 if (!OldLoad || !OldLoad->isSimple())
6822 return false;
6823
6824 auto *OldLoadTy = dyn_cast<FixedVectorType>(OldLoad->getType());
6825 if (!OldLoadTy)
6826 return false;
6827
6828 unsigned const OldNumElements = OldLoadTy->getNumElements();
6829
6830 // Search all uses of load. If all uses are shufflevector instructions, and
6831 // the second operands are all poison values, find the minimum and maximum
6832 // indices of the vector elements referenced by all shuffle masks.
6833 // Otherwise return `std::nullopt`.
6834 using IndexRange = std::pair<int, int>;
6835 auto GetIndexRangeInShuffles = [&]() -> std::optional<IndexRange> {
6836 IndexRange OutputRange = IndexRange(OldNumElements, -1);
6837 for (llvm::Use &Use : I.uses()) {
6838 // Ensure all uses match the required pattern.
6839 User *Shuffle = Use.getUser();
6840 ArrayRef<int> Mask;
6841
6842 if (!match(Shuffle,
6843 m_Shuffle(m_Specific(OldLoad), m_Undef(), m_Mask(Mask))))
6844 return std::nullopt;
6845
6846 // Ignore shufflevector instructions that have no uses.
6847 if (Shuffle->use_empty())
6848 continue;
6849
6850 // Find the min and max indices used by the shufflevector instruction.
6851 for (int Index : Mask) {
6852 if (Index >= 0 && Index < static_cast<int>(OldNumElements)) {
6853 OutputRange.first = std::min(Index, OutputRange.first);
6854 OutputRange.second = std::max(Index, OutputRange.second);
6855 }
6856 }
6857 }
6858
6859 if (OutputRange.second < OutputRange.first)
6860 return std::nullopt;
6861
6862 return OutputRange;
6863 };
6864
6865 // Get the range of vector elements used by shufflevector instructions.
6866 if (std::optional<IndexRange> Indices = GetIndexRangeInShuffles()) {
6867 unsigned const NewNumElements =
6868 getAlignedNumElements(Indices->second, OldLoadTy, TTI, *DL);
6869
6870 // If the range of vector elements is smaller than the full load, attempt
6871 // to create a smaller load.
6872 if (NewNumElements < OldNumElements) {
6873 Builder.SetInsertPoint(&I);
6874 Builder.SetCurrentDebugLocation(I.getDebugLoc());
6875
6876 // Calculate costs of old and new ops.
6877 Type *ElemTy = OldLoadTy->getElementType();
6878 FixedVectorType *NewLoadTy = FixedVectorType::get(ElemTy, NewNumElements);
6879 Value *PtrOp = OldLoad->getPointerOperand();
6880
6882 Instruction::Load, OldLoad->getType(), OldLoad->getAlign(),
6883 OldLoad->getPointerAddressSpace(), CostKind);
6884 InstructionCost NewCost =
6885 TTI.getMemoryOpCost(Instruction::Load, NewLoadTy, OldLoad->getAlign(),
6886 OldLoad->getPointerAddressSpace(), CostKind);
6887
6888 using UseEntry = std::pair<ShuffleVectorInst *, std::vector<int>>;
6890 unsigned const MaxIndex = NewNumElements * 2u;
6891
6892 for (llvm::Use &Use : I.uses()) {
6893 auto *Shuffle = cast<ShuffleVectorInst>(Use.getUser());
6894
6895 // Ignore shufflevector instructions that have no uses.
6896 if (Shuffle->use_empty())
6897 continue;
6898
6899 ArrayRef<int> OldMask = Shuffle->getShuffleMask();
6900
6901 // Create entry for new use.
6902 NewUses.push_back({Shuffle, OldMask});
6903
6904 // Validate mask indices.
6905 for (int Index : OldMask) {
6906 if (Index >= static_cast<int>(MaxIndex))
6907 return false;
6908 }
6909
6910 // Update costs.
6911 OldCost +=
6913 OldLoadTy, CostKind, OldMask);
6914 NewCost +=
6916 NewLoadTy, CostKind, OldMask);
6917 }
6918
6919 LLVM_DEBUG(
6920 dbgs() << "Found a load used only by shufflevector instructions: "
6921 << I << "\n OldCost: " << OldCost
6922 << " vs NewCost: " << NewCost << "\n");
6923
6924 if (OldCost < NewCost || !NewCost.isValid())
6925 return false;
6926
6927 // Create new load of smaller vector.
6928 auto *NewLoad = cast<LoadInst>(
6929 Builder.CreateAlignedLoad(NewLoadTy, PtrOp, OldLoad->getAlign()));
6930 NewLoad->copyMetadata(I);
6931
6932 // Replace all uses.
6933 for (UseEntry &Use : NewUses) {
6934 ShuffleVectorInst *Shuffle = Use.first;
6935 std::vector<int> &NewMask = Use.second;
6936
6937 Builder.SetInsertPoint(Shuffle);
6938 Builder.SetCurrentDebugLocation(Shuffle->getDebugLoc());
6939 Value *NewShuffle = Builder.CreateShuffleVector(
6940 NewLoad, PoisonValue::get(NewLoadTy), NewMask);
6941
6942 replaceValue(*Shuffle, *NewShuffle, false);
6943 }
6944
6945 return true;
6946 }
6947 }
6948 return false;
6949}
6950
6951// Attempt to combine two adjacent fixed-length vector loads, that only feed
6952// shufflevector instructions, into a single wider load, rewriting every such
6953// shuffle so that operand 0 is the wide load and operand 1 is poison.
6954// clang-format off
6955// e.g.
6956// %loadA = load <16 x i8>, ptr %a
6957// %gep = getelementptr inbounds <16 x i8>, ptr %a, i64 1
6958// %loadB = load <16 x i8>, ptr %gep
6959// %shuffle0 = shufflevector <16 x i8> %loadA, <16 x i8> %loadB,
6960// <32 x i8> <...>
6961// %shuffle1 = shufflevector <16 x i8> %loadA, <16 x i8> %loadB,
6962// <32 x i8> <...>
6963//
6964// The fold would transform this to:
6965// %loadAB = load <32 x i8>, ptr %a
6966// %shuffle0 = shufflevector <32 x i8> %loadAB, <32 x i8> poison,
6967// <32 x i8> <...>
6968// %shuffle1 = shufflevector <32 x i8> %loadAB, <32 x i8> poison,
6969// <32 x i8> <...>
6970//
6971// clang-format on
6972// Matching this pattern in codegen becomes difficult and hence, we prefer doing
6973// this here.
6974bool VectorCombine::foldShuffleOfAdjacentLoads(Instruction &I) {
6975 auto *SV = cast<ShuffleVectorInst>(&I);
6976
6977 // The two operands must be distinct loads of the same fixed vector type.
6978 auto *Load0 = dyn_cast<LoadInst>(SV->getOperand(0));
6979 auto *Load1 = dyn_cast<LoadInst>(SV->getOperand(1));
6980 if (!Load0 || !Load1 || Load0 == Load1 || !Load0->isSimple() ||
6981 !Load1->isSimple())
6982 return false;
6983
6984 // Confirm both loads are of fixed vector type.
6985 auto *LoadTy = dyn_cast<FixedVectorType>(Load0->getType());
6986 if (!LoadTy)
6987 return false;
6988
6989 // We restrict to loads occurring in the same BB for now.
6990 if (Load0->getParent() != Load1->getParent())
6991 return false;
6992
6993 if (Load0->getPointerAddressSpace() != Load1->getPointerAddressSpace())
6994 return false;
6995
6996 // Check that the original load type has no padding bits otherwise the wide
6997 // load would be incorrect.
6998 if (DL->getTypeSizeInBits(LoadTy) != 8 * DL->getTypeStoreSize(LoadTy))
6999 return false;
7000
7001 const unsigned NumElts = LoadTy->getNumElements();
7002 // Avoid overflow/wraparound issues.
7003 if (NumElts > INT_MAX / 2)
7004 return false;
7005
7006 // Determine which load is at the lower address and confirm the two loads are
7007 // exactly contiguous: both pointers must strip to the same base, and their
7008 // constant offsets from it must differ by exactly the store size of LoadTy.
7009 unsigned AS = Load0->getPointerAddressSpace();
7010 unsigned IdxWidth = DL->getIndexSizeInBits(AS);
7011 APInt Offset0(IdxWidth, 0), Offset1(IdxWidth, 0);
7012 const Value *Base0 =
7013 Load0->getPointerOperand()->stripAndAccumulateConstantOffsets(
7014 *DL, Offset0, /*AllowNonInbounds=*/true);
7015 const Value *Base1 =
7016 Load1->getPointerOperand()->stripAndAccumulateConstantOffsets(
7017 *DL, Offset1, /*AllowNonInbounds=*/true);
7018 // Offsets accumulated across an addrspacecast are not comparable.
7019 if (Base0 != Base1 || Base0->getType()->getPointerAddressSpace() != AS)
7020 return false;
7021
7022 int64_t LoadSize = DL->getTypeStoreSize(LoadTy).getFixedValue();
7023 std::optional<int64_t> Dist = (Offset1 - Offset0).trySExtValue();
7024 LoadInst *LowLoad, *HighLoad;
7025 if (Dist == LoadSize) {
7026 LowLoad = Load0;
7027 HighLoad = Load1;
7028 } else if (Dist == -LoadSize) {
7029 LowLoad = Load1;
7030 HighLoad = Load0;
7031 } else {
7032 return false;
7033 }
7034
7035 // 1. Check all users of both loads are shuffles.
7036 // 2. Check that both loads feed exactly the same set of shuffles.
7037 SmallPtrSet<ShuffleVectorInst *, 4> Shuffles;
7038 if (!std::is_permutation(LowLoad->user_begin(), LowLoad->user_end(),
7039 HighLoad->user_begin(), HighLoad->user_end()) ||
7040 !all_of(LowLoad->users(), [&Shuffles](User *U) {
7041 if (auto *SVI = dyn_cast<ShuffleVectorInst>(U)) {
7042 Shuffles.insert(SVI);
7043 return true;
7044 }
7045 return false;
7046 }))
7047 return false;
7048
7049 // The value loaded by either load must not be clobbered in between the loads.
7050 auto *WideTy = FixedVectorType::get(LoadTy->getElementType(), NumElts * 2);
7051 LoadInst *FirstLoad = LowLoad, *LastLoad = HighLoad;
7052 if (HighLoad->comesBefore(LowLoad))
7053 std::swap(FirstLoad, LastLoad);
7054 MemoryLocation FirstLoc = MemoryLocation::get(FirstLoad);
7055 if (isMemModifiedBetween(Opts, std::next(FirstLoad->getIterator()),
7056 LastLoad->getIterator(), FirstLoc, AA))
7057 return false;
7058
7059 // case 1: wide load = LowLoad + HighLoad ,
7060 // shuffle 0th operand = LowLoad
7061 // shuffle 1st operand = HighLoad
7062 // Implication with this is shuffle mask for the wide load remains unchanged
7063 // case 2: wide load = LowLoad + HighLoad ,
7064 // shuffle 0th operand = HighLoad
7065 // shuffle 1st operand = LowLoad
7066 // Implication with this is shuffle mask for the wide load changes
7067 auto RemapMask = [&](ShuffleVectorInst *SV, SmallVectorImpl<int> &NewMask) {
7068 Value *SVOp0 = SV->getOperand(0);
7069 assert(((SVOp0 == LowLoad && SV->getOperand(1) == HighLoad) ||
7070 (SVOp0 == HighLoad && SV->getOperand(1) == LowLoad)) &&
7071 "Shuffle operands must be exactly {LowLoad, HighLoad} or {HighLoad, "
7072 "LowLoad}");
7073 SV->getShuffleMask(NewMask);
7074 if (SVOp0 == HighLoad)
7075 ShuffleVectorInst::commuteShuffleMask(NewMask, NumElts);
7076 };
7077
7078 // Cost model checks
7079 Value *Poison = PoisonValue::get(WideTy);
7080 InstructionCost OldCost =
7081 TTI.getMemoryOpCost(Instruction::Load, LoadTy, LowLoad->getAlign(),
7082 LowLoad->getPointerAddressSpace(), CostKind);
7083 OldCost +=
7084 TTI.getMemoryOpCost(Instruction::Load, LoadTy, HighLoad->getAlign(),
7085 HighLoad->getPointerAddressSpace(), CostKind);
7086 InstructionCost NewCost =
7087 TTI.getMemoryOpCost(Instruction::Load, WideTy, LowLoad->getAlign(),
7088 LowLoad->getPointerAddressSpace(), CostKind);
7089 for (ShuffleVectorInst *SV : Shuffles) {
7090 OldCost += TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, SV->getType(), LoadTy,
7091 CostKind, SV->getShuffleMask());
7092 SmallVector<int, 32> NewMask;
7093 RemapMask(SV, NewMask);
7094 // LoadSz = initial load size
7095 // WideSz = 2 * LoadSz
7096 // MaxMaskSize = WideSz * 2
7097 // Check if MaxMaskSize fits within an integer range.
7098 if (!ShuffleVectorInst::isValidOperands(Poison, Poison, NewMask))
7099 return false;
7100 NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, SV->getType(),
7101 WideTy, CostKind, NewMask);
7102 }
7103
7104 LLVM_DEBUG(dbgs() << "Found adjacent loads feeding shuffles: " << *LowLoad
7105 << ", " << *HighLoad << "\n OldCost: " << OldCost
7106 << " vs NewCost: " << NewCost << "\n");
7107
7108 if (!NewCost.isValid() || NewCost > OldCost)
7109 return false;
7110
7111 // Insert the wide load at whichever original load comes last, so that both
7112 // halves of the contiguous range are known to be dereferenceable there.
7113 LoadInst *InsertPt = LastLoad;
7114
7115 // Build the wide load at the insertion point using the low load's pointer and
7116 // alignment, intersecting alias metadata from both original loads.
7117 Builder.SetInsertPoint(InsertPt);
7118 Builder.SetCurrentDebugLocation(InsertPt->getDebugLoc());
7119 LoadInst *WideLoad = Builder.CreateAlignedLoad(
7120 WideTy, LowLoad->getPointerOperand(), LowLoad->getAlign());
7121
7122 // Set the metadata on the wide load. copyMetadataForLoad seeds it from
7123 // LowLoad, then combineMetadataForCSE intersects every known kind against
7124 // HighLoad (taking the most-generic value where applicable, keeping facts
7125 // only where both loads agree, and dropping unknown metadata), so nothing is
7126 // asserted over the combined load unless justified by both halves.
7127 copyMetadataForLoad(*WideLoad, *LowLoad);
7128 combineMetadataForCSE(WideLoad, HighLoad, /*DoesKMove=*/true);
7129
7130 for (ShuffleVectorInst *SV : Shuffles) {
7131 SmallVector<int, 32> NewMask;
7132 RemapMask(SV, NewMask);
7133
7134 Builder.SetInsertPoint(SV);
7135 Builder.SetCurrentDebugLocation(SV->getDebugLoc());
7136 Value *NewShuf = Builder.CreateShuffleVector(WideLoad, Poison, NewMask);
7137 // We do not want to erase shuffles immediately because they may invalidate
7138 // the NextInst pointer in the caller's BB traversal.
7139 replaceValue(*SV, *NewShuf, /*Erase=*/false);
7140 }
7141 return true;
7142}
7143
7144// Attempt to narrow a phi of shufflevector instructions where the two incoming
7145// values have the same operands but different masks. If the two shuffle masks
7146// are offsets of one another we can use one branch to rotate the incoming
7147// vector and perform one larger shuffle after the phi.
7148bool VectorCombine::shrinkPhiOfShuffles(Instruction &I) {
7149 auto *Phi = dyn_cast<PHINode>(&I);
7150 if (!Phi || Phi->getNumIncomingValues() != 2u)
7151 return false;
7152
7153 Value *Op = nullptr;
7154 ArrayRef<int> Mask0;
7155 ArrayRef<int> Mask1;
7156
7157 if (!match(Phi->getOperand(0u),
7158 m_OneUse(m_Shuffle(m_Value(Op), m_Poison(), m_Mask(Mask0)))) ||
7159 !match(Phi->getOperand(1u),
7160 m_OneUse(m_Shuffle(m_Specific(Op), m_Poison(), m_Mask(Mask1)))))
7161 return false;
7162
7163 auto *Shuf = cast<ShuffleVectorInst>(Phi->getOperand(0u));
7164
7165 // Ensure result vectors are wider than the argument vector.
7166 auto *InputVT = cast<FixedVectorType>(Op->getType());
7167 auto *ResultVT = cast<FixedVectorType>(Shuf->getType());
7168 auto const InputNumElements = InputVT->getNumElements();
7169
7170 if (InputNumElements >= ResultVT->getNumElements())
7171 return false;
7172
7173 // Take the difference of the two shuffle masks at each index. Ignore poison
7174 // values at the same index in both masks.
7175 SmallVector<int, 16> NewMask;
7176 NewMask.reserve(Mask0.size());
7177
7178 auto IsPoison = [InputNumElements](int M) {
7179 return M < 0 || (unsigned)M >= InputNumElements;
7180 };
7181
7182 for (auto [M0, M1] : zip(Mask0, Mask1)) {
7183 bool P0 = IsPoison(M0);
7184 bool P1 = IsPoison(M1);
7185 if (!P0 && !P1)
7186 NewMask.push_back(M0 - M1);
7187 else if (P0 && P1)
7188 continue;
7189 else
7190 return false;
7191 }
7192
7193 // Ensure all elements of the new mask are equal. If the difference between
7194 // the incoming mask elements is the same, the two must be constant offsets
7195 // of one another.
7196 if (NewMask.empty() || !all_equal(NewMask))
7197 return false;
7198
7199 // Create new mask using difference of the two incoming masks.
7200 int MaskOffset = NewMask[0u];
7201 unsigned Index = (InputNumElements + MaskOffset) % InputNumElements;
7202 NewMask.clear();
7203
7204 for (unsigned I = 0u; I < InputNumElements; ++I) {
7205 NewMask.push_back(Index);
7206 Index = (Index + 1u) % InputNumElements;
7207 }
7208
7209 // Calculate costs for worst cases and compare.
7210 auto const Kind = TTI::SK_PermuteSingleSrc;
7211 auto OldCost =
7212 std::max(TTI.getShuffleCost(Kind, ResultVT, InputVT, CostKind, Mask0),
7213 TTI.getShuffleCost(Kind, ResultVT, InputVT, CostKind, Mask1));
7214 auto NewCost = TTI.getShuffleCost(Kind, InputVT, InputVT, CostKind, NewMask) +
7215 TTI.getShuffleCost(Kind, ResultVT, InputVT, CostKind, Mask1);
7216
7217 LLVM_DEBUG(dbgs() << "Found a phi of mergeable shuffles: " << I
7218 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
7219 << "\n");
7220
7221 if (NewCost > OldCost)
7222 return false;
7223
7224 // Create new shuffles and narrowed phi.
7225 Builder.SetInsertPoint(Shuf);
7226 Builder.SetCurrentDebugLocation(Shuf->getDebugLoc());
7227 auto *PoisonVal = PoisonValue::get(InputVT);
7228 auto *NewShuf0 = Builder.CreateShuffleVector(Op, PoisonVal, NewMask);
7229
7230 Builder.SetInsertPoint(Phi);
7231 Builder.SetCurrentDebugLocation(Phi->getDebugLoc());
7232 auto *NewPhi = Builder.CreatePHI(NewShuf0->getType(), 2u);
7233 NewPhi->addIncoming(NewShuf0, Phi->getIncomingBlock(0u));
7234 NewPhi->addIncoming(Op, Phi->getIncomingBlock(1u));
7235
7236 Builder.SetInsertPoint(*NewPhi->getInsertionPointAfterDef());
7237 PoisonVal = PoisonValue::get(NewPhi->getType());
7238 auto *NewShuf1 = Builder.CreateShuffleVector(NewPhi, PoisonVal, Mask1);
7239
7240 replaceValue(*Phi, *NewShuf1);
7241 return true;
7242}
7243
7244/// This is the entry point for all transforms. Pass manager differences are
7245/// handled in the callers of this function.
7246bool VectorCombine::run() {
7247 if (Opts.disable_vector_combine)
7248 return false;
7249
7250 // Don't attempt vectorization if the target does not support vectors.
7251 if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
7252 return false;
7253
7254 LLVM_DEBUG(dbgs() << "\n\nVECTORCOMBINE on " << F.getName() << "\n");
7255
7256 auto FoldInst = [this](Instruction &I) {
7257 Builder.SetInsertPoint(&I);
7258 bool IsVectorType = isa<VectorType>(I.getType());
7259 bool IsFixedVectorType = isa<FixedVectorType>(I.getType());
7260 auto Opcode = I.getOpcode();
7261
7262 LLVM_DEBUG(dbgs() << "VC: Visiting: " << I << '\n');
7263
7264 // These folds should be beneficial regardless of when this pass is run
7265 // in the optimization pipeline.
7266 // The type checking is for run-time efficiency. We can avoid wasting time
7267 // dispatching to folding functions if there's no chance of matching.
7268 if (IsFixedVectorType) {
7269 switch (Opcode) {
7270 case Instruction::InsertElement:
7271 if (vectorizeLoadInsert(I))
7272 return true;
7273 break;
7274 case Instruction::ShuffleVector:
7275 if (widenSubvectorLoad(I))
7276 return true;
7277 break;
7278 default:
7279 break;
7280 }
7281 }
7282
7283 // This transform works with scalable and fixed vectors
7284 // TODO: Identify and allow other scalable transforms
7285 if (IsVectorType) {
7286 if (scalarizeOpOrCmp(I))
7287 return true;
7288 if (scalarizeLoad(I))
7289 return true;
7290 if (scalarizeExtExtract(I))
7291 return true;
7292 if (foldInterleaveIntrinsics(I))
7293 return true;
7294 if (foldBitcastOfVPLoad(I))
7295 return true;
7296 }
7297
7298 if (foldDeinterleaveIntrinsics(I))
7299 return true;
7300
7301 if (Opcode == Instruction::Store)
7302 if (foldInsertElementsToStores(I))
7303 return true;
7304
7305 // If this is an early pipeline invocation of this pass, we are done.
7306 if (TryEarlyFoldsOnly)
7307 return false;
7308
7309 if (Opcode == Instruction::Call)
7310 if (foldBitOrderReverseAndSwap(I))
7311 return true;
7312 if (Opcode == Instruction::BitCast)
7313 if (foldBitOrderReverseAndSwap(I))
7314 return true;
7315
7316 // Otherwise, try folds that improve codegen but may interfere with
7317 // early IR canonicalizations.
7318 // The type checking is for run-time efficiency. We can avoid wasting time
7319 // dispatching to folding functions if there's no chance of matching.
7320 if (IsFixedVectorType) {
7321 switch (Opcode) {
7322 case Instruction::InsertElement:
7323 if (foldInsExtFNeg(I))
7324 return true;
7325 if (foldInsExtBinop(I))
7326 return true;
7327 if (foldInsExtVectorToShuffle(I))
7328 return true;
7329 if (foldInsertScalarPartsToShuffle(I))
7330 return true;
7331 break;
7332 case Instruction::ShuffleVector:
7333 if (foldPermuteOfBinops(I))
7334 return true;
7335 if (foldShuffleOfBinops(I))
7336 return true;
7337 if (foldShuffleOfSelects(I))
7338 return true;
7339 if (foldShuffleOfCastops(I))
7340 return true;
7341 if (foldShuffleOfShuffles(I))
7342 return true;
7343 if (foldShuffleOfAdjacentLoads(I))
7344 return true;
7345 if (foldPermuteOfIntrinsic(I))
7346 return true;
7347 if (foldShufflesOfLengthChangingShuffles(I))
7348 return true;
7349 if (foldShuffleOfIntrinsics(I))
7350 return true;
7351 if (foldSelectShuffle(I))
7352 return true;
7353 if (foldShuffleToIdentity(I))
7354 return true;
7355 break;
7356 case Instruction::Load:
7357 if (shrinkLoadForShuffles(I))
7358 return true;
7359 break;
7360 case Instruction::BitCast:
7361 if (foldBitcastShuffle(I))
7362 return true;
7363 if (foldSelectsFromBitcast(I))
7364 return true;
7365 break;
7366 case Instruction::And:
7367 case Instruction::Or:
7368 case Instruction::Xor:
7369 if (foldBitOpOfCastops(I))
7370 return true;
7371 if (foldBitOpOfCastConstant(I))
7372 return true;
7373 break;
7374 case Instruction::PHI:
7375 if (shrinkPhiOfShuffles(I))
7376 return true;
7377 break;
7378 default:
7379 if (shrinkType(I))
7380 return true;
7381 break;
7382 }
7383 } else {
7384 switch (Opcode) {
7385 case Instruction::Call:
7386 if (foldShuffleFromReductions(I))
7387 return true;
7388 if (foldCastFromReductions(I))
7389 return true;
7390 break;
7391 case Instruction::ExtractElement:
7392 if (foldShuffleChainsToReduce(I))
7393 return true;
7394 break;
7395 case Instruction::ICmp:
7396 if (foldSignBitReductionCmp(I))
7397 return true;
7398 if (foldICmpEqZeroVectorReduce(I))
7399 return true;
7400 if (foldReductionZeroTest(I))
7401 return true;
7402 if (foldEquivalentReductionCmp(I))
7403 return true;
7404 if (foldReduceAddCmpZero(I))
7405 return true;
7406 [[fallthrough]];
7407 case Instruction::FCmp:
7408 if (foldExtractExtract(I))
7409 return true;
7410 break;
7411 case Instruction::Or:
7412 if (foldConcatOfBoolMasks(I))
7413 return true;
7414 [[fallthrough]];
7415 default:
7416 if (Instruction::isBinaryOp(Opcode)) {
7417 if (foldExtractExtract(I))
7418 return true;
7419 if (foldExtractedCmps(I))
7420 return true;
7421 if (foldBinopOfReductions(I))
7422 return true;
7423 }
7424 break;
7425 }
7426 }
7427 return false;
7428 };
7429
7430 bool MadeChange = false;
7431 for (BasicBlock &BB : F) {
7432 // Ignore unreachable basic blocks.
7433 if (!DT.isReachableFromEntry(&BB))
7434 continue;
7435 // Use early increment range so that we can erase instructions in loop.
7436 // make_early_inc_range is not applicable here, as the next iterator may
7437 // be invalidated by RecursivelyDeleteTriviallyDeadInstructions.
7438 // We manually maintain the next instruction and update it when it is about
7439 // to be deleted.
7440 Instruction *I = &BB.front();
7441 while (I) {
7442 NextInst = I->getNextNode();
7443 MadeChange |= FoldInst(*I);
7444 I = NextInst;
7445 }
7446 }
7447
7448 NextInst = nullptr;
7449
7450 while (!Worklist.isEmpty()) {
7451 // Push deferred instructions in reverse order, so that they'll end up
7452 // popped from the worklist in-order.
7453 while (Instruction *I = Worklist.popDeferred()) {
7456 continue;
7457 }
7458
7459 Worklist.push(I);
7460 }
7461
7462 Instruction *I = Worklist.removeOne();
7463 if (!I)
7464 continue;
7465
7468 continue;
7469 }
7470
7471 MadeChange |= FoldInst(*I);
7472 }
7473
7474 return MadeChange;
7475}
7476
7479 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
7481 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F);
7482 AAResults &AA = FAM.getResult<AAManager>(F);
7483 const DataLayout *DL = &F.getDataLayout();
7484 TTI::TargetCostKind CostKind =
7486 VectorCombine Combiner(getVectorizeOptions(F), F, TTI, DT, AA, AC, DL,
7487 CostKind, TryEarlyFoldsOnly);
7488 if (!Combiner.run())
7489 return PreservedAnalyses::all();
7492 return PA;
7493}
SDValue Pred
unsigned RegSize
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static const Function * getParent(const Value *V)
This is the interface for LLVM's primary stateless and local alias analysis.
#define X(NUM, ENUM, NAME)
Definition ELF.h:665
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
This file defines the DenseMap class.
#define Check(C,...)
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
iv users
Definition IVUsers.cpp:48
const size_t AbstractManglingParser< Derived, Alloc >::NumOps
const AbstractManglingParser< Derived, Alloc >::OperatorInfo AbstractManglingParser< Derived, Alloc >::Ops[]
static void eraseInstruction(Instruction &I, const LICMDependencies &Deps)
Definition LICM.cpp:1173
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T1
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
if(PassOpts->AAPipeline)
This file contains the declarations for profiling metadata utility functions.
SmallVector< MachineOperand, 4 > Cond
int64_t C1
int64_t C0
SI Fold Operands
This file contains some templates that are useful if you are working with the STL at all.
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This file defines generic set operations that may be used on set's of different types,...
This file defines the SmallVector class.
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:171
#define LLVM_DEBUG(...)
Definition Debug.h:119
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SymbolRef::Type getType(const Symbol *Sym)
Definition TapiFile.cpp:39
This pass exposes codegen information to IR-level passes.
static bool isEquivBitcast(Value *X, Value *Y)
Helper to peek through bitcasts to the same value.
static SmallVector< Value *, 8 > getInstrOperandsAtIdx(ArrayRef< Value * > Members, unsigned OperandIndex)
Return the operand at OperandIndex of each Members.
static bool isFreeConcat(ArrayRef< InstLane > Item, TTI::TargetCostKind CostKind, const TargetTransformInfo &TTI)
Detect concat of multiple values into a vector.
static void analyzeCostOfVecReduction(const IntrinsicInst &II, TTI::TargetCostKind CostKind, const TargetTransformInfo &TTI, InstructionCost &CostBeforeReduction, InstructionCost &CostAfterReduction)
static Value * generateNewInstTree(ArrayRef< InstLane > Item, Use *From, const DenseSet< std::pair< Value *, Use * > > &IdentityLeafs, const DenseSet< std::pair< Value *, Use * > > &SplatLeafs, const DenseSet< std::pair< Value *, Use * > > &ConcatLeafs, IRBuilderBase &Builder, InstructionWorklist &WorkList, const TargetTransformInfo *TTI)
static SmallVector< InstLane > generateInstLaneVectorFromOperand(ArrayRef< InstLane > Item, int Op)
static Value * createShiftShuffle(Value *Vec, unsigned OldIndex, unsigned NewIndex, IRBuilderBase &Builder)
Create a shuffle that translates (shifts) 1 element from the input vector to a new element location.
std::pair< Value *, int > InstLane
static Value * createWideInstruction(Instruction *NarrowInst, ArrayRef< Value * > NewOperands, VectorType *WideResultTy, IRBuilderBase &Builder)
static unsigned getNumDataOperands(const Instruction *Inst)
Return the number of data operands of Inst.
static bool isKnownNonPositive(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Used by foldReduceAddCmpZero to check if we can prove that a value is non-positive.
static bool isSupportedElementwise(Instruction *Inst)
Return true if Inst is an elementwise operation that can be rebuilt at a wider element count.
static Value * materializeScalarizedGEPIndex(Value *Idx, IntegerType *GEPIndexTy, IRBuilderBase &Builder)
Materialize an index for a scalarized GEP after profitability is known.
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 bool feedsIntoVectorReduction(ShuffleVectorInst *SVI)
Returns true if this ShuffleVectorInst eventually feeds into a vector reduction intrinsic (e....
static bool canWidenLoad(LoadInst *Load, const TargetTransformInfo &TTI)
static const unsigned InvalidIndex
static Value * getCommonSplatValue(ArrayRef< Value * > Values)
Return the common splat value of Values.
static IntegerType * getScalarizedGEPIndexInfo(VectorType *VecTy, Value *Idx, Type *PtrTy, const DataLayout &DL)
Return the GEP index type if the unsigned vector index Idx can be represented by an inbounds GEP.
static Value * translateExtract(ExtractElementInst *ExtElt, unsigned NewIndex, IRBuilderBase &Builder)
Given an extract element instruction with constant index operand, shuffle the source vector (shift th...
static ScalarizationResult canScalarizeAccess(VectorType *VecTy, Value *Idx, const SimplifyQuery &SQ)
Check if it is legal to scalarize a memory access to VecTy at index Idx.
static bool canWidenDeinterleavedOperations(const VectorizeOptions &Opts, ArrayRef< Value * > Members, DenseSet< Value * > &Visited, SmallPtrSetImpl< User * > &UndroppableUsers)
Check whether the tree of elementwise operations each feeding Members can be rebuilt at the interleav...
static unsigned getAlignedNumElements(unsigned MaxIdx, FixedVectorType *LoadTy, const TargetTransformInfo &TTI, const DataLayout &DL)
Given the maximum shuffle index and load vector type, compute the number of elements for the shrunk l...
static InstLane lookThroughShuffles(Value *V, int Lane)
static IntrinsicInst * getCommonDeinterleavedSource(ArrayRef< Value * > Members)
Return the common deinterleave intrinsic if Members are its extracts in field order.
static bool isMemModifiedBetween(const VectorizeOptions &Opts, BasicBlock::iterator Begin, BasicBlock::iterator End, const MemoryLocation &Loc, AAResults &AA)
static Value * widenDeinterleavedOperations(const SmallVector< Value *, 8 > &Members, ElementCount WideEC, IRBuilderBase &Builder, DenseMap< SmallVector< Value *, 8 >, Value * > &WideValueCache)
static constexpr int Concat[]
Value * RHS
Value * LHS
A manager for alias analyses.
Class for arbitrary precision integers.
Definition APInt.h:78
LLVM_ABI APInt zext(unsigned width) const
Zero extend to a new width.
Definition APInt.cpp:1057
uint64_t getZExtValue() const
Get zero extended value.
Definition APInt.h:1560
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1350
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:367
bool ugt(const APInt &RHS) const
Unsigned greater than comparison.
Definition APInt.h:1186
bool isZero() const
Determine if this value is zero, i.e. all bits are clear.
Definition APInt.h:376
unsigned getBitWidth() const
Return the number of bits in the APInt.
Definition APInt.h:1508
static APInt getSignedMaxValue(unsigned numBits)
Gets maximum signed value of APInt for a specific bit width.
Definition APInt.h:205
bool isNegative() const
Determine sign of this APInt.
Definition APInt.h:325
unsigned countl_one() const
Count the number of leading one bits.
Definition APInt.h:1635
LLVM_ABI APInt sext(unsigned width) const
Sign extend to a new width.
Definition APInt.cpp:1030
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:302
static APInt getHighBitsSet(unsigned numBits, unsigned hiBitsSet)
Constructs an APInt value that has the top hiBitsSet bits set.
Definition APInt.h:292
static APInt getZero(unsigned numBits)
Get the '0' value for the specified bit-width.
Definition APInt.h:196
bool isOne() const
Determine if this is a value of 1.
Definition APInt.h:385
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition APInt.h:235
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
Definition APInt.h:1225
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
ArrayRef< T > drop_front(size_t N=1) const
Drop the first N elements of the array.
Definition ArrayRef.h:194
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
BinaryOps getOpcode() const
Definition InstrTypes.h:409
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
Value * getArgOperand(unsigned i) const
void addParamAttrs(unsigned ArgNo, const AttrBuilder &B)
Adds attributes to the indicated argument.
This is the base class for all instructions that perform data casts.
Definition InstrTypes.h:512
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition InstrTypes.h:740
bool isFPPredicate() const
Definition InstrTypes.h:845
static LLVM_ABI 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:33
static LLVM_ABI Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
This class represents a range of values.
LLVM_ABI ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
LLVM_ABI 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...
LLVM_ABI bool contains(const APInt &Val) const
Return true if the specified value is in the set.
static LLVM_ABI Constant * getSplat(ElementCount EC, Constant *Elt)
Return a ConstantVector with the specified constant in each element.
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
static LLVM_ABI Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
bool empty() const
Definition DenseMap.h:716
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:856
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Analysis pass which computes a DominatorTree.
Definition Dominators.h:241
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition Dominators.h:122
LLVM_ABI bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
LLVM_ABI bool dominates(const BasicBlock *BB, const Use &U) const
Return true if the (end of the) basic block BB dominates the use U.
static constexpr ElementCount get(ScalarTy MinVal, bool Scalable)
Definition TypeSize.h:312
This instruction extracts a single (scalar) element from a VectorType value.
Convenience struct for specifying and reasoning about fast-math flags.
Definition FMF.h:23
bool noSignedZeros() const
Definition FMF.h:67
Class to represent fixed width SIMD vectors.
unsigned getNumElements() const
static FixedVectorType * getDoubleElementsVectorType(FixedVectorType *VTy)
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:838
This class represents a freeze function that returns random concrete value if an operand is either a ...
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool isEquality() const
Return true if this predicate is either EQ or NE.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:111
LLVM_ABI CallInst * CreateIntrinsicWithoutFolding(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={})
Create a call to intrinsic ID with Args, mangled using OverloadTypes.
Value * CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1471
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2748
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition IRBuilder.h:2736
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition IRBuilder.h:1940
Value * CreateNoWrapBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, bool IsNUW, bool IsNSW, const Twine &Name="")
Definition IRBuilder.h:1750
LLVM_ABI Value * CreateSelectFMF(Value *C, Value *True, Value *False, FMFSource FMFSource, const Twine &Name="", Instruction *MDFrom=nullptr)
LLVM_ABI Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Value * CreateExtractValue(Value *Agg, ArrayRef< unsigned > Idxs, const Twine &Name="")
Definition IRBuilder.h:2795
ConstantInt * getTrue()
Get the constant value for i1 true.
Definition IRBuilder.h:451
LLVM_ABI Value * CreateSelect(Value *C, Value *True, Value *False, const Twine &Name="", Instruction *MDFrom=nullptr)
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition IRBuilder.h:2814
void SetCurrentDebugLocation(const DebugLoc &L)
Set location information used by debugging information.
Definition IRBuilder.h:229
Value * CreateLShr(Value *LHS, Value *RHS, const Twine &Name="", bool isExact=false)
Definition IRBuilder.h:1534
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="", MDNode *FPMathTag=nullptr, FMFSource FMFSource={})
Definition IRBuilder.h:2360
Value * CreateIsNotNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg > -1.
Definition IRBuilder.h:2852
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition IRBuilder.h:2021
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="", bool HasSameSign=false)
Definition IRBuilder.h:2568
Value * CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2385
Value * CreateFCmpFMF(CmpInst::Predicate P, Value *LHS, Value *RHS, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2589
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition IRBuilder.h:476
LLVM_ABI Value * CreateOrReduce(Value *Src)
Create a vector int OR reduction intrinsic of the source vector.
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition IRBuilder.h:471
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:2595
PHINode * CreatePHI(Type *Ty, unsigned NumReservedValues, const Twine &Name="")
Definition IRBuilder.h:2626
InstTy * Insert(InstTy *I, const Twine &Name="") const
Insert and return the specified instruction.
Definition IRBuilder.h:148
Value * CreateBinOpFMF(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1739
Value * CreateIsNeg(Value *Arg, const Twine &Name="")
Return a boolean value testing if Arg < 0.
Definition IRBuilder.h:2847
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition IRBuilder.h:2319
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:1913
Value * CreateUnOpFMF(Instruction::UnaryOps Opc, Value *V, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1866
Value * CreateShl(Value *LHS, Value *RHS, const Twine &Name="", bool HasNUW=false, bool HasNSW=false)
Definition IRBuilder.h:1513
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="", bool IsNonNeg=false)
Definition IRBuilder.h:2197
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition IRBuilder.h:2770
Value * CreateAnd(Value *LHS, Value *RHS, const Twine &Name="")
Definition IRBuilder.h:1572
LLVM_ABI Value * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > OverloadTypes, ArrayRef< Value * > Args, FMFSource FMFSource={}, const Twine &Name="", ArrayRef< OperandBundleDef > OpBundles={}, function_ref< void(CallInst *)> SetFn=[](CallInst *) {})
Variant to create a possibly constant-folded intrinsic.
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition IRBuilder.h:1931
Value * CreateExactBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, bool IsExact, const Twine &Name="")
Definition IRBuilder.h:1762
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="", bool IsNUW=false, bool IsNSW=false)
Definition IRBuilder.h:2183
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition IRBuilder.h:571
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1733
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition IRBuilder.h:197
Value * CreateFNegFMF(Value *V, FMFSource FMFSource, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition IRBuilder.h:1846
Value * CreateOr(Value *LHS, Value *RHS, const Twine &Name="", bool IsDisjoint=false)
Definition IRBuilder.h:1594
IntegerType * getInt8Ty()
Fetch the type representing an 8-bit integer.
Definition IRBuilder.h:518
LLVM_ABI Value * CreateUnaryIntrinsic(Intrinsic::ID ID, Value *Op, FMFSource FMFSource={}, const Twine &Name="")
Create a call to intrinsic ID with 1 operand which is mangled on its type.
Provides an 'InsertHelper' that calls a user-provided callback after performing the default insertion...
Definition IRBuilder.h:74
InstSimplifyFolder - Use InstructionSimplify to fold operations to existing values.
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
InstructionWorklist - This is the worklist management logic for InstCombine and other simplification ...
void push(Instruction *I)
Push the instruction onto the worklist stack.
void remove(Instruction *I)
Remove I from the worklist if it exists.
LLVM_ABI void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
LLVM_ABI void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag.
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
bool isBinaryOp() const
LLVM_ABI void setNonNeg(bool b=true)
Set or clear the nneg flag on this instruction, which must be a zext instruction.
LLVM_ABI bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
iterator_range< user_iterator > users()
LLVM_ABI void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
LLVM_ABI FastMathFlags getFastMathFlags() const LLVM_READONLY
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
user_iterator user_begin()
@ CompareCallTargets
Check for equivalence by comparing call targets.
LLVM_ABI AAMDNodes getAAMetadata() const
Returns the AA metadata for this instruction.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
user_iterator user_end()
bool isIdempotent() const
Return true if the instruction is idempotent:
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
LLVM_ABI bool hasAllowReassoc() const LLVM_READONLY
Determine whether the allow-reassociation flag is set.
bool isIntDivRem() const
Class to represent integer types.
static LLVM_ABI IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
Definition Type.cpp:333
unsigned getBitWidth() const
Get the number of bits in this IntegerType.
A wrapper class for inspecting calls to intrinsic functions.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
An instruction for reading from memory.
unsigned getPointerAddressSpace() const
Returns the address space of the pointer operand.
void setAlignment(Align Align)
Value * getPointerOperand()
Type * getPointerOperandType() const
Align getAlign() const
Return the alignment of the access that is being performed.
Representation for a specific memory location.
static LLVM_ABI MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
Definition Analysis.h:112
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:152
This class represents the LLVM 'select' instruction.
bool contains(const_arg_type key) const
Check if the SetVector contains the given key.
Definition SetVector.h:258
bool empty() const
Determine if the SetVector is empty or not.
Definition SetVector.h:100
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition SetVector.h:157
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.
static LLVM_ABI bool isValidOperands(const Value *V1, const Value *V2, const Value *Mask)
Return true if a shufflevector instruction can be formed with the specified operands.
VectorType * getType() const
Overload to return most specific vector type.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
static LLVM_ABI bool isIdentityMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector without lane crossin...
static void commuteShuffleMask(MutableArrayRef< int > Mask, unsigned InVecNumElts)
Change values in a shuffle permute mask assuming the two vector operands of length InVecNumElts have ...
size_type size() const
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void assign(size_type NumElts, ValueParamT Elt)
reference emplace_back(ArgTypes &&... Args)
void reserve(size_type N)
void append(ItTy in_start, ItTy in_end)
Add the specified range to the end of the SmallVector.
void push_back(const T &Elt)
LLVM_NO_SANITIZE_CFI_UNRELATED_CAST iterator begin()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
void setAlignment(Align Align)
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
static LLVM_ABI CastContextHint getCastContextHint(const Instruction *I)
Calculates a CastContextHint from I.
LLVM_ABI InstructionCost getGEPCost(Type *PointeeType, const Value *Ptr, ArrayRef< const Value * > Operands, TargetCostKind CostKind, Type *AccessType=nullptr) const
Estimate the cost of a GEP operation when lowered.
LLVM_ABI TypeSize getRegisterBitWidth(RegisterKind K) const
LLVM_ABI InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind, OperandValueInfo OpdInfo={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
static LLVM_ABI OperandValueInfo commonOperandInfo(const Value *X, const Value *Y)
Collect common data between two OperandValueInfo inputs.
LLVM_ABI bool allowVectorElementIndexingUsingGEP() const
Returns true if GEP should not be used to index into vectors for this target.
LLVM_ABI InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
LLVM_ABI InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, const Value *Op0=nullptr, const Value *Op1=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
LLVM_ABI InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind, OperandValueInfo Op1Info={OK_AnyValue, OP_None}, OperandValueInfo Op2Info={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
LLVM_ABI InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *DstTy, VectorType *SrcTy, TTI::TargetCostKind CostKind, ArrayRef< int > Mask={}, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
LLVM_ABI InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind, const Instruction *I=nullptr) const
LLVM_ABI unsigned getRegisterClassForType(bool Vector, Type *Ty=nullptr) const
LLVM_ABI InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind) const
Calculate the cost of vector reduction intrinsics.
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
@ TCK_CodeSize
Instruction code size.
LLVM_ABI InstructionCost getMemIntrinsicInstrCost(const MemIntrinsicCostAttributes &MICA, TTI::TargetCostKind CostKind) const
LLVM_ABI InstructionCost getMinMaxReductionCost(Intrinsic::ID IID, VectorType *Ty, FastMathFlags FMF, TTI::TargetCostKind CostKind) const
LLVM_ABI unsigned getMinVectorRegisterBitWidth() const
LLVM_ABI InstructionCost getAddressComputationCost(Type *PtrTy, ScalarEvolution *SE, const SCEV *Ptr, TTI::TargetCostKind CostKind) const
LLVM_ABI unsigned getNumberOfRegisters(unsigned ClassID) const
LLVM_ABI InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args={}, const Instruction *CtxI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
LLVM_ABI InstructionCost getInstructionCost(const User *U, ArrayRef< const Value * > Operands, TargetCostKind CostKind) const
Estimate the cost of a given IR user when lowered.
LLVM_ABI InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind, bool ForPoisonSrc=true, ArrayRef< Value * > VL={}, TTI::VectorInstrContext VIC=TTI::VectorInstrContext::None) const
Estimate the overhead of scalarizing an instruction.
ShuffleKind
The various kinds of shuffle patterns for vector queries.
@ SK_PermuteSingleSrc
Shuffle elements of single source vector with any shuffle mask.
@ SK_PermuteTwoSrc
Merge elements from two source vectors into one with any shuffle mask.
@ SK_ExtractSubvector
ExtractSubvector Index indicates start offset.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
LLVM_ABI unsigned getIntegerBitWidth() const
bool isPointerTy() const
True if this is an instance of PointerType.
Definition Type.h:277
LLVM_ABI unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:370
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:187
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition Type.h:130
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:252
bool isFPOrFPVectorTy() const
Return true if this is a FP type or a vector of FP.
Definition Type.h:222
bool isIEEELikeFPTy() const
Return true if this is a well-behaved IEEE-like type, which has a IEEE compatible layout,...
Definition Type.h:172
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
op_range operands()
Definition User.h:267
Value * getOperand(unsigned i) const
Definition User.h:207
unsigned getNumOperands() const
Definition User.h:229
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:257
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:729
LLVM_ABI bool hasOneUser() const
Return true if there is exactly one user of this value.
Definition Value.cpp:158
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:441
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:548
iterator_range< user_iterator > users()
Definition Value.h:428
LLVM_ABI Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition Value.cpp:985
unsigned getValueID() const
Return an ID for the concrete type of this object.
Definition Value.h:545
LLVM_ABI bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition Value.cpp:142
LLVM_ABI const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition Value.cpp:707
bool use_empty() const
Definition Value.h:348
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:314
bool user_empty() const
Definition Value.h:391
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
Type * getElementType() const
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:210
size_type size() const
Definition DenseSet.h:85
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:188
constexpr bool hasKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns true if there exists a value X where RHS*X will result in a value whose quantity matches our ...
Definition TypeSize.h:266
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr ScalarTy getKnownScalarFactor(const FixedOrScalableQuantity &RHS) const
Returns a value X where RHS*X will result in a value whose quantity matches our own.
Definition TypeSize.h:274
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
constexpr bool isZero() const
Definition TypeSize.h:154
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
Definition ilist_node.h:348
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Abstract Attribute helper functions.
Definition Attributor.h:166
constexpr char Align[]
Key for Kernel::Arg::Metadata::mAlign.
const APInt & smin(const APInt &A, const APInt &B)
Determine the smaller of two APInts considered to be signed.
Definition APInt.h:2274
const APInt & smax(const APInt &A, const APInt &B)
Determine the larger of two APInts considered to be signed.
Definition APInt.h:2279
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.
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:83
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
AllOnesConstantMatch m_AllOnes()
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_and< Ty... > m_CombineAnd(const Ty &...Ps)
Combine pattern matchers matching all of Ps patterns.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
auto m_BSwap(const Opnd0 &Op0)
auto m_Cmp()
Matches any compare instruction and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
auto m_BitReverse(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
auto m_Poison()
Match an arbitrary poison constant.
ap_match< APInt > m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt.
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.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
DisjointOr_match< LHS, RHS > m_DisjointOr(const LHS &L, const RHS &R)
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
CmpClass_match< LHS, RHS, ICmpInst, true > m_c_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
Matches an ICmp with a predicate over LHS and RHS in either order.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
auto m_Value()
Match an arbitrary value and ignore it.
BinaryOp_match< LHS, RHS, Instruction::Mul > m_Mul(const LHS &L, const RHS &R)
auto m_Constant()
Match an arbitrary Constant and ignore it.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
cst_pred_ty< is_non_zero_int > m_NonZeroInt()
Match a non-zero integer or a vector with all non-zero elements.
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Shl, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWShl(const LHS &L, const RHS &R)
auto m_AnyIntrinsic()
Matches any intrinsic call and ignore it.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Mul, OverflowingBinaryOperator::NoUnsignedWrap > m_NUWMul(const LHS &L, const RHS &R)
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
BinOpPred_match< LHS, RHS, is_bitwiselogic_op, true > m_c_BitwiseLogic(const LHS &L, const RHS &R)
Matches bitwise logic operations in either order.
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".
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_Deinterleave2(const Opnd &Op)
FNeg_match< OpTy, true > m_FNegOrFSubNegZero(const OpTy &X)
Match fneg X or fsub -0.0, X.
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
CmpClass_match< LHS, RHS, ICmpInst > m_ICmp(CmpPredicate &Pred, const LHS &L, const RHS &R)
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
auto m_Undef()
Match an arbitrary undef constant.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
BinaryOp_match< LHS, RHS, Instruction::Or, true > m_c_Or(const LHS &L, const RHS &R)
Matches an Or with LHS and RHS in either order.
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.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
@ Valid
The data is already valid.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
NodeAddr< PhiNode * > Phi
Definition RDFGraph.h:390
NodeAddr< UseNode * > Use
Definition RDFGraph.h:385
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
Definition STLExtras.h:316
unsigned Log2_32_Ceil(uint32_t Value)
Return the ceil log base 2 of the specified value, 32 if the value is zero.
Definition MathExtras.h:339
@ Offset
Definition DWP.cpp:577
detail::zippy< detail::zip_shortest, T, U, Args... > zip(T &&t, U &&u, Args &&...args)
zip iterator for two or more iteratable types.
Definition STLExtras.h:846
void stable_sort(R &&Range)
Definition STLExtras.h:2132
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
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:1748
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicOp(Intrinsic::ID RdxID)
Returns the min/max intrinsic used when expanding a min/max reduction.
LLVM_ABI bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr, std::function< void(Value *)> AboutToDeleteCallback=std::function< void(Value *)>())
If the specified value is a trivially dead instruction, delete it.
Definition Local.cpp:522
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
LLVM_ABI SDValue peekThroughBitcasts(SDValue V)
Return the non-bitcasted source operand of V if it exists.
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2575
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI Value * simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q)
Given operand for a UnaryOperator, fold the result or return null.
scope_exit(Callable) -> scope_exit< Callable >
@ Load
The value being inserted comes from a load (InsertElement only).
LLVM_ABI void copyMetadataForLoad(LoadInst &Dest, const LoadInst &Source)
Copy the metadata from the source instruction to the destination (the replacement for the source inst...
Definition Local.cpp:3195
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool set_is_subset(const S1Ty &S1, const S2Ty &S2)
set_is_subset(A, B) - Return true iff A in B
LLVM_ABI unsigned getArithmeticReductionInstruction(Intrinsic::ID RdxID)
Returns the arithmetic instruction opcode used when expanding a reduction.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2229
constexpr bool isUIntN(unsigned N, uint64_t x)
Checks if an unsigned integer fits into the given (dynamic) bit width.
Definition MathExtras.h:244
LLVM_ABI Value * simplifyCall(CallBase *Call, Value *Callee, ArrayRef< Value * > Args, const SimplifyQuery &Q)
Given a callsite, callee, and arguments, fold the result or return null.
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:649
LLVM_ABI void computeKnownBits(const Value *V, KnownBits &Known, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Determine which bits of V are known to be either zero or one and return them in the KnownZero/KnownOn...
LLVM_ABI 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:452
LLVM_ABI 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...
LLVM_ABI bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr, bool UseVariableInfo=true, bool IgnoreUBImplyingAttrs=true)
Return true if the instruction does not have any effects besides calculating the result and does not ...
LLVM_ABI Instruction * propagateMetadata(Instruction *I, ArrayRef< Value * > VL)
Propagate metadata that can be preserved after vectorization from VL to I, retaining only information...
LLVM_ABI Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
LLVM_ABI unsigned ComputeNumSignBits(const Value *Op, const DataLayout &DL, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true, unsigned Depth=0)
Return the number of times the sign bit of the register is replicated into the other bits.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
unsigned M1(unsigned Val)
Definition VE.h:394
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1762
LLVM_ABI 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:408
LLVM_ABI 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...
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
Definition MathExtras.h:326
auto reverse(ContainerTy &&C)
Definition STLExtras.h:408
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
bool isModSet(const ModRefInfo MRI)
Definition ModRef.h:49
void sort(IteratorTy Start, IteratorTy End)
Definition STLExtras.h:1652
LLVM_ABI bool programUndefinedIfPoison(const Instruction *Inst)
LLVM_ABI unsigned getDeinterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.deinterleaveN intrinsics.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
constexpr uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
Definition Alignment.h:149
LLVM_ABI unsigned getInterleaveIntrinsicFactor(Intrinsic::ID ID)
Returns the corresponding factor of llvm.vector.interleaveN intrinsics.
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
Definition STLExtras.h:552
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI 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...
MutableArrayRef(T &OneElt) -> MutableArrayRef< T >
constexpr int PoisonMaskElem
LLVM_ABI void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
Definition Local.cpp:3186
@ Other
Any other memory.
Definition ModRef.h:68
TargetTransformInfo TTI
LLVM_ABI bool isSafeToLoadUnconditionally(Value *V, Align Alignment, const APInt &Size, const SimplifyQuery &SQ, bool IgnoreFree=false)
Return true if we know that executing a load from this value cannot trap.
Definition Loads.cpp:456
LLVM_ABI Value * simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
LLVM_ABI 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...
LLVM_ABI Intrinsic::ID getReductionForBinop(Instruction::BinaryOps Opc)
Returns the reduction intrinsic id corresponding to the binary operation.
@ And
Bitwise or logical AND of integers.
LLVM_ABI bool isVectorIntrinsicWithScalarOpAtArg(Intrinsic::ID ID, unsigned ScalarOpdIdx, const TargetTransformInfo *TTI)
Identifies if the vector form of the intrinsic has a scalar operand.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Count
Definition InstrProf.h:145
DWARFExpression::Operation Op
unsigned M0(unsigned Val)
Definition VE.h:393
ArrayRef(const T &OneElt) -> ArrayRef< T >
LLVM_ABI bool willNotFreeBetween(const Instruction *Assume, const Instruction *CtxI, const DominatorTree *DT=nullptr)
Returns true, if no instruction between Assume and CtxI may free (including through synchronization).
constexpr unsigned BitWidth
LLVM_ABI bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
LLVM_ABI Constant * getLosslessInvCast(Constant *C, Type *InvCastTo, unsigned CastOp, const DataLayout &DL, PreservedCastFlags *Flags=nullptr)
Try to cast C to InvC losslessly, satisfying CastOp(InvC) equals C, or CastOp(InvC) is a refined valu...
const VectorizeOptions & getVectorizeOptions(const LLVMContext &C)
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
constexpr bool isIntN(unsigned N, int64_t x)
Checks if an signed integer fits into the given (dynamic) bit width.
Definition MathExtras.h:249
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition Alignment.h:206
bool all_equal(std::initializer_list< T > Values)
Returns true if all Values in the initializer lists are equal or the list.
Definition STLExtras.h:2182
LLVM_ABI Value * simplifyCmpInst(CmpPredicate Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
LLVM_ABI 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.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
LLVM_ABI bool isKnownNonNegative(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Returns true if the give value is known to be non-negative.
LLVM_ABI bool isTriviallyVectorizable(Intrinsic::ID ID)
Identify if the intrinsic is trivially vectorizable.
LLVM_ABI Intrinsic::ID getMinMaxReductionIntrinsicID(Intrinsic::ID IID)
Returns the llvm.vector.reduce min/max intrinsic that corresponds to the intrinsic op.
LLVM_ABI ConstantRange computeConstantRange(const Value *V, bool ForSigned, const SimplifyQuery &SQ, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:881
#define N
LLVM_ABI AAMDNodes adjustForAccess(unsigned AccessSize)
Create a new AAMDNode for accessing AccessSize bytes of this AAMDNode.
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:310
unsigned countMinLeadingZeros() const
Returns the minimum number of leading zero bits.
Definition KnownBits.h:262
APInt getMaxValue() const
Return the maximal unsigned value possible given these KnownBits.
Definition KnownBits.h:146
const DataLayout & DL
const DominatorTree * DT
SimplifyQuery getWithInstruction(const Instruction *I) const
AssumptionCache * AC
const Instruction * CtxI