LLVM 19.0.0git
VectorCombine.cpp
Go to the documentation of this file.
1//===------- VectorCombine.cpp - Optimize partial vector operations -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass optimizes scalar/vector interactions using target cost models. The
10// transforms implemented here may not fit in traditional loop-based or SLP
11// vectorization passes.
12//
13//===----------------------------------------------------------------------===//
14
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/ScopeExit.h"
18#include "llvm/ADT/Statistic.h"
22#include "llvm/Analysis/Loads.h"
26#include "llvm/IR/Dominators.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/IRBuilder.h"
33#include <numeric>
34#include <queue>
35
36#define DEBUG_TYPE "vector-combine"
38
39using namespace llvm;
40using namespace llvm::PatternMatch;
41
42STATISTIC(NumVecLoad, "Number of vector loads formed");
43STATISTIC(NumVecCmp, "Number of vector compares formed");
44STATISTIC(NumVecBO, "Number of vector binops formed");
45STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
46STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
47STATISTIC(NumScalarBO, "Number of scalar binops formed");
48STATISTIC(NumScalarCmp, "Number of scalar compares formed");
49
51 "disable-vector-combine", cl::init(false), cl::Hidden,
52 cl::desc("Disable all vector combine transforms"));
53
55 "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
56 cl::desc("Disable binop extract to shuffle transforms"));
57
59 "vector-combine-max-scan-instrs", cl::init(30), cl::Hidden,
60 cl::desc("Max number of instructions to scan for vector combining."));
61
62static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
63
64namespace {
65class VectorCombine {
66public:
67 VectorCombine(Function &F, const TargetTransformInfo &TTI,
68 const DominatorTree &DT, AAResults &AA, AssumptionCache &AC,
69 const DataLayout *DL, bool TryEarlyFoldsOnly)
70 : F(F), Builder(F.getContext()), TTI(TTI), DT(DT), AA(AA), AC(AC), DL(DL),
71 TryEarlyFoldsOnly(TryEarlyFoldsOnly) {}
72
73 bool run();
74
75private:
76 Function &F;
77 IRBuilder<> Builder;
79 const DominatorTree &DT;
80 AAResults &AA;
82 const DataLayout *DL;
83
84 /// If true, only perform beneficial early IR transforms. Do not introduce new
85 /// vector operations.
86 bool TryEarlyFoldsOnly;
87
88 InstructionWorklist Worklist;
89
90 // TODO: Direct calls from the top-level "run" loop use a plain "Instruction"
91 // parameter. That should be updated to specific sub-classes because the
92 // run loop was changed to dispatch on opcode.
93 bool vectorizeLoadInsert(Instruction &I);
94 bool widenSubvectorLoad(Instruction &I);
95 ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
97 unsigned PreferredExtractIndex) const;
98 bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
99 const Instruction &I,
100 ExtractElementInst *&ConvertToShuffle,
101 unsigned PreferredExtractIndex);
102 void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
103 Instruction &I);
104 void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
105 Instruction &I);
106 bool foldExtractExtract(Instruction &I);
107 bool foldInsExtFNeg(Instruction &I);
108 bool foldBitcastShuffle(Instruction &I);
109 bool scalarizeBinopOrCmp(Instruction &I);
110 bool scalarizeVPIntrinsic(Instruction &I);
111 bool foldExtractedCmps(Instruction &I);
112 bool foldSingleElementStore(Instruction &I);
113 bool scalarizeLoadExtract(Instruction &I);
114 bool foldShuffleOfBinops(Instruction &I);
115 bool foldShuffleOfCastops(Instruction &I);
116 bool foldShuffleFromReductions(Instruction &I);
117 bool foldTruncFromReductions(Instruction &I);
118 bool foldSelectShuffle(Instruction &I, bool FromReduction = false);
119
120 void replaceValue(Value &Old, Value &New) {
121 Old.replaceAllUsesWith(&New);
122 if (auto *NewI = dyn_cast<Instruction>(&New)) {
123 New.takeName(&Old);
124 Worklist.pushUsersToWorkList(*NewI);
125 Worklist.pushValue(NewI);
126 }
127 Worklist.pushValue(&Old);
128 }
129
131 for (Value *Op : I.operands())
132 Worklist.pushValue(Op);
133 Worklist.remove(&I);
134 I.eraseFromParent();
135 }
136};
137} // namespace
138
139/// Return the source operand of a potentially bitcasted value. If there is no
140/// bitcast, return the input value itself.
142 while (auto *BitCast = dyn_cast<BitCastInst>(V))
143 V = BitCast->getOperand(0);
144 return V;
145}
146
147static bool canWidenLoad(LoadInst *Load, const TargetTransformInfo &TTI) {
148 // Do not widen load if atomic/volatile or under asan/hwasan/memtag/tsan.
149 // The widened load may load data from dirty regions or create data races
150 // non-existent in the source.
151 if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
152 Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
154 return false;
155
156 // We are potentially transforming byte-sized (8-bit) memory accesses, so make
157 // sure we have all of our type-based constraints in place for this target.
158 Type *ScalarTy = Load->getType()->getScalarType();
159 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
160 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
161 if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
162 ScalarSize % 8 != 0)
163 return false;
164
165 return true;
166}
167
168bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
169 // Match insert into fixed vector of scalar value.
170 // TODO: Handle non-zero insert index.
171 Value *Scalar;
172 if (!match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt())) ||
173 !Scalar->hasOneUse())
174 return false;
175
176 // Optionally match an extract from another vector.
177 Value *X;
178 bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
179 if (!HasExtract)
180 X = Scalar;
181
182 auto *Load = dyn_cast<LoadInst>(X);
183 if (!canWidenLoad(Load, TTI))
184 return false;
185
186 Type *ScalarTy = Scalar->getType();
187 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
188 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
189
190 // Check safety of replacing the scalar load with a larger vector load.
191 // We use minimal alignment (maximum flexibility) because we only care about
192 // the dereferenceable region. When calculating cost and creating a new op,
193 // we may use a larger value based on alignment attributes.
194 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
195 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
196
197 unsigned MinVecNumElts = MinVectorSize / ScalarSize;
198 auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
199 unsigned OffsetEltIndex = 0;
200 Align Alignment = Load->getAlign();
201 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), *DL, Load, &AC,
202 &DT)) {
203 // It is not safe to load directly from the pointer, but we can still peek
204 // through gep offsets and check if it safe to load from a base address with
205 // updated alignment. If it is, we can shuffle the element(s) into place
206 // after loading.
207 unsigned OffsetBitWidth = DL->getIndexTypeSizeInBits(SrcPtr->getType());
208 APInt Offset(OffsetBitWidth, 0);
210
211 // We want to shuffle the result down from a high element of a vector, so
212 // the offset must be positive.
213 if (Offset.isNegative())
214 return false;
215
216 // The offset must be a multiple of the scalar element to shuffle cleanly
217 // in the element's size.
218 uint64_t ScalarSizeInBytes = ScalarSize / 8;
219 if (Offset.urem(ScalarSizeInBytes) != 0)
220 return false;
221
222 // If we load MinVecNumElts, will our target element still be loaded?
223 OffsetEltIndex = Offset.udiv(ScalarSizeInBytes).getZExtValue();
224 if (OffsetEltIndex >= MinVecNumElts)
225 return false;
226
227 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), *DL, Load, &AC,
228 &DT))
229 return false;
230
231 // Update alignment with offset value. Note that the offset could be negated
232 // to more accurately represent "(new) SrcPtr - Offset = (old) SrcPtr", but
233 // negation does not change the result of the alignment calculation.
234 Alignment = commonAlignment(Alignment, Offset.getZExtValue());
235 }
236
237 // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
238 // Use the greater of the alignment on the load or its source pointer.
239 Alignment = std::max(SrcPtr->getPointerAlignment(*DL), Alignment);
240 Type *LoadTy = Load->getType();
241 unsigned AS = Load->getPointerAddressSpace();
242 InstructionCost OldCost =
243 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
244 APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
246 OldCost +=
247 TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
248 /* Insert */ true, HasExtract, CostKind);
249
250 // New pattern: load VecPtr
251 InstructionCost NewCost =
252 TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS);
253 // Optionally, we are shuffling the loaded vector element(s) into place.
254 // For the mask set everything but element 0 to undef to prevent poison from
255 // propagating from the extra loaded memory. This will also optionally
256 // shrink/grow the vector from the loaded size to the output size.
257 // We assume this operation has no cost in codegen if there was no offset.
258 // Note that we could use freeze to avoid poison problems, but then we might
259 // still need a shuffle to change the vector size.
260 auto *Ty = cast<FixedVectorType>(I.getType());
261 unsigned OutputNumElts = Ty->getNumElements();
263 assert(OffsetEltIndex < MinVecNumElts && "Address offset too big");
264 Mask[0] = OffsetEltIndex;
265 if (OffsetEltIndex)
266 NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, MinVecTy, Mask);
267
268 // We can aggressively convert to the vector form because the backend can
269 // invert this transform if it does not result in a performance win.
270 if (OldCost < NewCost || !NewCost.isValid())
271 return false;
272
273 // It is safe and potentially profitable to load a vector directly:
274 // inselt undef, load Scalar, 0 --> load VecPtr
275 IRBuilder<> Builder(Load);
276 Value *CastedPtr =
277 Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Builder.getPtrTy(AS));
278 Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
279 VecLd = Builder.CreateShuffleVector(VecLd, Mask);
280
281 replaceValue(I, *VecLd);
282 ++NumVecLoad;
283 return true;
284}
285
286/// If we are loading a vector and then inserting it into a larger vector with
287/// undefined elements, try to load the larger vector and eliminate the insert.
288/// This removes a shuffle in IR and may allow combining of other loaded values.
289bool VectorCombine::widenSubvectorLoad(Instruction &I) {
290 // Match subvector insert of fixed vector.
291 auto *Shuf = cast<ShuffleVectorInst>(&I);
292 if (!Shuf->isIdentityWithPadding())
293 return false;
294
295 // Allow a non-canonical shuffle mask that is choosing elements from op1.
296 unsigned NumOpElts =
297 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
298 unsigned OpIndex = any_of(Shuf->getShuffleMask(), [&NumOpElts](int M) {
299 return M >= (int)(NumOpElts);
300 });
301
302 auto *Load = dyn_cast<LoadInst>(Shuf->getOperand(OpIndex));
303 if (!canWidenLoad(Load, TTI))
304 return false;
305
306 // We use minimal alignment (maximum flexibility) because we only care about
307 // the dereferenceable region. When calculating cost and creating a new op,
308 // we may use a larger value based on alignment attributes.
309 auto *Ty = cast<FixedVectorType>(I.getType());
310 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
311 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
312 Align Alignment = Load->getAlign();
313 if (!isSafeToLoadUnconditionally(SrcPtr, Ty, Align(1), *DL, Load, &AC, &DT))
314 return false;
315
316 Alignment = std::max(SrcPtr->getPointerAlignment(*DL), Alignment);
317 Type *LoadTy = Load->getType();
318 unsigned AS = Load->getPointerAddressSpace();
319
320 // Original pattern: insert_subvector (load PtrOp)
321 // This conservatively assumes that the cost of a subvector insert into an
322 // undef value is 0. We could add that cost if the cost model accurately
323 // reflects the real cost of that operation.
324 InstructionCost OldCost =
325 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
326
327 // New pattern: load PtrOp
328 InstructionCost NewCost =
329 TTI.getMemoryOpCost(Instruction::Load, Ty, Alignment, AS);
330
331 // We can aggressively convert to the vector form because the backend can
332 // invert this transform if it does not result in a performance win.
333 if (OldCost < NewCost || !NewCost.isValid())
334 return false;
335
336 IRBuilder<> Builder(Load);
337 Value *CastedPtr =
338 Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Builder.getPtrTy(AS));
339 Value *VecLd = Builder.CreateAlignedLoad(Ty, CastedPtr, Alignment);
340 replaceValue(I, *VecLd);
341 ++NumVecLoad;
342 return true;
343}
344
345/// Determine which, if any, of the inputs should be replaced by a shuffle
346/// followed by extract from a different index.
347ExtractElementInst *VectorCombine::getShuffleExtract(
349 unsigned PreferredExtractIndex = InvalidIndex) const {
350 auto *Index0C = dyn_cast<ConstantInt>(Ext0->getIndexOperand());
351 auto *Index1C = dyn_cast<ConstantInt>(Ext1->getIndexOperand());
352 assert(Index0C && Index1C && "Expected constant extract indexes");
353
354 unsigned Index0 = Index0C->getZExtValue();
355 unsigned Index1 = Index1C->getZExtValue();
356
357 // If the extract indexes are identical, no shuffle is needed.
358 if (Index0 == Index1)
359 return nullptr;
360
361 Type *VecTy = Ext0->getVectorOperand()->getType();
363 assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
364 InstructionCost Cost0 =
365 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
366 InstructionCost Cost1 =
367 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
368
369 // If both costs are invalid no shuffle is needed
370 if (!Cost0.isValid() && !Cost1.isValid())
371 return nullptr;
372
373 // We are extracting from 2 different indexes, so one operand must be shuffled
374 // before performing a vector operation and/or extract. The more expensive
375 // extract will be replaced by a shuffle.
376 if (Cost0 > Cost1)
377 return Ext0;
378 if (Cost1 > Cost0)
379 return Ext1;
380
381 // If the costs are equal and there is a preferred extract index, shuffle the
382 // opposite operand.
383 if (PreferredExtractIndex == Index0)
384 return Ext1;
385 if (PreferredExtractIndex == Index1)
386 return Ext0;
387
388 // Otherwise, replace the extract with the higher index.
389 return Index0 > Index1 ? Ext0 : Ext1;
390}
391
392/// Compare the relative costs of 2 extracts followed by scalar operation vs.
393/// vector operation(s) followed by extract. Return true if the existing
394/// instructions are cheaper than a vector alternative. Otherwise, return false
395/// and if one of the extracts should be transformed to a shufflevector, set
396/// \p ConvertToShuffle to that extract instruction.
397bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
398 ExtractElementInst *Ext1,
399 const Instruction &I,
400 ExtractElementInst *&ConvertToShuffle,
401 unsigned PreferredExtractIndex) {
402 auto *Ext0IndexC = dyn_cast<ConstantInt>(Ext0->getOperand(1));
403 auto *Ext1IndexC = dyn_cast<ConstantInt>(Ext1->getOperand(1));
404 assert(Ext0IndexC && Ext1IndexC && "Expected constant extract indexes");
405
406 unsigned Opcode = I.getOpcode();
407 Type *ScalarTy = Ext0->getType();
408 auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
409 InstructionCost ScalarOpCost, VectorOpCost;
410
411 // Get cost estimates for scalar and vector versions of the operation.
412 bool IsBinOp = Instruction::isBinaryOp(Opcode);
413 if (IsBinOp) {
414 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
415 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
416 } else {
417 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
418 "Expected a compare");
419 CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
420 ScalarOpCost = TTI.getCmpSelInstrCost(
421 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
422 VectorOpCost = TTI.getCmpSelInstrCost(
423 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
424 }
425
426 // Get cost estimates for the extract elements. These costs will factor into
427 // both sequences.
428 unsigned Ext0Index = Ext0IndexC->getZExtValue();
429 unsigned Ext1Index = Ext1IndexC->getZExtValue();
431
432 InstructionCost Extract0Cost =
433 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Ext0Index);
434 InstructionCost Extract1Cost =
435 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Ext1Index);
436
437 // A more expensive extract will always be replaced by a splat shuffle.
438 // For example, if Ext0 is more expensive:
439 // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
440 // extelt (opcode (splat V0, Ext0), V1), Ext1
441 // TODO: Evaluate whether that always results in lowest cost. Alternatively,
442 // check the cost of creating a broadcast shuffle and shuffling both
443 // operands to element 0.
444 InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
445
446 // Extra uses of the extracts mean that we include those costs in the
447 // vector total because those instructions will not be eliminated.
448 InstructionCost OldCost, NewCost;
449 if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
450 // Handle a special case. If the 2 extracts are identical, adjust the
451 // formulas to account for that. The extra use charge allows for either the
452 // CSE'd pattern or an unoptimized form with identical values:
453 // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
454 bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
455 : !Ext0->hasOneUse() || !Ext1->hasOneUse();
456 OldCost = CheapExtractCost + ScalarOpCost;
457 NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
458 } else {
459 // Handle the general case. Each extract is actually a different value:
460 // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
461 OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
462 NewCost = VectorOpCost + CheapExtractCost +
463 !Ext0->hasOneUse() * Extract0Cost +
464 !Ext1->hasOneUse() * Extract1Cost;
465 }
466
467 ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
468 if (ConvertToShuffle) {
469 if (IsBinOp && DisableBinopExtractShuffle)
470 return true;
471
472 // If we are extracting from 2 different indexes, then one operand must be
473 // shuffled before performing the vector operation. The shuffle mask is
474 // poison except for 1 lane that is being translated to the remaining
475 // extraction lane. Therefore, it is a splat shuffle. Ex:
476 // ShufMask = { poison, poison, 0, poison }
477 // TODO: The cost model has an option for a "broadcast" shuffle
478 // (splat-from-element-0), but no option for a more general splat.
479 NewCost +=
481 }
482
483 // Aggressively form a vector op if the cost is equal because the transform
484 // may enable further optimization.
485 // Codegen can reverse this transform (scalarize) if it was not profitable.
486 return OldCost < NewCost;
487}
488
489/// Create a shuffle that translates (shifts) 1 element from the input vector
490/// to a new element location.
491static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
492 unsigned NewIndex, IRBuilder<> &Builder) {
493 // The shuffle mask is poison except for 1 lane that is being translated
494 // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
495 // ShufMask = { 2, poison, poison, poison }
496 auto *VecTy = cast<FixedVectorType>(Vec->getType());
497 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem);
498 ShufMask[NewIndex] = OldIndex;
499 return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
500}
501
502/// Given an extract element instruction with constant index operand, shuffle
503/// the source vector (shift the scalar element) to a NewIndex for extraction.
504/// Return null if the input can be constant folded, so that we are not creating
505/// unnecessary instructions.
507 unsigned NewIndex,
508 IRBuilder<> &Builder) {
509 // Shufflevectors can only be created for fixed-width vectors.
510 if (!isa<FixedVectorType>(ExtElt->getOperand(0)->getType()))
511 return nullptr;
512
513 // If the extract can be constant-folded, this code is unsimplified. Defer
514 // to other passes to handle that.
515 Value *X = ExtElt->getVectorOperand();
516 Value *C = ExtElt->getIndexOperand();
517 assert(isa<ConstantInt>(C) && "Expected a constant index operand");
518 if (isa<Constant>(X))
519 return nullptr;
520
521 Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
522 NewIndex, Builder);
523 return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
524}
525
526/// Try to reduce extract element costs by converting scalar compares to vector
527/// compares followed by extract.
528/// cmp (ext0 V0, C), (ext1 V1, C)
529void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
531 assert(isa<CmpInst>(&I) && "Expected a compare");
532 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
533 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
534 "Expected matching constant extract indexes");
535
536 // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
537 ++NumVecCmp;
538 CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
539 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
540 Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
541 Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
542 replaceValue(I, *NewExt);
543}
544
545/// Try to reduce extract element costs by converting scalar binops to vector
546/// binops followed by extract.
547/// bo (ext0 V0, C), (ext1 V1, C)
548void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
550 assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
551 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
552 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
553 "Expected matching constant extract indexes");
554
555 // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
556 ++NumVecBO;
557 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
558 Value *VecBO =
559 Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
560
561 // All IR flags are safe to back-propagate because any potential poison
562 // created in unused vector elements is discarded by the extract.
563 if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
564 VecBOInst->copyIRFlags(&I);
565
566 Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
567 replaceValue(I, *NewExt);
568}
569
570/// Match an instruction with extracted vector operands.
571bool VectorCombine::foldExtractExtract(Instruction &I) {
572 // It is not safe to transform things like div, urem, etc. because we may
573 // create undefined behavior when executing those on unknown vector elements.
575 return false;
576
577 Instruction *I0, *I1;
579 if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
581 return false;
582
583 Value *V0, *V1;
584 uint64_t C0, C1;
585 if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
586 !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
587 V0->getType() != V1->getType())
588 return false;
589
590 // If the scalar value 'I' is going to be re-inserted into a vector, then try
591 // to create an extract to that same element. The extract/insert can be
592 // reduced to a "select shuffle".
593 // TODO: If we add a larger pattern match that starts from an insert, this
594 // probably becomes unnecessary.
595 auto *Ext0 = cast<ExtractElementInst>(I0);
596 auto *Ext1 = cast<ExtractElementInst>(I1);
597 uint64_t InsertIndex = InvalidIndex;
598 if (I.hasOneUse())
599 match(I.user_back(),
600 m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
601
602 ExtractElementInst *ExtractToChange;
603 if (isExtractExtractCheap(Ext0, Ext1, I, ExtractToChange, InsertIndex))
604 return false;
605
606 if (ExtractToChange) {
607 unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
608 ExtractElementInst *NewExtract =
609 translateExtract(ExtractToChange, CheapExtractIdx, Builder);
610 if (!NewExtract)
611 return false;
612 if (ExtractToChange == Ext0)
613 Ext0 = NewExtract;
614 else
615 Ext1 = NewExtract;
616 }
617
618 if (Pred != CmpInst::BAD_ICMP_PREDICATE)
619 foldExtExtCmp(Ext0, Ext1, I);
620 else
621 foldExtExtBinop(Ext0, Ext1, I);
622
623 Worklist.push(Ext0);
624 Worklist.push(Ext1);
625 return true;
626}
627
628/// Try to replace an extract + scalar fneg + insert with a vector fneg +
629/// shuffle.
630bool VectorCombine::foldInsExtFNeg(Instruction &I) {
631 // Match an insert (op (extract)) pattern.
632 Value *DestVec;
634 Instruction *FNeg;
635 if (!match(&I, m_InsertElt(m_Value(DestVec), m_OneUse(m_Instruction(FNeg)),
637 return false;
638
639 // Note: This handles the canonical fneg instruction and "fsub -0.0, X".
640 Value *SrcVec;
641 Instruction *Extract;
642 if (!match(FNeg, m_FNeg(m_CombineAnd(
643 m_Instruction(Extract),
645 return false;
646
647 // TODO: We could handle this with a length-changing shuffle.
648 auto *VecTy = cast<FixedVectorType>(I.getType());
649 if (SrcVec->getType() != VecTy)
650 return false;
651
652 // Ignore bogus insert/extract index.
653 unsigned NumElts = VecTy->getNumElements();
654 if (Index >= NumElts)
655 return false;
656
657 // We are inserting the negated element into the same lane that we extracted
658 // from. This is equivalent to a select-shuffle that chooses all but the
659 // negated element from the destination vector.
660 SmallVector<int> Mask(NumElts);
661 std::iota(Mask.begin(), Mask.end(), 0);
662 Mask[Index] = Index + NumElts;
663
664 Type *ScalarTy = VecTy->getScalarType();
666 InstructionCost OldCost =
667 TTI.getArithmeticInstrCost(Instruction::FNeg, ScalarTy) +
669
670 // If the extract has one use, it will be eliminated, so count it in the
671 // original cost. If it has more than one use, ignore the cost because it will
672 // be the same before/after.
673 if (Extract->hasOneUse())
674 OldCost += TTI.getVectorInstrCost(*Extract, VecTy, CostKind, Index);
675
676 InstructionCost NewCost =
677 TTI.getArithmeticInstrCost(Instruction::FNeg, VecTy) +
679
680 if (NewCost > OldCost)
681 return false;
682
683 // insertelt DestVec, (fneg (extractelt SrcVec, Index)), Index -->
684 // shuffle DestVec, (fneg SrcVec), Mask
685 Value *VecFNeg = Builder.CreateFNegFMF(SrcVec, FNeg);
686 Value *Shuf = Builder.CreateShuffleVector(DestVec, VecFNeg, Mask);
687 replaceValue(I, *Shuf);
688 return true;
689}
690
691/// If this is a bitcast of a shuffle, try to bitcast the source vector to the
692/// destination type followed by shuffle. This can enable further transforms by
693/// moving bitcasts or shuffles together.
694bool VectorCombine::foldBitcastShuffle(Instruction &I) {
695 Value *V0, *V1;
697 if (!match(&I, m_BitCast(m_OneUse(
698 m_Shuffle(m_Value(V0), m_Value(V1), m_Mask(Mask))))))
699 return false;
700
701 // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
702 // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
703 // mask for scalable type is a splat or not.
704 // 2) Disallow non-vector casts.
705 // TODO: We could allow any shuffle.
706 auto *DestTy = dyn_cast<FixedVectorType>(I.getType());
707 auto *SrcTy = dyn_cast<FixedVectorType>(V0->getType());
708 if (!DestTy || !SrcTy)
709 return false;
710
711 unsigned DestEltSize = DestTy->getScalarSizeInBits();
712 unsigned SrcEltSize = SrcTy->getScalarSizeInBits();
713 if (SrcTy->getPrimitiveSizeInBits() % DestEltSize != 0)
714 return false;
715
716 bool IsUnary = isa<UndefValue>(V1);
717
718 // For binary shuffles, only fold bitcast(shuffle(X,Y))
719 // if it won't increase the number of bitcasts.
720 if (!IsUnary) {
721 auto *BCTy0 = dyn_cast<FixedVectorType>(peekThroughBitcasts(V0)->getType());
722 auto *BCTy1 = dyn_cast<FixedVectorType>(peekThroughBitcasts(V1)->getType());
723 if (!(BCTy0 && BCTy0->getElementType() == DestTy->getElementType()) &&
724 !(BCTy1 && BCTy1->getElementType() == DestTy->getElementType()))
725 return false;
726 }
727
728 SmallVector<int, 16> NewMask;
729 if (DestEltSize <= SrcEltSize) {
730 // The bitcast is from wide to narrow/equal elements. The shuffle mask can
731 // always be expanded to the equivalent form choosing narrower elements.
732 assert(SrcEltSize % DestEltSize == 0 && "Unexpected shuffle mask");
733 unsigned ScaleFactor = SrcEltSize / DestEltSize;
734 narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
735 } else {
736 // The bitcast is from narrow elements to wide elements. The shuffle mask
737 // must choose consecutive elements to allow casting first.
738 assert(DestEltSize % SrcEltSize == 0 && "Unexpected shuffle mask");
739 unsigned ScaleFactor = DestEltSize / SrcEltSize;
740 if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
741 return false;
742 }
743
744 // Bitcast the shuffle src - keep its original width but using the destination
745 // scalar type.
746 unsigned NumSrcElts = SrcTy->getPrimitiveSizeInBits() / DestEltSize;
747 auto *NewShuffleTy =
748 FixedVectorType::get(DestTy->getScalarType(), NumSrcElts);
749 auto *OldShuffleTy =
750 FixedVectorType::get(SrcTy->getScalarType(), Mask.size());
751 unsigned NumOps = IsUnary ? 1 : 2;
752
753 // The new shuffle must not cost more than the old shuffle.
759
760 InstructionCost DestCost =
761 TTI.getShuffleCost(SK, NewShuffleTy, NewMask, CK) +
762 (NumOps * TTI.getCastInstrCost(Instruction::BitCast, NewShuffleTy, SrcTy,
763 TargetTransformInfo::CastContextHint::None,
764 CK));
765 InstructionCost SrcCost =
766 TTI.getShuffleCost(SK, SrcTy, Mask, CK) +
767 TTI.getCastInstrCost(Instruction::BitCast, DestTy, OldShuffleTy,
768 TargetTransformInfo::CastContextHint::None, CK);
769 if (DestCost > SrcCost || !DestCost.isValid())
770 return false;
771
772 // bitcast (shuf V0, V1, MaskC) --> shuf (bitcast V0), (bitcast V1), MaskC'
773 ++NumShufOfBitcast;
774 Value *CastV0 = Builder.CreateBitCast(peekThroughBitcasts(V0), NewShuffleTy);
775 Value *CastV1 = Builder.CreateBitCast(peekThroughBitcasts(V1), NewShuffleTy);
776 Value *Shuf = Builder.CreateShuffleVector(CastV0, CastV1, NewMask);
777 replaceValue(I, *Shuf);
778 return true;
779}
780
781/// VP Intrinsics whose vector operands are both splat values may be simplified
782/// into the scalar version of the operation and the result splatted. This
783/// can lead to scalarization down the line.
784bool VectorCombine::scalarizeVPIntrinsic(Instruction &I) {
785 if (!isa<VPIntrinsic>(I))
786 return false;
787 VPIntrinsic &VPI = cast<VPIntrinsic>(I);
788 Value *Op0 = VPI.getArgOperand(0);
789 Value *Op1 = VPI.getArgOperand(1);
790
791 if (!isSplatValue(Op0) || !isSplatValue(Op1))
792 return false;
793
794 // Check getSplatValue early in this function, to avoid doing unnecessary
795 // work.
796 Value *ScalarOp0 = getSplatValue(Op0);
797 Value *ScalarOp1 = getSplatValue(Op1);
798 if (!ScalarOp0 || !ScalarOp1)
799 return false;
800
801 // For the binary VP intrinsics supported here, the result on disabled lanes
802 // is a poison value. For now, only do this simplification if all lanes
803 // are active.
804 // TODO: Relax the condition that all lanes are active by using insertelement
805 // on inactive lanes.
806 auto IsAllTrueMask = [](Value *MaskVal) {
807 if (Value *SplattedVal = getSplatValue(MaskVal))
808 if (auto *ConstValue = dyn_cast<Constant>(SplattedVal))
809 return ConstValue->isAllOnesValue();
810 return false;
811 };
812 if (!IsAllTrueMask(VPI.getArgOperand(2)))
813 return false;
814
815 // Check to make sure we support scalarization of the intrinsic
816 Intrinsic::ID IntrID = VPI.getIntrinsicID();
817 if (!VPBinOpIntrinsic::isVPBinOp(IntrID))
818 return false;
819
820 // Calculate cost of splatting both operands into vectors and the vector
821 // intrinsic
822 VectorType *VecTy = cast<VectorType>(VPI.getType());
825 if (auto *FVTy = dyn_cast<FixedVectorType>(VecTy))
826 Mask.resize(FVTy->getNumElements(), 0);
827 InstructionCost SplatCost =
828 TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind, 0) +
830
831 // Calculate the cost of the VP Intrinsic
833 for (Value *V : VPI.args())
834 Args.push_back(V->getType());
835 IntrinsicCostAttributes Attrs(IntrID, VecTy, Args);
836 InstructionCost VectorOpCost = TTI.getIntrinsicInstrCost(Attrs, CostKind);
837 InstructionCost OldCost = 2 * SplatCost + VectorOpCost;
838
839 // Determine scalar opcode
840 std::optional<unsigned> FunctionalOpcode =
842 std::optional<Intrinsic::ID> ScalarIntrID = std::nullopt;
843 if (!FunctionalOpcode) {
844 ScalarIntrID = VPI.getFunctionalIntrinsicID();
845 if (!ScalarIntrID)
846 return false;
847 }
848
849 // Calculate cost of scalarizing
850 InstructionCost ScalarOpCost = 0;
851 if (ScalarIntrID) {
852 IntrinsicCostAttributes Attrs(*ScalarIntrID, VecTy->getScalarType(), Args);
853 ScalarOpCost = TTI.getIntrinsicInstrCost(Attrs, CostKind);
854 } else {
855 ScalarOpCost =
856 TTI.getArithmeticInstrCost(*FunctionalOpcode, VecTy->getScalarType());
857 }
858
859 // The existing splats may be kept around if other instructions use them.
860 InstructionCost CostToKeepSplats =
861 (SplatCost * !Op0->hasOneUse()) + (SplatCost * !Op1->hasOneUse());
862 InstructionCost NewCost = ScalarOpCost + SplatCost + CostToKeepSplats;
863
864 LLVM_DEBUG(dbgs() << "Found a VP Intrinsic to scalarize: " << VPI
865 << "\n");
866 LLVM_DEBUG(dbgs() << "Cost of Intrinsic: " << OldCost
867 << ", Cost of scalarizing:" << NewCost << "\n");
868
869 // We want to scalarize unless the vector variant actually has lower cost.
870 if (OldCost < NewCost || !NewCost.isValid())
871 return false;
872
873 // Scalarize the intrinsic
874 ElementCount EC = cast<VectorType>(Op0->getType())->getElementCount();
875 Value *EVL = VPI.getArgOperand(3);
876
877 // If the VP op might introduce UB or poison, we can scalarize it provided
878 // that we know the EVL > 0: If the EVL is zero, then the original VP op
879 // becomes a no-op and thus won't be UB, so make sure we don't introduce UB by
880 // scalarizing it.
881 bool SafeToSpeculate;
882 if (ScalarIntrID)
883 SafeToSpeculate = Intrinsic::getAttributes(I.getContext(), *ScalarIntrID)
884 .hasFnAttr(Attribute::AttrKind::Speculatable);
885 else
887 *FunctionalOpcode, &VPI, nullptr, &AC, &DT);
888 if (!SafeToSpeculate &&
889 !isKnownNonZero(EVL, /*Depth=*/0, SimplifyQuery(*DL, &DT, &AC, &VPI)))
890 return false;
891
892 Value *ScalarVal =
893 ScalarIntrID
894 ? Builder.CreateIntrinsic(VecTy->getScalarType(), *ScalarIntrID,
895 {ScalarOp0, ScalarOp1})
896 : Builder.CreateBinOp((Instruction::BinaryOps)(*FunctionalOpcode),
897 ScalarOp0, ScalarOp1);
898
899 replaceValue(VPI, *Builder.CreateVectorSplat(EC, ScalarVal));
900 return true;
901}
902
903/// Match a vector binop or compare instruction with at least one inserted
904/// scalar operand and convert to scalar binop/cmp followed by insertelement.
905bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
907 Value *Ins0, *Ins1;
908 if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
909 !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
910 return false;
911
912 // Do not convert the vector condition of a vector select into a scalar
913 // condition. That may cause problems for codegen because of differences in
914 // boolean formats and register-file transfers.
915 // TODO: Can we account for that in the cost model?
916 bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
917 if (IsCmp)
918 for (User *U : I.users())
919 if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
920 return false;
921
922 // Match against one or both scalar values being inserted into constant
923 // vectors:
924 // vec_op VecC0, (inselt VecC1, V1, Index)
925 // vec_op (inselt VecC0, V0, Index), VecC1
926 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
927 // TODO: Deal with mismatched index constants and variable indexes?
928 Constant *VecC0 = nullptr, *VecC1 = nullptr;
929 Value *V0 = nullptr, *V1 = nullptr;
930 uint64_t Index0 = 0, Index1 = 0;
931 if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
932 m_ConstantInt(Index0))) &&
933 !match(Ins0, m_Constant(VecC0)))
934 return false;
935 if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
936 m_ConstantInt(Index1))) &&
937 !match(Ins1, m_Constant(VecC1)))
938 return false;
939
940 bool IsConst0 = !V0;
941 bool IsConst1 = !V1;
942 if (IsConst0 && IsConst1)
943 return false;
944 if (!IsConst0 && !IsConst1 && Index0 != Index1)
945 return false;
946
947 // Bail for single insertion if it is a load.
948 // TODO: Handle this once getVectorInstrCost can cost for load/stores.
949 auto *I0 = dyn_cast_or_null<Instruction>(V0);
950 auto *I1 = dyn_cast_or_null<Instruction>(V1);
951 if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
952 (IsConst1 && I0 && I0->mayReadFromMemory()))
953 return false;
954
955 uint64_t Index = IsConst0 ? Index1 : Index0;
956 Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
957 Type *VecTy = I.getType();
958 assert(VecTy->isVectorTy() &&
959 (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
960 (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
961 ScalarTy->isPointerTy()) &&
962 "Unexpected types for insert element into binop or cmp");
963
964 unsigned Opcode = I.getOpcode();
965 InstructionCost ScalarOpCost, VectorOpCost;
966 if (IsCmp) {
967 CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
968 ScalarOpCost = TTI.getCmpSelInstrCost(
969 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
970 VectorOpCost = TTI.getCmpSelInstrCost(
971 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
972 } else {
973 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
974 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
975 }
976
977 // Get cost estimate for the insert element. This cost will factor into
978 // both sequences.
981 Instruction::InsertElement, VecTy, CostKind, Index);
982 InstructionCost OldCost =
983 (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + VectorOpCost;
984 InstructionCost NewCost = ScalarOpCost + InsertCost +
985 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
986 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
987
988 // We want to scalarize unless the vector variant actually has lower cost.
989 if (OldCost < NewCost || !NewCost.isValid())
990 return false;
991
992 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
993 // inselt NewVecC, (scalar_op V0, V1), Index
994 if (IsCmp)
995 ++NumScalarCmp;
996 else
997 ++NumScalarBO;
998
999 // For constant cases, extract the scalar element, this should constant fold.
1000 if (IsConst0)
1001 V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
1002 if (IsConst1)
1003 V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
1004
1005 Value *Scalar =
1006 IsCmp ? Builder.CreateCmp(Pred, V0, V1)
1007 : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
1008
1009 Scalar->setName(I.getName() + ".scalar");
1010
1011 // All IR flags are safe to back-propagate. There is no potential for extra
1012 // poison to be created by the scalar instruction.
1013 if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
1014 ScalarInst->copyIRFlags(&I);
1015
1016 // Fold the vector constants in the original vectors into a new base vector.
1017 Value *NewVecC =
1018 IsCmp ? Builder.CreateCmp(Pred, VecC0, VecC1)
1019 : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, VecC0, VecC1);
1020 Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
1021 replaceValue(I, *Insert);
1022 return true;
1023}
1024
1025/// Try to combine a scalar binop + 2 scalar compares of extracted elements of
1026/// a vector into vector operations followed by extract. Note: The SLP pass
1027/// may miss this pattern because of implementation problems.
1028bool VectorCombine::foldExtractedCmps(Instruction &I) {
1029 // We are looking for a scalar binop of booleans.
1030 // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
1031 if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
1032 return false;
1033
1034 // The compare predicates should match, and each compare should have a
1035 // constant operand.
1036 // TODO: Relax the one-use constraints.
1037 Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
1038 Instruction *I0, *I1;
1039 Constant *C0, *C1;
1040 CmpInst::Predicate P0, P1;
1041 if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
1042 !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
1043 P0 != P1)
1044 return false;
1045
1046 // The compare operands must be extracts of the same vector with constant
1047 // extract indexes.
1048 // TODO: Relax the one-use constraints.
1049 Value *X;
1050 uint64_t Index0, Index1;
1051 if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
1053 return false;
1054
1055 auto *Ext0 = cast<ExtractElementInst>(I0);
1056 auto *Ext1 = cast<ExtractElementInst>(I1);
1057 ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
1058 if (!ConvertToShuf)
1059 return false;
1060
1061 // The original scalar pattern is:
1062 // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
1063 CmpInst::Predicate Pred = P0;
1064 unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
1065 : Instruction::ICmp;
1066 auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
1067 if (!VecTy)
1068 return false;
1069
1071 InstructionCost OldCost =
1072 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
1073 OldCost += TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
1074 OldCost +=
1075 TTI.getCmpSelInstrCost(CmpOpcode, I0->getType(),
1076 CmpInst::makeCmpResultType(I0->getType()), Pred) *
1077 2;
1078 OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
1079
1080 // The proposed vector pattern is:
1081 // vcmp = cmp Pred X, VecC
1082 // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
1083 int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
1084 int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
1085 auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
1087 CmpOpcode, X->getType(), CmpInst::makeCmpResultType(X->getType()), Pred);
1088 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem);
1089 ShufMask[CheapIndex] = ExpensiveIndex;
1091 ShufMask);
1092 NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
1093 NewCost += TTI.getVectorInstrCost(*Ext0, CmpTy, CostKind, CheapIndex);
1094
1095 // Aggressively form vector ops if the cost is equal because the transform
1096 // may enable further optimization.
1097 // Codegen can reverse this transform (scalarize) if it was not profitable.
1098 if (OldCost < NewCost || !NewCost.isValid())
1099 return false;
1100
1101 // Create a vector constant from the 2 scalar constants.
1102 SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
1103 PoisonValue::get(VecTy->getElementType()));
1104 CmpC[Index0] = C0;
1105 CmpC[Index1] = C1;
1106 Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
1107
1108 Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
1109 Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
1110 VCmp, Shuf);
1111 Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
1112 replaceValue(I, *NewExt);
1113 ++NumVecCmpBO;
1114 return true;
1115}
1116
1117// Check if memory loc modified between two instrs in the same BB
1120 const MemoryLocation &Loc, AAResults &AA) {
1121 unsigned NumScanned = 0;
1122 return std::any_of(Begin, End, [&](const Instruction &Instr) {
1123 return isModSet(AA.getModRefInfo(&Instr, Loc)) ||
1124 ++NumScanned > MaxInstrsToScan;
1125 });
1126}
1127
1128namespace {
1129/// Helper class to indicate whether a vector index can be safely scalarized and
1130/// if a freeze needs to be inserted.
1131class ScalarizationResult {
1132 enum class StatusTy { Unsafe, Safe, SafeWithFreeze };
1133
1134 StatusTy Status;
1135 Value *ToFreeze;
1136
1137 ScalarizationResult(StatusTy Status, Value *ToFreeze = nullptr)
1138 : Status(Status), ToFreeze(ToFreeze) {}
1139
1140public:
1141 ScalarizationResult(const ScalarizationResult &Other) = default;
1142 ~ScalarizationResult() {
1143 assert(!ToFreeze && "freeze() not called with ToFreeze being set");
1144 }
1145
1146 static ScalarizationResult unsafe() { return {StatusTy::Unsafe}; }
1147 static ScalarizationResult safe() { return {StatusTy::Safe}; }
1148 static ScalarizationResult safeWithFreeze(Value *ToFreeze) {
1149 return {StatusTy::SafeWithFreeze, ToFreeze};
1150 }
1151
1152 /// Returns true if the index can be scalarize without requiring a freeze.
1153 bool isSafe() const { return Status == StatusTy::Safe; }
1154 /// Returns true if the index cannot be scalarized.
1155 bool isUnsafe() const { return Status == StatusTy::Unsafe; }
1156 /// Returns true if the index can be scalarize, but requires inserting a
1157 /// freeze.
1158 bool isSafeWithFreeze() const { return Status == StatusTy::SafeWithFreeze; }
1159
1160 /// Reset the state of Unsafe and clear ToFreze if set.
1161 void discard() {
1162 ToFreeze = nullptr;
1163 Status = StatusTy::Unsafe;
1164 }
1165
1166 /// Freeze the ToFreeze and update the use in \p User to use it.
1167 void freeze(IRBuilder<> &Builder, Instruction &UserI) {
1168 assert(isSafeWithFreeze() &&
1169 "should only be used when freezing is required");
1170 assert(is_contained(ToFreeze->users(), &UserI) &&
1171 "UserI must be a user of ToFreeze");
1172 IRBuilder<>::InsertPointGuard Guard(Builder);
1173 Builder.SetInsertPoint(cast<Instruction>(&UserI));
1174 Value *Frozen =
1175 Builder.CreateFreeze(ToFreeze, ToFreeze->getName() + ".frozen");
1176 for (Use &U : make_early_inc_range((UserI.operands())))
1177 if (U.get() == ToFreeze)
1178 U.set(Frozen);
1179
1180 ToFreeze = nullptr;
1181 }
1182};
1183} // namespace
1184
1185/// Check if it is legal to scalarize a memory access to \p VecTy at index \p
1186/// Idx. \p Idx must access a valid vector element.
1187static ScalarizationResult canScalarizeAccess(VectorType *VecTy, Value *Idx,
1188 Instruction *CtxI,
1189 AssumptionCache &AC,
1190 const DominatorTree &DT) {
1191 // We do checks for both fixed vector types and scalable vector types.
1192 // This is the number of elements of fixed vector types,
1193 // or the minimum number of elements of scalable vector types.
1194 uint64_t NumElements = VecTy->getElementCount().getKnownMinValue();
1195
1196 if (auto *C = dyn_cast<ConstantInt>(Idx)) {
1197 if (C->getValue().ult(NumElements))
1198 return ScalarizationResult::safe();
1199 return ScalarizationResult::unsafe();
1200 }
1201
1202 unsigned IntWidth = Idx->getType()->getScalarSizeInBits();
1203 APInt Zero(IntWidth, 0);
1204 APInt MaxElts(IntWidth, NumElements);
1205 ConstantRange ValidIndices(Zero, MaxElts);
1206 ConstantRange IdxRange(IntWidth, true);
1207
1208 if (isGuaranteedNotToBePoison(Idx, &AC)) {
1209 if (ValidIndices.contains(computeConstantRange(Idx, /* ForSigned */ false,
1210 true, &AC, CtxI, &DT)))
1211 return ScalarizationResult::safe();
1212 return ScalarizationResult::unsafe();
1213 }
1214
1215 // If the index may be poison, check if we can insert a freeze before the
1216 // range of the index is restricted.
1217 Value *IdxBase;
1218 ConstantInt *CI;
1219 if (match(Idx, m_And(m_Value(IdxBase), m_ConstantInt(CI)))) {
1220 IdxRange = IdxRange.binaryAnd(CI->getValue());
1221 } else if (match(Idx, m_URem(m_Value(IdxBase), m_ConstantInt(CI)))) {
1222 IdxRange = IdxRange.urem(CI->getValue());
1223 }
1224
1225 if (ValidIndices.contains(IdxRange))
1226 return ScalarizationResult::safeWithFreeze(IdxBase);
1227 return ScalarizationResult::unsafe();
1228}
1229
1230/// The memory operation on a vector of \p ScalarType had alignment of
1231/// \p VectorAlignment. Compute the maximal, but conservatively correct,
1232/// alignment that will be valid for the memory operation on a single scalar
1233/// element of the same type with index \p Idx.
1235 Type *ScalarType, Value *Idx,
1236 const DataLayout &DL) {
1237 if (auto *C = dyn_cast<ConstantInt>(Idx))
1238 return commonAlignment(VectorAlignment,
1239 C->getZExtValue() * DL.getTypeStoreSize(ScalarType));
1240 return commonAlignment(VectorAlignment, DL.getTypeStoreSize(ScalarType));
1241}
1242
1243// Combine patterns like:
1244// %0 = load <4 x i32>, <4 x i32>* %a
1245// %1 = insertelement <4 x i32> %0, i32 %b, i32 1
1246// store <4 x i32> %1, <4 x i32>* %a
1247// to:
1248// %0 = bitcast <4 x i32>* %a to i32*
1249// %1 = getelementptr inbounds i32, i32* %0, i64 0, i64 1
1250// store i32 %b, i32* %1
1251bool VectorCombine::foldSingleElementStore(Instruction &I) {
1252 auto *SI = cast<StoreInst>(&I);
1253 if (!SI->isSimple() || !isa<VectorType>(SI->getValueOperand()->getType()))
1254 return false;
1255
1256 // TODO: Combine more complicated patterns (multiple insert) by referencing
1257 // TargetTransformInfo.
1259 Value *NewElement;
1260 Value *Idx;
1261 if (!match(SI->getValueOperand(),
1262 m_InsertElt(m_Instruction(Source), m_Value(NewElement),
1263 m_Value(Idx))))
1264 return false;
1265
1266 if (auto *Load = dyn_cast<LoadInst>(Source)) {
1267 auto VecTy = cast<VectorType>(SI->getValueOperand()->getType());
1268 Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts();
1269 // Don't optimize for atomic/volatile load or store. Ensure memory is not
1270 // modified between, vector type matches store size, and index is inbounds.
1271 if (!Load->isSimple() || Load->getParent() != SI->getParent() ||
1272 !DL->typeSizeEqualsStoreSize(Load->getType()->getScalarType()) ||
1273 SrcAddr != SI->getPointerOperand()->stripPointerCasts())
1274 return false;
1275
1276 auto ScalarizableIdx = canScalarizeAccess(VecTy, Idx, Load, AC, DT);
1277 if (ScalarizableIdx.isUnsafe() ||
1278 isMemModifiedBetween(Load->getIterator(), SI->getIterator(),
1279 MemoryLocation::get(SI), AA))
1280 return false;
1281
1282 if (ScalarizableIdx.isSafeWithFreeze())
1283 ScalarizableIdx.freeze(Builder, *cast<Instruction>(Idx));
1284 Value *GEP = Builder.CreateInBoundsGEP(
1285 SI->getValueOperand()->getType(), SI->getPointerOperand(),
1286 {ConstantInt::get(Idx->getType(), 0), Idx});
1287 StoreInst *NSI = Builder.CreateStore(NewElement, GEP);
1288 NSI->copyMetadata(*SI);
1289 Align ScalarOpAlignment = computeAlignmentAfterScalarization(
1290 std::max(SI->getAlign(), Load->getAlign()), NewElement->getType(), Idx,
1291 *DL);
1292 NSI->setAlignment(ScalarOpAlignment);
1293 replaceValue(I, *NSI);
1295 return true;
1296 }
1297
1298 return false;
1299}
1300
1301/// Try to scalarize vector loads feeding extractelement instructions.
1302bool VectorCombine::scalarizeLoadExtract(Instruction &I) {
1303 Value *Ptr;
1304 if (!match(&I, m_Load(m_Value(Ptr))))
1305 return false;
1306
1307 auto *VecTy = cast<VectorType>(I.getType());
1308 auto *LI = cast<LoadInst>(&I);
1309 if (LI->isVolatile() || !DL->typeSizeEqualsStoreSize(VecTy->getScalarType()))
1310 return false;
1311
1312 InstructionCost OriginalCost =
1313 TTI.getMemoryOpCost(Instruction::Load, VecTy, LI->getAlign(),
1314 LI->getPointerAddressSpace());
1315 InstructionCost ScalarizedCost = 0;
1316
1317 Instruction *LastCheckedInst = LI;
1318 unsigned NumInstChecked = 0;
1320 auto FailureGuard = make_scope_exit([&]() {
1321 // If the transform is aborted, discard the ScalarizationResults.
1322 for (auto &Pair : NeedFreeze)
1323 Pair.second.discard();
1324 });
1325
1326 // Check if all users of the load are extracts with no memory modifications
1327 // between the load and the extract. Compute the cost of both the original
1328 // code and the scalarized version.
1329 for (User *U : LI->users()) {
1330 auto *UI = dyn_cast<ExtractElementInst>(U);
1331 if (!UI || UI->getParent() != LI->getParent())
1332 return false;
1333
1334 // Check if any instruction between the load and the extract may modify
1335 // memory.
1336 if (LastCheckedInst->comesBefore(UI)) {
1337 for (Instruction &I :
1338 make_range(std::next(LI->getIterator()), UI->getIterator())) {
1339 // Bail out if we reached the check limit or the instruction may write
1340 // to memory.
1341 if (NumInstChecked == MaxInstrsToScan || I.mayWriteToMemory())
1342 return false;
1343 NumInstChecked++;
1344 }
1345 LastCheckedInst = UI;
1346 }
1347
1348 auto ScalarIdx = canScalarizeAccess(VecTy, UI->getOperand(1), &I, AC, DT);
1349 if (ScalarIdx.isUnsafe())
1350 return false;
1351 if (ScalarIdx.isSafeWithFreeze()) {
1352 NeedFreeze.try_emplace(UI, ScalarIdx);
1353 ScalarIdx.discard();
1354 }
1355
1356 auto *Index = dyn_cast<ConstantInt>(UI->getOperand(1));
1358 OriginalCost +=
1359 TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, CostKind,
1360 Index ? Index->getZExtValue() : -1);
1361 ScalarizedCost +=
1362 TTI.getMemoryOpCost(Instruction::Load, VecTy->getElementType(),
1363 Align(1), LI->getPointerAddressSpace());
1364 ScalarizedCost += TTI.getAddressComputationCost(VecTy->getElementType());
1365 }
1366
1367 if (ScalarizedCost >= OriginalCost)
1368 return false;
1369
1370 // Replace extracts with narrow scalar loads.
1371 for (User *U : LI->users()) {
1372 auto *EI = cast<ExtractElementInst>(U);
1373 Value *Idx = EI->getOperand(1);
1374
1375 // Insert 'freeze' for poison indexes.
1376 auto It = NeedFreeze.find(EI);
1377 if (It != NeedFreeze.end())
1378 It->second.freeze(Builder, *cast<Instruction>(Idx));
1379
1380 Builder.SetInsertPoint(EI);
1381 Value *GEP =
1382 Builder.CreateInBoundsGEP(VecTy, Ptr, {Builder.getInt32(0), Idx});
1383 auto *NewLoad = cast<LoadInst>(Builder.CreateLoad(
1384 VecTy->getElementType(), GEP, EI->getName() + ".scalar"));
1385
1386 Align ScalarOpAlignment = computeAlignmentAfterScalarization(
1387 LI->getAlign(), VecTy->getElementType(), Idx, *DL);
1388 NewLoad->setAlignment(ScalarOpAlignment);
1389
1390 replaceValue(*EI, *NewLoad);
1391 }
1392
1393 FailureGuard.release();
1394 return true;
1395}
1396
1397/// Try to convert "shuffle (binop), (binop)" with a shared binop operand into
1398/// "binop (shuffle), (shuffle)".
1399bool VectorCombine::foldShuffleOfBinops(Instruction &I) {
1400 auto *VecTy = cast<FixedVectorType>(I.getType());
1401 BinaryOperator *B0, *B1;
1403 if (!match(&I, m_Shuffle(m_OneUse(m_BinOp(B0)), m_OneUse(m_BinOp(B1)),
1404 m_Mask(Mask))) ||
1405 B0->getOpcode() != B1->getOpcode() || B0->getType() != VecTy)
1406 return false;
1407
1408 // Try to replace a binop with a shuffle if the shuffle is not costly.
1409 // The new shuffle will choose from a single, common operand, so it may be
1410 // cheaper than the existing two-operand shuffle.
1411 SmallVector<int> UnaryMask = createUnaryMask(Mask, Mask.size());
1412 Instruction::BinaryOps Opcode = B0->getOpcode();
1413 InstructionCost BinopCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
1416 if (ShufCost > BinopCost)
1417 return false;
1418
1419 // If we have something like "add X, Y" and "add Z, X", swap ops to match.
1420 Value *X = B0->getOperand(0), *Y = B0->getOperand(1);
1421 Value *Z = B1->getOperand(0), *W = B1->getOperand(1);
1422 if (BinaryOperator::isCommutative(Opcode) && X != Z && Y != W)
1423 std::swap(X, Y);
1424
1425 Value *Shuf0, *Shuf1;
1426 if (X == Z) {
1427 // shuf (bo X, Y), (bo X, W) --> bo (shuf X), (shuf Y, W)
1428 Shuf0 = Builder.CreateShuffleVector(X, UnaryMask);
1429 Shuf1 = Builder.CreateShuffleVector(Y, W, Mask);
1430 } else if (Y == W) {
1431 // shuf (bo X, Y), (bo Z, Y) --> bo (shuf X, Z), (shuf Y)
1432 Shuf0 = Builder.CreateShuffleVector(X, Z, Mask);
1433 Shuf1 = Builder.CreateShuffleVector(Y, UnaryMask);
1434 } else {
1435 return false;
1436 }
1437
1438 Value *NewBO = Builder.CreateBinOp(Opcode, Shuf0, Shuf1);
1439 // Intersect flags from the old binops.
1440 if (auto *NewInst = dyn_cast<Instruction>(NewBO)) {
1441 NewInst->copyIRFlags(B0);
1442 NewInst->andIRFlags(B1);
1443 }
1444
1445 // TODO: Add Shuf0/Shuf1 to WorkList?
1446 replaceValue(I, *NewBO);
1447 return true;
1448}
1449
1450/// Try to convert "shuffle (castop), (castop)" with a shared castop operand
1451/// into "castop (shuffle)".
1452bool VectorCombine::foldShuffleOfCastops(Instruction &I) {
1453 Value *V0, *V1;
1454 ArrayRef<int> OldMask;
1455 if (!match(&I, m_Shuffle(m_OneUse(m_Value(V0)), m_OneUse(m_Value(V1)),
1456 m_Mask(OldMask))))
1457 return false;
1458
1459 auto *C0 = dyn_cast<CastInst>(V0);
1460 auto *C1 = dyn_cast<CastInst>(V1);
1461 if (!C0 || !C1)
1462 return false;
1463
1464 Instruction::CastOps Opcode = C0->getOpcode();
1465 if (C0->getSrcTy() != C1->getSrcTy())
1466 return false;
1467
1468 // Handle shuffle(zext_nneg(x), sext(y)) -> sext(shuffle(x,y)) folds.
1469 if (Opcode != C1->getOpcode()) {
1470 if (match(C0, m_SExtLike(m_Value())) && match(C1, m_SExtLike(m_Value())))
1471 Opcode = Instruction::SExt;
1472 else
1473 return false;
1474 }
1475
1476 auto *ShuffleDstTy = dyn_cast<FixedVectorType>(I.getType());
1477 auto *CastDstTy = dyn_cast<FixedVectorType>(C0->getDestTy());
1478 auto *CastSrcTy = dyn_cast<FixedVectorType>(C0->getSrcTy());
1479 if (!ShuffleDstTy || !CastDstTy || !CastSrcTy)
1480 return false;
1481
1482 unsigned NumSrcElts = CastSrcTy->getNumElements();
1483 unsigned NumDstElts = CastDstTy->getNumElements();
1484 assert((NumDstElts == NumSrcElts || Opcode == Instruction::BitCast) &&
1485 "Only bitcasts expected to alter src/dst element counts");
1486
1487 // Check for bitcasting of unscalable vector types.
1488 // e.g. <32 x i40> -> <40 x i32>
1489 if (NumDstElts != NumSrcElts && (NumSrcElts % NumDstElts) != 0 &&
1490 (NumDstElts % NumSrcElts) != 0)
1491 return false;
1492
1493 SmallVector<int, 16> NewMask;
1494 if (NumSrcElts >= NumDstElts) {
1495 // The bitcast is from wide to narrow/equal elements. The shuffle mask can
1496 // always be expanded to the equivalent form choosing narrower elements.
1497 assert(NumSrcElts % NumDstElts == 0 && "Unexpected shuffle mask");
1498 unsigned ScaleFactor = NumSrcElts / NumDstElts;
1499 narrowShuffleMaskElts(ScaleFactor, OldMask, NewMask);
1500 } else {
1501 // The bitcast is from narrow elements to wide elements. The shuffle mask
1502 // must choose consecutive elements to allow casting first.
1503 assert(NumDstElts % NumSrcElts == 0 && "Unexpected shuffle mask");
1504 unsigned ScaleFactor = NumDstElts / NumSrcElts;
1505 if (!widenShuffleMaskElts(ScaleFactor, OldMask, NewMask))
1506 return false;
1507 }
1508
1509 auto *NewShuffleDstTy =
1510 FixedVectorType::get(CastSrcTy->getScalarType(), NewMask.size());
1511
1512 // Try to replace a castop with a shuffle if the shuffle is not costly.
1514
1515 InstructionCost OldCost =
1516 TTI.getCastInstrCost(C0->getOpcode(), CastDstTy, CastSrcTy,
1518 TTI.getCastInstrCost(C1->getOpcode(), CastDstTy, CastSrcTy,
1520 OldCost +=
1522 OldMask, CostKind, 0, nullptr, std::nullopt, &I);
1523
1525 TargetTransformInfo::SK_PermuteTwoSrc, CastSrcTy, NewMask, CostKind);
1526 NewCost += TTI.getCastInstrCost(Opcode, ShuffleDstTy, NewShuffleDstTy,
1528
1529 LLVM_DEBUG(dbgs() << "Found a shuffle feeding two casts: " << I
1530 << "\n OldCost: " << OldCost << " vs NewCost: " << NewCost
1531 << "\n");
1532 if (NewCost > OldCost)
1533 return false;
1534
1535 Value *Shuf = Builder.CreateShuffleVector(C0->getOperand(0),
1536 C1->getOperand(0), NewMask);
1537 Value *Cast = Builder.CreateCast(Opcode, Shuf, ShuffleDstTy);
1538
1539 // Intersect flags from the old casts.
1540 if (auto *NewInst = dyn_cast<Instruction>(Cast)) {
1541 NewInst->copyIRFlags(C0);
1542 NewInst->andIRFlags(C1);
1543 }
1544
1545 Worklist.pushValue(Shuf);
1546 replaceValue(I, *Cast);
1547 return true;
1548}
1549
1550/// Given a commutative reduction, the order of the input lanes does not alter
1551/// the results. We can use this to remove certain shuffles feeding the
1552/// reduction, removing the need to shuffle at all.
1553bool VectorCombine::foldShuffleFromReductions(Instruction &I) {
1554 auto *II = dyn_cast<IntrinsicInst>(&I);
1555 if (!II)
1556 return false;
1557 switch (II->getIntrinsicID()) {
1558 case Intrinsic::vector_reduce_add:
1559 case Intrinsic::vector_reduce_mul:
1560 case Intrinsic::vector_reduce_and:
1561 case Intrinsic::vector_reduce_or:
1562 case Intrinsic::vector_reduce_xor:
1563 case Intrinsic::vector_reduce_smin:
1564 case Intrinsic::vector_reduce_smax:
1565 case Intrinsic::vector_reduce_umin:
1566 case Intrinsic::vector_reduce_umax:
1567 break;
1568 default:
1569 return false;
1570 }
1571
1572 // Find all the inputs when looking through operations that do not alter the
1573 // lane order (binops, for example). Currently we look for a single shuffle,
1574 // and can ignore splat values.
1575 std::queue<Value *> Worklist;
1577 ShuffleVectorInst *Shuffle = nullptr;
1578 if (auto *Op = dyn_cast<Instruction>(I.getOperand(0)))
1579 Worklist.push(Op);
1580
1581 while (!Worklist.empty()) {
1582 Value *CV = Worklist.front();
1583 Worklist.pop();
1584 if (Visited.contains(CV))
1585 continue;
1586
1587 // Splats don't change the order, so can be safely ignored.
1588 if (isSplatValue(CV))
1589 continue;
1590
1591 Visited.insert(CV);
1592
1593 if (auto *CI = dyn_cast<Instruction>(CV)) {
1594 if (CI->isBinaryOp()) {
1595 for (auto *Op : CI->operand_values())
1596 Worklist.push(Op);
1597 continue;
1598 } else if (auto *SV = dyn_cast<ShuffleVectorInst>(CI)) {
1599 if (Shuffle && Shuffle != SV)
1600 return false;
1601 Shuffle = SV;
1602 continue;
1603 }
1604 }
1605
1606 // Anything else is currently an unknown node.
1607 return false;
1608 }
1609
1610 if (!Shuffle)
1611 return false;
1612
1613 // Check all uses of the binary ops and shuffles are also included in the
1614 // lane-invariant operations (Visited should be the list of lanewise
1615 // instructions, including the shuffle that we found).
1616 for (auto *V : Visited)
1617 for (auto *U : V->users())
1618 if (!Visited.contains(U) && U != &I)
1619 return false;
1620
1622 dyn_cast<FixedVectorType>(II->getOperand(0)->getType());
1623 if (!VecType)
1624 return false;
1625 FixedVectorType *ShuffleInputType =
1626 dyn_cast<FixedVectorType>(Shuffle->getOperand(0)->getType());
1627 if (!ShuffleInputType)
1628 return false;
1629 unsigned NumInputElts = ShuffleInputType->getNumElements();
1630
1631 // Find the mask from sorting the lanes into order. This is most likely to
1632 // become a identity or concat mask. Undef elements are pushed to the end.
1633 SmallVector<int> ConcatMask;
1634 Shuffle->getShuffleMask(ConcatMask);
1635 sort(ConcatMask, [](int X, int Y) { return (unsigned)X < (unsigned)Y; });
1636 // In the case of a truncating shuffle it's possible for the mask
1637 // to have an index greater than the size of the resulting vector.
1638 // This requires special handling.
1639 bool IsTruncatingShuffle = VecType->getNumElements() < NumInputElts;
1640 bool UsesSecondVec =
1641 any_of(ConcatMask, [&](int M) { return M >= (int)NumInputElts; });
1642
1643 FixedVectorType *VecTyForCost =
1644 (UsesSecondVec && !IsTruncatingShuffle) ? VecType : ShuffleInputType;
1647 VecTyForCost, Shuffle->getShuffleMask());
1650 VecTyForCost, ConcatMask);
1651
1652 LLVM_DEBUG(dbgs() << "Found a reduction feeding from a shuffle: " << *Shuffle
1653 << "\n");
1654 LLVM_DEBUG(dbgs() << " OldCost: " << OldCost << " vs NewCost: " << NewCost
1655 << "\n");
1656 if (NewCost < OldCost) {
1657 Builder.SetInsertPoint(Shuffle);
1658 Value *NewShuffle = Builder.CreateShuffleVector(
1659 Shuffle->getOperand(0), Shuffle->getOperand(1), ConcatMask);
1660 LLVM_DEBUG(dbgs() << "Created new shuffle: " << *NewShuffle << "\n");
1661 replaceValue(*Shuffle, *NewShuffle);
1662 }
1663
1664 // See if we can re-use foldSelectShuffle, getting it to reduce the size of
1665 // the shuffle into a nicer order, as it can ignore the order of the shuffles.
1666 return foldSelectShuffle(*Shuffle, true);
1667}
1668
1669/// Determine if its more efficient to fold:
1670/// reduce(trunc(x)) -> trunc(reduce(x)).
1671bool VectorCombine::foldTruncFromReductions(Instruction &I) {
1672 auto *II = dyn_cast<IntrinsicInst>(&I);
1673 if (!II)
1674 return false;
1675
1676 Intrinsic::ID IID = II->getIntrinsicID();
1677 switch (IID) {
1678 case Intrinsic::vector_reduce_add:
1679 case Intrinsic::vector_reduce_mul:
1680 case Intrinsic::vector_reduce_and:
1681 case Intrinsic::vector_reduce_or:
1682 case Intrinsic::vector_reduce_xor:
1683 break;
1684 default:
1685 return false;
1686 }
1687
1688 unsigned ReductionOpc = getArithmeticReductionInstruction(IID);
1689 Value *ReductionSrc = I.getOperand(0);
1690
1691 Value *TruncSrc;
1692 if (!match(ReductionSrc, m_OneUse(m_Trunc(m_Value(TruncSrc)))))
1693 return false;
1694
1695 auto *Trunc = cast<CastInst>(ReductionSrc);
1696 auto *TruncSrcTy = cast<VectorType>(TruncSrc->getType());
1697 auto *ReductionSrcTy = cast<VectorType>(ReductionSrc->getType());
1698 Type *ResultTy = I.getType();
1699
1701 InstructionCost OldCost =
1702 TTI.getCastInstrCost(Instruction::Trunc, ReductionSrcTy, TruncSrcTy,
1704 TTI.getArithmeticReductionCost(ReductionOpc, ReductionSrcTy, std::nullopt,
1705 CostKind);
1706 InstructionCost NewCost =
1707 TTI.getArithmeticReductionCost(ReductionOpc, TruncSrcTy, std::nullopt,
1708 CostKind) +
1709 TTI.getCastInstrCost(Instruction::Trunc, ResultTy,
1710 ReductionSrcTy->getScalarType(),
1712
1713 if (OldCost <= NewCost || !NewCost.isValid())
1714 return false;
1715
1716 Value *NewReduction = Builder.CreateIntrinsic(
1717 TruncSrcTy->getScalarType(), II->getIntrinsicID(), {TruncSrc});
1718 Value *NewTruncation = Builder.CreateTrunc(NewReduction, ResultTy);
1719 replaceValue(I, *NewTruncation);
1720 return true;
1721}
1722
1723/// This method looks for groups of shuffles acting on binops, of the form:
1724/// %x = shuffle ...
1725/// %y = shuffle ...
1726/// %a = binop %x, %y
1727/// %b = binop %x, %y
1728/// shuffle %a, %b, selectmask
1729/// We may, especially if the shuffle is wider than legal, be able to convert
1730/// the shuffle to a form where only parts of a and b need to be computed. On
1731/// architectures with no obvious "select" shuffle, this can reduce the total
1732/// number of operations if the target reports them as cheaper.
1733bool VectorCombine::foldSelectShuffle(Instruction &I, bool FromReduction) {
1734 auto *SVI = cast<ShuffleVectorInst>(&I);
1735 auto *VT = cast<FixedVectorType>(I.getType());
1736 auto *Op0 = dyn_cast<Instruction>(SVI->getOperand(0));
1737 auto *Op1 = dyn_cast<Instruction>(SVI->getOperand(1));
1738 if (!Op0 || !Op1 || Op0 == Op1 || !Op0->isBinaryOp() || !Op1->isBinaryOp() ||
1739 VT != Op0->getType())
1740 return false;
1741
1742 auto *SVI0A = dyn_cast<Instruction>(Op0->getOperand(0));
1743 auto *SVI0B = dyn_cast<Instruction>(Op0->getOperand(1));
1744 auto *SVI1A = dyn_cast<Instruction>(Op1->getOperand(0));
1745 auto *SVI1B = dyn_cast<Instruction>(Op1->getOperand(1));
1746 SmallPtrSet<Instruction *, 4> InputShuffles({SVI0A, SVI0B, SVI1A, SVI1B});
1747 auto checkSVNonOpUses = [&](Instruction *I) {
1748 if (!I || I->getOperand(0)->getType() != VT)
1749 return true;
1750 return any_of(I->users(), [&](User *U) {
1751 return U != Op0 && U != Op1 &&
1752 !(isa<ShuffleVectorInst>(U) &&
1753 (InputShuffles.contains(cast<Instruction>(U)) ||
1754 isInstructionTriviallyDead(cast<Instruction>(U))));
1755 });
1756 };
1757 if (checkSVNonOpUses(SVI0A) || checkSVNonOpUses(SVI0B) ||
1758 checkSVNonOpUses(SVI1A) || checkSVNonOpUses(SVI1B))
1759 return false;
1760
1761 // Collect all the uses that are shuffles that we can transform together. We
1762 // may not have a single shuffle, but a group that can all be transformed
1763 // together profitably.
1765 auto collectShuffles = [&](Instruction *I) {
1766 for (auto *U : I->users()) {
1767 auto *SV = dyn_cast<ShuffleVectorInst>(U);
1768 if (!SV || SV->getType() != VT)
1769 return false;
1770 if ((SV->getOperand(0) != Op0 && SV->getOperand(0) != Op1) ||
1771 (SV->getOperand(1) != Op0 && SV->getOperand(1) != Op1))
1772 return false;
1773 if (!llvm::is_contained(Shuffles, SV))
1774 Shuffles.push_back(SV);
1775 }
1776 return true;
1777 };
1778 if (!collectShuffles(Op0) || !collectShuffles(Op1))
1779 return false;
1780 // From a reduction, we need to be processing a single shuffle, otherwise the
1781 // other uses will not be lane-invariant.
1782 if (FromReduction && Shuffles.size() > 1)
1783 return false;
1784
1785 // Add any shuffle uses for the shuffles we have found, to include them in our
1786 // cost calculations.
1787 if (!FromReduction) {
1788 for (ShuffleVectorInst *SV : Shuffles) {
1789 for (auto *U : SV->users()) {
1790 ShuffleVectorInst *SSV = dyn_cast<ShuffleVectorInst>(U);
1791 if (SSV && isa<UndefValue>(SSV->getOperand(1)) && SSV->getType() == VT)
1792 Shuffles.push_back(SSV);
1793 }
1794 }
1795 }
1796
1797 // For each of the output shuffles, we try to sort all the first vector
1798 // elements to the beginning, followed by the second array elements at the
1799 // end. If the binops are legalized to smaller vectors, this may reduce total
1800 // number of binops. We compute the ReconstructMask mask needed to convert
1801 // back to the original lane order.
1803 SmallVector<SmallVector<int>> OrigReconstructMasks;
1804 int MaxV1Elt = 0, MaxV2Elt = 0;
1805 unsigned NumElts = VT->getNumElements();
1806 for (ShuffleVectorInst *SVN : Shuffles) {
1808 SVN->getShuffleMask(Mask);
1809
1810 // Check the operands are the same as the original, or reversed (in which
1811 // case we need to commute the mask).
1812 Value *SVOp0 = SVN->getOperand(0);
1813 Value *SVOp1 = SVN->getOperand(1);
1814 if (isa<UndefValue>(SVOp1)) {
1815 auto *SSV = cast<ShuffleVectorInst>(SVOp0);
1816 SVOp0 = SSV->getOperand(0);
1817 SVOp1 = SSV->getOperand(1);
1818 for (unsigned I = 0, E = Mask.size(); I != E; I++) {
1819 if (Mask[I] >= static_cast<int>(SSV->getShuffleMask().size()))
1820 return false;
1821 Mask[I] = Mask[I] < 0 ? Mask[I] : SSV->getMaskValue(Mask[I]);
1822 }
1823 }
1824 if (SVOp0 == Op1 && SVOp1 == Op0) {
1825 std::swap(SVOp0, SVOp1);
1827 }
1828 if (SVOp0 != Op0 || SVOp1 != Op1)
1829 return false;
1830
1831 // Calculate the reconstruction mask for this shuffle, as the mask needed to
1832 // take the packed values from Op0/Op1 and reconstructing to the original
1833 // order.
1834 SmallVector<int> ReconstructMask;
1835 for (unsigned I = 0; I < Mask.size(); I++) {
1836 if (Mask[I] < 0) {
1837 ReconstructMask.push_back(-1);
1838 } else if (Mask[I] < static_cast<int>(NumElts)) {
1839 MaxV1Elt = std::max(MaxV1Elt, Mask[I]);
1840 auto It = find_if(V1, [&](const std::pair<int, int> &A) {
1841 return Mask[I] == A.first;
1842 });
1843 if (It != V1.end())
1844 ReconstructMask.push_back(It - V1.begin());
1845 else {
1846 ReconstructMask.push_back(V1.size());
1847 V1.emplace_back(Mask[I], V1.size());
1848 }
1849 } else {
1850 MaxV2Elt = std::max<int>(MaxV2Elt, Mask[I] - NumElts);
1851 auto It = find_if(V2, [&](const std::pair<int, int> &A) {
1852 return Mask[I] - static_cast<int>(NumElts) == A.first;
1853 });
1854 if (It != V2.end())
1855 ReconstructMask.push_back(NumElts + It - V2.begin());
1856 else {
1857 ReconstructMask.push_back(NumElts + V2.size());
1858 V2.emplace_back(Mask[I] - NumElts, NumElts + V2.size());
1859 }
1860 }
1861 }
1862
1863 // For reductions, we know that the lane ordering out doesn't alter the
1864 // result. In-order can help simplify the shuffle away.
1865 if (FromReduction)
1866 sort(ReconstructMask);
1867 OrigReconstructMasks.push_back(std::move(ReconstructMask));
1868 }
1869
1870 // If the Maximum element used from V1 and V2 are not larger than the new
1871 // vectors, the vectors are already packes and performing the optimization
1872 // again will likely not help any further. This also prevents us from getting
1873 // stuck in a cycle in case the costs do not also rule it out.
1874 if (V1.empty() || V2.empty() ||
1875 (MaxV1Elt == static_cast<int>(V1.size()) - 1 &&
1876 MaxV2Elt == static_cast<int>(V2.size()) - 1))
1877 return false;
1878
1879 // GetBaseMaskValue takes one of the inputs, which may either be a shuffle, a
1880 // shuffle of another shuffle, or not a shuffle (that is treated like a
1881 // identity shuffle).
1882 auto GetBaseMaskValue = [&](Instruction *I, int M) {
1883 auto *SV = dyn_cast<ShuffleVectorInst>(I);
1884 if (!SV)
1885 return M;
1886 if (isa<UndefValue>(SV->getOperand(1)))
1887 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
1888 if (InputShuffles.contains(SSV))
1889 return SSV->getMaskValue(SV->getMaskValue(M));
1890 return SV->getMaskValue(M);
1891 };
1892
1893 // Attempt to sort the inputs my ascending mask values to make simpler input
1894 // shuffles and push complex shuffles down to the uses. We sort on the first
1895 // of the two input shuffle orders, to try and get at least one input into a
1896 // nice order.
1897 auto SortBase = [&](Instruction *A, std::pair<int, int> X,
1898 std::pair<int, int> Y) {
1899 int MXA = GetBaseMaskValue(A, X.first);
1900 int MYA = GetBaseMaskValue(A, Y.first);
1901 return MXA < MYA;
1902 };
1903 stable_sort(V1, [&](std::pair<int, int> A, std::pair<int, int> B) {
1904 return SortBase(SVI0A, A, B);
1905 });
1906 stable_sort(V2, [&](std::pair<int, int> A, std::pair<int, int> B) {
1907 return SortBase(SVI1A, A, B);
1908 });
1909 // Calculate our ReconstructMasks from the OrigReconstructMasks and the
1910 // modified order of the input shuffles.
1911 SmallVector<SmallVector<int>> ReconstructMasks;
1912 for (const auto &Mask : OrigReconstructMasks) {
1913 SmallVector<int> ReconstructMask;
1914 for (int M : Mask) {
1915 auto FindIndex = [](const SmallVector<std::pair<int, int>> &V, int M) {
1916 auto It = find_if(V, [M](auto A) { return A.second == M; });
1917 assert(It != V.end() && "Expected all entries in Mask");
1918 return std::distance(V.begin(), It);
1919 };
1920 if (M < 0)
1921 ReconstructMask.push_back(-1);
1922 else if (M < static_cast<int>(NumElts)) {
1923 ReconstructMask.push_back(FindIndex(V1, M));
1924 } else {
1925 ReconstructMask.push_back(NumElts + FindIndex(V2, M));
1926 }
1927 }
1928 ReconstructMasks.push_back(std::move(ReconstructMask));
1929 }
1930
1931 // Calculate the masks needed for the new input shuffles, which get padded
1932 // with undef
1933 SmallVector<int> V1A, V1B, V2A, V2B;
1934 for (unsigned I = 0; I < V1.size(); I++) {
1935 V1A.push_back(GetBaseMaskValue(SVI0A, V1[I].first));
1936 V1B.push_back(GetBaseMaskValue(SVI0B, V1[I].first));
1937 }
1938 for (unsigned I = 0; I < V2.size(); I++) {
1939 V2A.push_back(GetBaseMaskValue(SVI1A, V2[I].first));
1940 V2B.push_back(GetBaseMaskValue(SVI1B, V2[I].first));
1941 }
1942 while (V1A.size() < NumElts) {
1945 }
1946 while (V2A.size() < NumElts) {
1949 }
1950
1951 auto AddShuffleCost = [&](InstructionCost C, Instruction *I) {
1952 auto *SV = dyn_cast<ShuffleVectorInst>(I);
1953 if (!SV)
1954 return C;
1955 return C + TTI.getShuffleCost(isa<UndefValue>(SV->getOperand(1))
1958 VT, SV->getShuffleMask());
1959 };
1960 auto AddShuffleMaskCost = [&](InstructionCost C, ArrayRef<int> Mask) {
1961 return C + TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, VT, Mask);
1962 };
1963
1964 // Get the costs of the shuffles + binops before and after with the new
1965 // shuffle masks.
1966 InstructionCost CostBefore =
1967 TTI.getArithmeticInstrCost(Op0->getOpcode(), VT) +
1968 TTI.getArithmeticInstrCost(Op1->getOpcode(), VT);
1969 CostBefore += std::accumulate(Shuffles.begin(), Shuffles.end(),
1970 InstructionCost(0), AddShuffleCost);
1971 CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(),
1972 InstructionCost(0), AddShuffleCost);
1973
1974 // The new binops will be unused for lanes past the used shuffle lengths.
1975 // These types attempt to get the correct cost for that from the target.
1976 FixedVectorType *Op0SmallVT =
1977 FixedVectorType::get(VT->getScalarType(), V1.size());
1978 FixedVectorType *Op1SmallVT =
1979 FixedVectorType::get(VT->getScalarType(), V2.size());
1980 InstructionCost CostAfter =
1981 TTI.getArithmeticInstrCost(Op0->getOpcode(), Op0SmallVT) +
1982 TTI.getArithmeticInstrCost(Op1->getOpcode(), Op1SmallVT);
1983 CostAfter += std::accumulate(ReconstructMasks.begin(), ReconstructMasks.end(),
1984 InstructionCost(0), AddShuffleMaskCost);
1985 std::set<SmallVector<int>> OutputShuffleMasks({V1A, V1B, V2A, V2B});
1986 CostAfter +=
1987 std::accumulate(OutputShuffleMasks.begin(), OutputShuffleMasks.end(),
1988 InstructionCost(0), AddShuffleMaskCost);
1989
1990 LLVM_DEBUG(dbgs() << "Found a binop select shuffle pattern: " << I << "\n");
1991 LLVM_DEBUG(dbgs() << " CostBefore: " << CostBefore
1992 << " vs CostAfter: " << CostAfter << "\n");
1993 if (CostBefore <= CostAfter)
1994 return false;
1995
1996 // The cost model has passed, create the new instructions.
1997 auto GetShuffleOperand = [&](Instruction *I, unsigned Op) -> Value * {
1998 auto *SV = dyn_cast<ShuffleVectorInst>(I);
1999 if (!SV)
2000 return I;
2001 if (isa<UndefValue>(SV->getOperand(1)))
2002 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
2003 if (InputShuffles.contains(SSV))
2004 return SSV->getOperand(Op);
2005 return SV->getOperand(Op);
2006 };
2007 Builder.SetInsertPoint(*SVI0A->getInsertionPointAfterDef());
2008 Value *NSV0A = Builder.CreateShuffleVector(GetShuffleOperand(SVI0A, 0),
2009 GetShuffleOperand(SVI0A, 1), V1A);
2010 Builder.SetInsertPoint(*SVI0B->getInsertionPointAfterDef());
2011 Value *NSV0B = Builder.CreateShuffleVector(GetShuffleOperand(SVI0B, 0),
2012 GetShuffleOperand(SVI0B, 1), V1B);
2013 Builder.SetInsertPoint(*SVI1A->getInsertionPointAfterDef());
2014 Value *NSV1A = Builder.CreateShuffleVector(GetShuffleOperand(SVI1A, 0),
2015 GetShuffleOperand(SVI1A, 1), V2A);
2016 Builder.SetInsertPoint(*SVI1B->getInsertionPointAfterDef());
2017 Value *NSV1B = Builder.CreateShuffleVector(GetShuffleOperand(SVI1B, 0),
2018 GetShuffleOperand(SVI1B, 1), V2B);
2019 Builder.SetInsertPoint(Op0);
2020 Value *NOp0 = Builder.CreateBinOp((Instruction::BinaryOps)Op0->getOpcode(),
2021 NSV0A, NSV0B);
2022 if (auto *I = dyn_cast<Instruction>(NOp0))
2023 I->copyIRFlags(Op0, true);
2024 Builder.SetInsertPoint(Op1);
2025 Value *NOp1 = Builder.CreateBinOp((Instruction::BinaryOps)Op1->getOpcode(),
2026 NSV1A, NSV1B);
2027 if (auto *I = dyn_cast<Instruction>(NOp1))
2028 I->copyIRFlags(Op1, true);
2029
2030 for (int S = 0, E = ReconstructMasks.size(); S != E; S++) {
2031 Builder.SetInsertPoint(Shuffles[S]);
2032 Value *NSV = Builder.CreateShuffleVector(NOp0, NOp1, ReconstructMasks[S]);
2033 replaceValue(*Shuffles[S], *NSV);
2034 }
2035
2036 Worklist.pushValue(NSV0A);
2037 Worklist.pushValue(NSV0B);
2038 Worklist.pushValue(NSV1A);
2039 Worklist.pushValue(NSV1B);
2040 for (auto *S : Shuffles)
2041 Worklist.add(S);
2042 return true;
2043}
2044
2045/// This is the entry point for all transforms. Pass manager differences are
2046/// handled in the callers of this function.
2047bool VectorCombine::run() {
2049 return false;
2050
2051 // Don't attempt vectorization if the target does not support vectors.
2052 if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
2053 return false;
2054
2055 bool MadeChange = false;
2056 auto FoldInst = [this, &MadeChange](Instruction &I) {
2057 Builder.SetInsertPoint(&I);
2058 bool IsFixedVectorType = isa<FixedVectorType>(I.getType());
2059 auto Opcode = I.getOpcode();
2060
2061 // These folds should be beneficial regardless of when this pass is run
2062 // in the optimization pipeline.
2063 // The type checking is for run-time efficiency. We can avoid wasting time
2064 // dispatching to folding functions if there's no chance of matching.
2065 if (IsFixedVectorType) {
2066 switch (Opcode) {
2067 case Instruction::InsertElement:
2068 MadeChange |= vectorizeLoadInsert(I);
2069 break;
2070 case Instruction::ShuffleVector:
2071 MadeChange |= widenSubvectorLoad(I);
2072 break;
2073 default:
2074 break;
2075 }
2076 }
2077
2078 // This transform works with scalable and fixed vectors
2079 // TODO: Identify and allow other scalable transforms
2080 if (isa<VectorType>(I.getType())) {
2081 MadeChange |= scalarizeBinopOrCmp(I);
2082 MadeChange |= scalarizeLoadExtract(I);
2083 MadeChange |= scalarizeVPIntrinsic(I);
2084 }
2085
2086 if (Opcode == Instruction::Store)
2087 MadeChange |= foldSingleElementStore(I);
2088
2089 // If this is an early pipeline invocation of this pass, we are done.
2090 if (TryEarlyFoldsOnly)
2091 return;
2092
2093 // Otherwise, try folds that improve codegen but may interfere with
2094 // early IR canonicalizations.
2095 // The type checking is for run-time efficiency. We can avoid wasting time
2096 // dispatching to folding functions if there's no chance of matching.
2097 if (IsFixedVectorType) {
2098 switch (Opcode) {
2099 case Instruction::InsertElement:
2100 MadeChange |= foldInsExtFNeg(I);
2101 break;
2102 case Instruction::ShuffleVector:
2103 MadeChange |= foldShuffleOfBinops(I);
2104 MadeChange |= foldShuffleOfCastops(I);
2105 MadeChange |= foldSelectShuffle(I);
2106 break;
2107 case Instruction::BitCast:
2108 MadeChange |= foldBitcastShuffle(I);
2109 break;
2110 }
2111 } else {
2112 switch (Opcode) {
2113 case Instruction::Call:
2114 MadeChange |= foldShuffleFromReductions(I);
2115 MadeChange |= foldTruncFromReductions(I);
2116 break;
2117 case Instruction::ICmp:
2118 case Instruction::FCmp:
2119 MadeChange |= foldExtractExtract(I);
2120 break;
2121 default:
2122 if (Instruction::isBinaryOp(Opcode)) {
2123 MadeChange |= foldExtractExtract(I);
2124 MadeChange |= foldExtractedCmps(I);
2125 }
2126 break;
2127 }
2128 }
2129 };
2130
2131 for (BasicBlock &BB : F) {
2132 // Ignore unreachable basic blocks.
2133 if (!DT.isReachableFromEntry(&BB))
2134 continue;
2135 // Use early increment range so that we can erase instructions in loop.
2136 for (Instruction &I : make_early_inc_range(BB)) {
2137 if (I.isDebugOrPseudoInst())
2138 continue;
2139 FoldInst(I);
2140 }
2141 }
2142
2143 while (!Worklist.isEmpty()) {
2144 Instruction *I = Worklist.removeOne();
2145 if (!I)
2146 continue;
2147
2150 continue;
2151 }
2152
2153 FoldInst(*I);
2154 }
2155
2156 return MadeChange;
2157}
2158
2161 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
2165 const DataLayout *DL = &F.getParent()->getDataLayout();
2166 VectorCombine Combiner(F, TTI, DT, AA, AC, DL, TryEarlyFoldsOnly);
2167 if (!Combiner.run())
2168 return PreservedAnalyses::all();
2171 return PA;
2172}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
This is the interface for LLVM's primary stateless and local alias analysis.
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static cl::opt< TargetTransformInfo::TargetCostKind > CostKind("cost-kind", cl::desc("Target cost kind"), cl::init(TargetTransformInfo::TCK_RecipThroughput), cl::values(clEnumValN(TargetTransformInfo::TCK_RecipThroughput, "throughput", "Reciprocal throughput"), clEnumValN(TargetTransformInfo::TCK_Latency, "latency", "Instruction latency"), clEnumValN(TargetTransformInfo::TCK_CodeSize, "code-size", "Code size"), clEnumValN(TargetTransformInfo::TCK_SizeAndLatency, "size-latency", "Code size and latency")))
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
#define LLVM_DEBUG(X)
Definition: Debug.h:101
This file defines the DenseMap class.
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1291
bool End
Definition: ELF_riscv.cpp:480
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This is the interface for a simple mod/ref and alias analysis over globals.
Hexagon Common GEP
static void eraseInstruction(Instruction &I, ICFLoopSafetyInfo &SafetyInfo, MemorySSAUpdater &MSSAU)
Definition: LICM.cpp:1497
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static GCMetadataPrinterRegistry::Add< OcamlGCMetadataPrinter > Y("ocaml", "ocaml 3.10-compatible collector")
FunctionAnalysisManager FAM
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned OpIndex
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
static SymbolRef::Type getType(const Symbol *Sym)
Definition: TapiFile.cpp:40
This pass exposes codegen information to IR-level passes.
static std::optional< unsigned > getOpcode(ArrayRef< VPValue * > Values)
Returns the opcode of Values or ~0 if they do not all agree.
Definition: VPlanSLP.cpp:191
static Value * createShiftShuffle(Value *Vec, unsigned OldIndex, unsigned NewIndex, IRBuilder<> &Builder)
Create a shuffle that translates (shifts) 1 element from the input vector to a new element location.
static Value * peekThroughBitcasts(Value *V)
Return the source operand of a potentially bitcasted value.
static Align computeAlignmentAfterScalarization(Align VectorAlignment, Type *ScalarType, Value *Idx, const DataLayout &DL)
The memory operation on a vector of ScalarType had alignment of VectorAlignment.
static ScalarizationResult canScalarizeAccess(VectorType *VecTy, Value *Idx, Instruction *CtxI, AssumptionCache &AC, const DominatorTree &DT)
Check if it is legal to scalarize a memory access to VecTy at index Idx.
static cl::opt< bool > DisableVectorCombine("disable-vector-combine", cl::init(false), cl::Hidden, cl::desc("Disable all vector combine transforms"))
static bool canWidenLoad(LoadInst *Load, const TargetTransformInfo &TTI)
static const unsigned InvalidIndex
static cl::opt< unsigned > MaxInstrsToScan("vector-combine-max-scan-instrs", cl::init(30), cl::Hidden, cl::desc("Max number of instructions to scan for vector combining."))
static cl::opt< bool > DisableBinopExtractShuffle("disable-binop-extract-shuffle", cl::init(false), cl::Hidden, cl::desc("Disable binop extract to shuffle transforms"))
static bool isMemModifiedBetween(BasicBlock::iterator Begin, BasicBlock::iterator End, const MemoryLocation &Loc, AAResults &AA)
static ExtractElementInst * translateExtract(ExtractElementInst *ExtElt, unsigned NewIndex, IRBuilder<> &Builder)
Given an extract element instruction with constant index operand, shuffle the source vector (shift th...
A manager for alias analyses.
ModRefInfo getModRefInfo(const Instruction *I, const std::optional< MemoryLocation > &OptLoc)
Check whether or not an instruction may read or write the optionally specified memory location.
Class for arbitrary precision integers.
Definition: APInt.h:76
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
Definition: APInt.h:217
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:321
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:473
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
bool hasFnAttr(Attribute::AttrKind Kind) const
Return true if the attribute exists for the function.
LLVM Basic Block Representation.
Definition: BasicBlock.h:60
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:165
BinaryOps getOpcode() const
Definition: InstrTypes.h:486
Represents analyses that only rely on functions' control flow.
Definition: Analysis.h:70
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1660
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
Definition: InstrTypes.h:1651
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:1335
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:966
bool isFPPredicate() const
Definition: InstrTypes.h:1095
Combiner implementation.
Definition: Combiner.h:34
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2452
This is the shared class of boolean and integer constants.
Definition: Constants.h:80
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:145
This class represents a range of values.
Definition: ConstantRange.h:47
ConstantRange urem(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an unsigned remainder operation of...
ConstantRange binaryAnd(const ConstantRange &Other) const
Return a new range representing the possible values resulting from a binary-and of a value in this ra...
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
static Constant * get(ArrayRef< Constant * > V)
Definition: Constants.cpp:1398
This is an important base class in LLVM.
Definition: Constant.h:41
This class represents an Operation in the Expression.
A parsed version of the target data layout string in and methods for querying it.
Definition: DataLayout.h:110
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:155
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
Definition: DenseMap.h:235
iterator end()
Definition: DenseMap.h:84
Analysis pass which computes a DominatorTree.
Definition: Dominators.h:279
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
Definition: Dominators.h:162
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Definition: Dominators.cpp:321
This instruction extracts a single (scalar) element from a VectorType value.
Class to represent fixed width SIMD vectors.
Definition: DerivedTypes.h:539
unsigned getNumElements() const
Definition: DerivedTypes.h:582
static FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition: Type.cpp:692
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2007
Value * CreateInsertElement(Type *VecTy, Value *NewElt, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2462
Value * CreateExtractElement(Value *Vec, Value *Idx, const Twine &Name="")
Definition: IRBuilder.h:2450
LoadInst * CreateAlignedLoad(Type *Ty, Value *Ptr, MaybeAlign Align, const char *Name)
Definition: IRBuilder.h:1807
Value * CreateVectorSplat(unsigned NumElts, Value *V, const Twine &Name="")
Return a vector value that contains.
Definition: IRBuilder.cpp:1214
CallInst * CreateIntrinsic(Intrinsic::ID ID, ArrayRef< Type * > Types, ArrayRef< Value * > Args, Instruction *FMFSource=nullptr, const Twine &Name="")
Create a call to intrinsic ID with Args, mangled using Types.
Definition: IRBuilder.cpp:932
Value * CreateFNegFMF(Value *V, Instruction *FMFSource, const Twine &Name="")
Copy fast-math-flags from an instruction rather than using the builder's default FMF.
Definition: IRBuilder.h:1740
Value * CreateFreeze(Value *V, const Twine &Name="")
Definition: IRBuilder.h:2525
Value * CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &Name="")
Definition: IRBuilder.h:1876
Value * CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2172
ConstantInt * getInt64(uint64_t C)
Get a constant 64-bit value.
Definition: IRBuilder.h:491
ConstantInt * getInt32(uint32_t C)
Get a constant 32-bit value.
Definition: IRBuilder.h:486
Value * CreateCmp(CmpInst::Predicate Pred, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:2356
Value * CreateBitCast(Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2117
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:1790
Value * CreateShuffleVector(Value *V1, Value *V2, Value *Mask, const Twine &Name="")
Definition: IRBuilder.h:2484
StoreInst * CreateStore(Value *Val, Value *Ptr, bool isVolatile=false)
Definition: IRBuilder.h:1803
PointerType * getPtrTy(unsigned AddrSpace=0)
Fetch the type representing a pointer.
Definition: IRBuilder.h:569
Value * CreateBinOp(Instruction::BinaryOps Opc, Value *LHS, Value *RHS, const Twine &Name="", MDNode *FPMathTag=nullptr)
Definition: IRBuilder.h:1666
Value * CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy, const Twine &Name="")
Definition: IRBuilder.h:2151
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block.
Definition: IRBuilder.h:180
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2656
InstructionWorklist - This is the worklist management logic for InstCombine and other simplification ...
void pushUsersToWorkList(Instruction &I)
When an instruction is simplified, add all users of the instruction to the work lists because they mi...
void push(Instruction *I)
Push the instruction onto the worklist stack.
void remove(Instruction *I)
Remove I from the worklist if it exists.
bool isBinaryOp() const
Definition: Instruction.h:257
bool comesBefore(const Instruction *Other) const
Given an instruction Other in the same basic block as this instruction, return true if this instructi...
bool mayReadFromMemory() const LLVM_READONLY
Return true if this instruction may read memory.
void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
Definition: IntrinsicInst.h:54
An instruction for reading from memory.
Definition: Instructions.h:184
Representation for a specific memory location.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1827
A set of analyses that are preserved following a run of a transformation pass.
Definition: Analysis.h:109
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: Analysis.h:115
void preserveSet()
Mark an analysis set as preserved.
Definition: Analysis.h:144
This instruction constructs a fixed permutation of two input vectors.
int getMaskValue(unsigned Elt) const
Return the shuffle mask value of this instruction for the given element index.
VectorType * getType() const
Overload to return most specific vector type.
static void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
static void commuteShuffleMask(MutableArrayRef< int > Mask, unsigned InVecNumElts)
Change values in a shuffle permute mask assuming the two vector operands of length InVecNumElts have ...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:342
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:366
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:427
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:950
void push_back(const T &Elt)
Definition: SmallVector.h:426
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
An instruction for storing to memory.
Definition: Instructions.h:317
void setAlignment(Align Align)
Definition: Instructions.h:373
Analysis pass providing the TargetTransformInfo.
This pass provides access to the codegen interfaces that are needed for IR-level transformations.
InstructionCost getAddressComputationCost(Type *Ty, ScalarEvolution *SE=nullptr, const SCEV *Ptr=nullptr) const
InstructionCost getMemoryOpCost(unsigned Opcode, Type *Src, Align Alignment, unsigned AddressSpace, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, OperandValueInfo OpdInfo={OK_AnyValue, OP_None}, const Instruction *I=nullptr) const
InstructionCost getIntrinsicInstrCost(const IntrinsicCostAttributes &ICA, TTI::TargetCostKind CostKind) const
InstructionCost getArithmeticReductionCost(unsigned Opcode, VectorType *Ty, std::optional< FastMathFlags > FMF, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput) const
Calculate the cost of vector reduction intrinsics.
InstructionCost getCastInstrCost(unsigned Opcode, Type *Dst, Type *Src, TTI::CastContextHint CCH, TTI::TargetCostKind CostKind=TTI::TCK_SizeAndLatency, const Instruction *I=nullptr) const
unsigned getRegisterClassForType(bool Vector, Type *Ty=nullptr) const
TargetCostKind
The kind of cost model.
@ TCK_RecipThroughput
Reciprocal throughput.
unsigned getMinVectorRegisterBitWidth() const
InstructionCost getArithmeticInstrCost(unsigned Opcode, Type *Ty, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, TTI::OperandValueInfo Opd1Info={TTI::OK_AnyValue, TTI::OP_None}, TTI::OperandValueInfo Opd2Info={TTI::OK_AnyValue, TTI::OP_None}, ArrayRef< const Value * > Args=ArrayRef< const Value * >(), const Instruction *CxtI=nullptr, const TargetLibraryInfo *TLibInfo=nullptr) const
This is an approximation of reciprocal throughput of a math/logic op.
unsigned getNumberOfRegisters(unsigned ClassID) const
InstructionCost getShuffleCost(ShuffleKind Kind, VectorType *Tp, ArrayRef< int > Mask=std::nullopt, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, int Index=0, VectorType *SubTp=nullptr, ArrayRef< const Value * > Args=std::nullopt, const Instruction *CxtI=nullptr) const
InstructionCost getScalarizationOverhead(VectorType *Ty, const APInt &DemandedElts, bool Insert, bool Extract, TTI::TargetCostKind CostKind) const
Estimate the overhead of scalarizing an instruction.
InstructionCost getVectorInstrCost(unsigned Opcode, Type *Val, TTI::TargetCostKind CostKind, unsigned Index=-1, Value *Op0=nullptr, Value *Op1=nullptr) const
ShuffleKind
The various kinds of shuffle patterns for vector queries.
@ SK_Select
Selects elements from the corresponding lane of either source operand.
@ SK_PermuteSingleSrc
Shuffle elements of single source vector with any shuffle mask.
@ SK_Broadcast
Broadcast element 0 to all other elements.
@ SK_PermuteTwoSrc
Merge elements from two source vectors into one with any shuffle mask.
@ None
The cast is not used with a load/store of any kind.
InstructionCost getCmpSelInstrCost(unsigned Opcode, Type *ValTy, Type *CondTy, CmpInst::Predicate VecPred, TTI::TargetCostKind CostKind=TTI::TCK_RecipThroughput, const Instruction *I=nullptr) const
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
bool isVectorTy() const
True if this is an instance of VectorType.
Definition: Type.h:265
bool isPointerTy() const
True if this is an instance of PointerType.
Definition: Type.h:255
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition: Type.h:185
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition: Type.h:228
TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition: Type.h:348
A Use represents the edge between a Value definition and its users.
Definition: Use.h:43
op_range operands()
Definition: User.h:242
Value * getOperand(unsigned i) const
Definition: User.h:169
static bool isVPBinOp(Intrinsic::ID ID)
This is the common base class for vector predication intrinsics.
std::optional< unsigned > getFunctionalIntrinsicID() const
std::optional< unsigned > getFunctionalOpcode() const
LLVM Value Representation.
Definition: Value.h:74
Type * getType() const
All values are typed, get the type of this value.
Definition: Value.h:255
const Value * stripAndAccumulateInBoundsConstantOffsets(const DataLayout &DL, APInt &Offset) const
This is a wrapper around stripAndAccumulateConstantOffsets with the in-bounds requirement set to fals...
Definition: Value.h:736
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition: Value.h:434
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
iterator_range< user_iterator > users()
Definition: Value.h:421
Align getPointerAlignment(const DataLayout &DL) const
Returns an alignment of the pointer value.
Definition: Value.cpp:926
bool hasNUses(unsigned N) const
Return true if this Value has exactly N uses.
Definition: Value.cpp:149
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
PreservedAnalyses run(Function &F, FunctionAnalysisManager &)
constexpr char Args[]
Key for Kernel::Metadata::mArgs.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
constexpr std::underlying_type_t< E > Mask()
Get a bitmask with 1s in all places up to the high-order bit of E's largest value.
Definition: BitmaskEnum.h:121
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
AttributeList getAttributes(LLVMContext &C, ID id)
Return the attributes for an intrinsic.
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:100
BinaryOp_match< LHS, RHS, Instruction::URem > m_URem(const LHS &L, const RHS &R)
class_match< Constant > m_Constant()
Match an arbitrary Constant and ignore it.
Definition: PatternMatch.h:160
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:918
bool match(Val *V, const Pattern &P)
Definition: PatternMatch.h:49
bind_ty< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
Definition: PatternMatch.h:765
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:821
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
Definition: PatternMatch.h:163
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
match_combine_and< LTy, RTy > m_CombineAnd(const LTy &L, const RTy &R)
Combine two pattern matchers matching L && R.
Definition: PatternMatch.h:240
CastOperator_match< OpTy, Instruction::Trunc > m_Trunc(const OpTy &Op)
Matches Trunc.
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
Definition: PatternMatch.h:548
OneUse_match< T > m_OneUse(const T &SubPattern)
Definition: PatternMatch.h:67
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
class_match< CmpInst > m_Cmp()
Matches any compare instruction and ignore it.
Definition: PatternMatch.h:105
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
match_combine_or< CastInst_match< OpTy, SExtInst >, NNegZExt_match< OpTy > > m_SExtLike(const OpTy &Op)
Match either "sext" or "zext nneg".
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:92
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
auto m_Undef()
Match an arbitrary undef constant.
Definition: PatternMatch.h:152
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:450
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
@ Offset
Definition: DWP.cpp:456
void stable_sort(R &&Range)
Definition: STLExtras.h:1995
detail::scope_exit< std::decay_t< Callable > > make_scope_exit(Callable &&F)
Definition: ScopeExit.h:59
llvm::SmallVector< int, 16 > createUnaryMask(ArrayRef< int > Mask, unsigned NumElts)
Given a shuffle mask for a binary shuffle, create the equivalent shuffle mask assuming both operands ...
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
unsigned getArithmeticReductionInstruction(Intrinsic::ID RdxID)
Returns the arithmetic instruction opcode used when expanding a reduction.
Definition: LoopUtils.cpp:921
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:656
bool mustSuppressSpeculation(const LoadInst &LI)
Return true if speculation of the given load must be suppressed to avoid ordering or interfering with...
bool widenShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Try to transform a shuffle mask by replacing elements with the scaled index for an equivalent mask of...
Value * getSplatValue(const Value *V)
Get splat value if the input is a splat vector or return nullptr.
ConstantRange computeConstantRange(const Value *V, bool ForSigned, bool UseInstrInfo=true, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Determine the possible constant range of an integer or vector of integer value.
bool isSafeToSpeculativelyExecuteWithOpcode(unsigned Opcode, const Instruction *Inst, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
This returns the same result as isSafeToSpeculativelyExecute if Opcode is the actual opcode of Inst.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
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:399
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...
bool isModSet(const ModRefInfo MRI)
Definition: ModRef.h:48
void sort(IteratorTy Start, IteratorTy End)
Definition: STLExtras.h:1647
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
constexpr int PoisonMaskElem
void narrowShuffleMaskElts(int Scale, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Replace each shuffle mask index with the scaled sequential indices for an equivalent mask of narrowed...
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecute(const Instruction *I, const Instruction *CtxI=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
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:1749
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1879
Align commonAlignment(Align A, uint64_t Offset)
Returns the alignment that satisfies both alignments.
Definition: Alignment.h:212
bool isSafeToLoadUnconditionally(Value *V, Align Alignment, APInt &Size, const DataLayout &DL, Instruction *ScanFrom=nullptr, AssumptionCache *AC=nullptr, const DominatorTree *DT=nullptr, const TargetLibraryInfo *TLI=nullptr)
Return true if we know that executing a load from this value cannot trap.
Definition: Loads.cpp:352
bool isKnownNonZero(const Value *V, unsigned Depth, const SimplifyQuery &Q)
Return true if the given value is known to be non-zero when defined.
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.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:860
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition: Alignment.h:39