LLVM 18.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/Statistic.h"
21#include "llvm/Analysis/Loads.h"
25#include "llvm/IR/Dominators.h"
26#include "llvm/IR/Function.h"
27#include "llvm/IR/IRBuilder.h"
31#include <numeric>
32
33#define DEBUG_TYPE "vector-combine"
35
36using namespace llvm;
37using namespace llvm::PatternMatch;
38
39STATISTIC(NumVecLoad, "Number of vector loads formed");
40STATISTIC(NumVecCmp, "Number of vector compares formed");
41STATISTIC(NumVecBO, "Number of vector binops formed");
42STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed");
43STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast");
44STATISTIC(NumScalarBO, "Number of scalar binops formed");
45STATISTIC(NumScalarCmp, "Number of scalar compares formed");
46
48 "disable-vector-combine", cl::init(false), cl::Hidden,
49 cl::desc("Disable all vector combine transforms"));
50
52 "disable-binop-extract-shuffle", cl::init(false), cl::Hidden,
53 cl::desc("Disable binop extract to shuffle transforms"));
54
56 "vector-combine-max-scan-instrs", cl::init(30), cl::Hidden,
57 cl::desc("Max number of instructions to scan for vector combining."));
58
59static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max();
60
61namespace {
62class VectorCombine {
63public:
64 VectorCombine(Function &F, const TargetTransformInfo &TTI,
65 const DominatorTree &DT, AAResults &AA, AssumptionCache &AC,
66 bool TryEarlyFoldsOnly)
67 : F(F), Builder(F.getContext()), TTI(TTI), DT(DT), AA(AA), AC(AC),
68 TryEarlyFoldsOnly(TryEarlyFoldsOnly) {}
69
70 bool run();
71
72private:
73 Function &F;
76 const DominatorTree &DT;
77 AAResults &AA;
79
80 /// If true, only perform beneficial early IR transforms. Do not introduce new
81 /// vector operations.
82 bool TryEarlyFoldsOnly;
83
84 InstructionWorklist Worklist;
85
86 // TODO: Direct calls from the top-level "run" loop use a plain "Instruction"
87 // parameter. That should be updated to specific sub-classes because the
88 // run loop was changed to dispatch on opcode.
89 bool vectorizeLoadInsert(Instruction &I);
90 bool widenSubvectorLoad(Instruction &I);
91 ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0,
93 unsigned PreferredExtractIndex) const;
94 bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
95 const Instruction &I,
96 ExtractElementInst *&ConvertToShuffle,
97 unsigned PreferredExtractIndex);
98 void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
99 Instruction &I);
100 void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1,
101 Instruction &I);
102 bool foldExtractExtract(Instruction &I);
103 bool foldInsExtFNeg(Instruction &I);
104 bool foldBitcastShuf(Instruction &I);
105 bool scalarizeBinopOrCmp(Instruction &I);
106 bool scalarizeVPIntrinsic(Instruction &I);
107 bool foldExtractedCmps(Instruction &I);
108 bool foldSingleElementStore(Instruction &I);
109 bool scalarizeLoadExtract(Instruction &I);
110 bool foldShuffleOfBinops(Instruction &I);
111 bool foldShuffleFromReductions(Instruction &I);
112 bool foldSelectShuffle(Instruction &I, bool FromReduction = false);
113
114 void replaceValue(Value &Old, Value &New) {
115 Old.replaceAllUsesWith(&New);
116 if (auto *NewI = dyn_cast<Instruction>(&New)) {
117 New.takeName(&Old);
118 Worklist.pushUsersToWorkList(*NewI);
119 Worklist.pushValue(NewI);
120 }
121 Worklist.pushValue(&Old);
122 }
123
125 for (Value *Op : I.operands())
126 Worklist.pushValue(Op);
127 Worklist.remove(&I);
128 I.eraseFromParent();
129 }
130};
131} // namespace
132
133static bool canWidenLoad(LoadInst *Load, const TargetTransformInfo &TTI) {
134 // Do not widen load if atomic/volatile or under asan/hwasan/memtag/tsan.
135 // The widened load may load data from dirty regions or create data races
136 // non-existent in the source.
137 if (!Load || !Load->isSimple() || !Load->hasOneUse() ||
138 Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) ||
140 return false;
141
142 // We are potentially transforming byte-sized (8-bit) memory accesses, so make
143 // sure we have all of our type-based constraints in place for this target.
144 Type *ScalarTy = Load->getType()->getScalarType();
145 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
146 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
147 if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0 ||
148 ScalarSize % 8 != 0)
149 return false;
150
151 return true;
152}
153
154bool VectorCombine::vectorizeLoadInsert(Instruction &I) {
155 // Match insert into fixed vector of scalar value.
156 // TODO: Handle non-zero insert index.
157 Value *Scalar;
158 if (!match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt())) ||
159 !Scalar->hasOneUse())
160 return false;
161
162 // Optionally match an extract from another vector.
163 Value *X;
164 bool HasExtract = match(Scalar, m_ExtractElt(m_Value(X), m_ZeroInt()));
165 if (!HasExtract)
166 X = Scalar;
167
168 auto *Load = dyn_cast<LoadInst>(X);
169 if (!canWidenLoad(Load, TTI))
170 return false;
171
172 Type *ScalarTy = Scalar->getType();
173 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits();
174 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth();
175
176 // Check safety of replacing the scalar load with a larger vector load.
177 // We use minimal alignment (maximum flexibility) because we only care about
178 // the dereferenceable region. When calculating cost and creating a new op,
179 // we may use a larger value based on alignment attributes.
180 const DataLayout &DL = I.getModule()->getDataLayout();
181 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
182 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
183
184 unsigned MinVecNumElts = MinVectorSize / ScalarSize;
185 auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false);
186 unsigned OffsetEltIndex = 0;
187 Align Alignment = Load->getAlign();
188 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &AC,
189 &DT)) {
190 // It is not safe to load directly from the pointer, but we can still peek
191 // through gep offsets and check if it safe to load from a base address with
192 // updated alignment. If it is, we can shuffle the element(s) into place
193 // after loading.
194 unsigned OffsetBitWidth = DL.getIndexTypeSizeInBits(SrcPtr->getType());
195 APInt Offset(OffsetBitWidth, 0);
197
198 // We want to shuffle the result down from a high element of a vector, so
199 // the offset must be positive.
200 if (Offset.isNegative())
201 return false;
202
203 // The offset must be a multiple of the scalar element to shuffle cleanly
204 // in the element's size.
205 uint64_t ScalarSizeInBytes = ScalarSize / 8;
206 if (Offset.urem(ScalarSizeInBytes) != 0)
207 return false;
208
209 // If we load MinVecNumElts, will our target element still be loaded?
210 OffsetEltIndex = Offset.udiv(ScalarSizeInBytes).getZExtValue();
211 if (OffsetEltIndex >= MinVecNumElts)
212 return false;
213
214 if (!isSafeToLoadUnconditionally(SrcPtr, MinVecTy, Align(1), DL, Load, &AC,
215 &DT))
216 return false;
217
218 // Update alignment with offset value. Note that the offset could be negated
219 // to more accurately represent "(new) SrcPtr - Offset = (old) SrcPtr", but
220 // negation does not change the result of the alignment calculation.
221 Alignment = commonAlignment(Alignment, Offset.getZExtValue());
222 }
223
224 // Original pattern: insertelt undef, load [free casts of] PtrOp, 0
225 // Use the greater of the alignment on the load or its source pointer.
226 Alignment = std::max(SrcPtr->getPointerAlignment(DL), Alignment);
227 Type *LoadTy = Load->getType();
228 unsigned AS = Load->getPointerAddressSpace();
229 InstructionCost OldCost =
230 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
231 APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0);
233 OldCost +=
234 TTI.getScalarizationOverhead(MinVecTy, DemandedElts,
235 /* Insert */ true, HasExtract, CostKind);
236
237 // New pattern: load VecPtr
238 InstructionCost NewCost =
239 TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS);
240 // Optionally, we are shuffling the loaded vector element(s) into place.
241 // For the mask set everything but element 0 to undef to prevent poison from
242 // propagating from the extra loaded memory. This will also optionally
243 // shrink/grow the vector from the loaded size to the output size.
244 // We assume this operation has no cost in codegen if there was no offset.
245 // Note that we could use freeze to avoid poison problems, but then we might
246 // still need a shuffle to change the vector size.
247 auto *Ty = cast<FixedVectorType>(I.getType());
248 unsigned OutputNumElts = Ty->getNumElements();
250 assert(OffsetEltIndex < MinVecNumElts && "Address offset too big");
251 Mask[0] = OffsetEltIndex;
252 if (OffsetEltIndex)
253 NewCost += TTI.getShuffleCost(TTI::SK_PermuteSingleSrc, MinVecTy, Mask);
254
255 // We can aggressively convert to the vector form because the backend can
256 // invert this transform if it does not result in a performance win.
257 if (OldCost < NewCost || !NewCost.isValid())
258 return false;
259
260 // It is safe and potentially profitable to load a vector directly:
261 // inselt undef, load Scalar, 0 --> load VecPtr
262 IRBuilder<> Builder(Load);
263 Value *CastedPtr = Builder.CreatePointerBitCastOrAddrSpaceCast(
264 SrcPtr, MinVecTy->getPointerTo(AS));
265 Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment);
266 VecLd = Builder.CreateShuffleVector(VecLd, Mask);
267
268 replaceValue(I, *VecLd);
269 ++NumVecLoad;
270 return true;
271}
272
273/// If we are loading a vector and then inserting it into a larger vector with
274/// undefined elements, try to load the larger vector and eliminate the insert.
275/// This removes a shuffle in IR and may allow combining of other loaded values.
276bool VectorCombine::widenSubvectorLoad(Instruction &I) {
277 // Match subvector insert of fixed vector.
278 auto *Shuf = cast<ShuffleVectorInst>(&I);
279 if (!Shuf->isIdentityWithPadding())
280 return false;
281
282 // Allow a non-canonical shuffle mask that is choosing elements from op1.
283 unsigned NumOpElts =
284 cast<FixedVectorType>(Shuf->getOperand(0)->getType())->getNumElements();
285 unsigned OpIndex = any_of(Shuf->getShuffleMask(), [&NumOpElts](int M) {
286 return M >= (int)(NumOpElts);
287 });
288
289 auto *Load = dyn_cast<LoadInst>(Shuf->getOperand(OpIndex));
290 if (!canWidenLoad(Load, TTI))
291 return false;
292
293 // We use minimal alignment (maximum flexibility) because we only care about
294 // the dereferenceable region. When calculating cost and creating a new op,
295 // we may use a larger value based on alignment attributes.
296 auto *Ty = cast<FixedVectorType>(I.getType());
297 const DataLayout &DL = I.getModule()->getDataLayout();
298 Value *SrcPtr = Load->getPointerOperand()->stripPointerCasts();
299 assert(isa<PointerType>(SrcPtr->getType()) && "Expected a pointer type");
300 Align Alignment = Load->getAlign();
301 if (!isSafeToLoadUnconditionally(SrcPtr, Ty, Align(1), DL, Load, &AC, &DT))
302 return false;
303
304 Alignment = std::max(SrcPtr->getPointerAlignment(DL), Alignment);
305 Type *LoadTy = Load->getType();
306 unsigned AS = Load->getPointerAddressSpace();
307
308 // Original pattern: insert_subvector (load PtrOp)
309 // This conservatively assumes that the cost of a subvector insert into an
310 // undef value is 0. We could add that cost if the cost model accurately
311 // reflects the real cost of that operation.
312 InstructionCost OldCost =
313 TTI.getMemoryOpCost(Instruction::Load, LoadTy, Alignment, AS);
314
315 // New pattern: load PtrOp
316 InstructionCost NewCost =
317 TTI.getMemoryOpCost(Instruction::Load, Ty, Alignment, AS);
318
319 // We can aggressively convert to the vector form because the backend can
320 // invert this transform if it does not result in a performance win.
321 if (OldCost < NewCost || !NewCost.isValid())
322 return false;
323
324 IRBuilder<> Builder(Load);
325 Value *CastedPtr =
326 Builder.CreatePointerBitCastOrAddrSpaceCast(SrcPtr, Ty->getPointerTo(AS));
327 Value *VecLd = Builder.CreateAlignedLoad(Ty, CastedPtr, Alignment);
328 replaceValue(I, *VecLd);
329 ++NumVecLoad;
330 return true;
331}
332
333/// Determine which, if any, of the inputs should be replaced by a shuffle
334/// followed by extract from a different index.
335ExtractElementInst *VectorCombine::getShuffleExtract(
337 unsigned PreferredExtractIndex = InvalidIndex) const {
338 auto *Index0C = dyn_cast<ConstantInt>(Ext0->getIndexOperand());
339 auto *Index1C = dyn_cast<ConstantInt>(Ext1->getIndexOperand());
340 assert(Index0C && Index1C && "Expected constant extract indexes");
341
342 unsigned Index0 = Index0C->getZExtValue();
343 unsigned Index1 = Index1C->getZExtValue();
344
345 // If the extract indexes are identical, no shuffle is needed.
346 if (Index0 == Index1)
347 return nullptr;
348
349 Type *VecTy = Ext0->getVectorOperand()->getType();
351 assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types");
352 InstructionCost Cost0 =
353 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
354 InstructionCost Cost1 =
355 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
356
357 // If both costs are invalid no shuffle is needed
358 if (!Cost0.isValid() && !Cost1.isValid())
359 return nullptr;
360
361 // We are extracting from 2 different indexes, so one operand must be shuffled
362 // before performing a vector operation and/or extract. The more expensive
363 // extract will be replaced by a shuffle.
364 if (Cost0 > Cost1)
365 return Ext0;
366 if (Cost1 > Cost0)
367 return Ext1;
368
369 // If the costs are equal and there is a preferred extract index, shuffle the
370 // opposite operand.
371 if (PreferredExtractIndex == Index0)
372 return Ext1;
373 if (PreferredExtractIndex == Index1)
374 return Ext0;
375
376 // Otherwise, replace the extract with the higher index.
377 return Index0 > Index1 ? Ext0 : Ext1;
378}
379
380/// Compare the relative costs of 2 extracts followed by scalar operation vs.
381/// vector operation(s) followed by extract. Return true if the existing
382/// instructions are cheaper than a vector alternative. Otherwise, return false
383/// and if one of the extracts should be transformed to a shufflevector, set
384/// \p ConvertToShuffle to that extract instruction.
385bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0,
386 ExtractElementInst *Ext1,
387 const Instruction &I,
388 ExtractElementInst *&ConvertToShuffle,
389 unsigned PreferredExtractIndex) {
390 auto *Ext0IndexC = dyn_cast<ConstantInt>(Ext0->getOperand(1));
391 auto *Ext1IndexC = dyn_cast<ConstantInt>(Ext1->getOperand(1));
392 assert(Ext0IndexC && Ext1IndexC && "Expected constant extract indexes");
393
394 unsigned Opcode = I.getOpcode();
395 Type *ScalarTy = Ext0->getType();
396 auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType());
397 InstructionCost ScalarOpCost, VectorOpCost;
398
399 // Get cost estimates for scalar and vector versions of the operation.
400 bool IsBinOp = Instruction::isBinaryOp(Opcode);
401 if (IsBinOp) {
402 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
403 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
404 } else {
405 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
406 "Expected a compare");
407 CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
408 ScalarOpCost = TTI.getCmpSelInstrCost(
409 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
410 VectorOpCost = TTI.getCmpSelInstrCost(
411 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
412 }
413
414 // Get cost estimates for the extract elements. These costs will factor into
415 // both sequences.
416 unsigned Ext0Index = Ext0IndexC->getZExtValue();
417 unsigned Ext1Index = Ext1IndexC->getZExtValue();
419
420 InstructionCost Extract0Cost =
421 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Ext0Index);
422 InstructionCost Extract1Cost =
423 TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Ext1Index);
424
425 // A more expensive extract will always be replaced by a splat shuffle.
426 // For example, if Ext0 is more expensive:
427 // opcode (extelt V0, Ext0), (ext V1, Ext1) -->
428 // extelt (opcode (splat V0, Ext0), V1), Ext1
429 // TODO: Evaluate whether that always results in lowest cost. Alternatively,
430 // check the cost of creating a broadcast shuffle and shuffling both
431 // operands to element 0.
432 InstructionCost CheapExtractCost = std::min(Extract0Cost, Extract1Cost);
433
434 // Extra uses of the extracts mean that we include those costs in the
435 // vector total because those instructions will not be eliminated.
436 InstructionCost OldCost, NewCost;
437 if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) {
438 // Handle a special case. If the 2 extracts are identical, adjust the
439 // formulas to account for that. The extra use charge allows for either the
440 // CSE'd pattern or an unoptimized form with identical values:
441 // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C
442 bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2)
443 : !Ext0->hasOneUse() || !Ext1->hasOneUse();
444 OldCost = CheapExtractCost + ScalarOpCost;
445 NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost;
446 } else {
447 // Handle the general case. Each extract is actually a different value:
448 // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C
449 OldCost = Extract0Cost + Extract1Cost + ScalarOpCost;
450 NewCost = VectorOpCost + CheapExtractCost +
451 !Ext0->hasOneUse() * Extract0Cost +
452 !Ext1->hasOneUse() * Extract1Cost;
453 }
454
455 ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex);
456 if (ConvertToShuffle) {
457 if (IsBinOp && DisableBinopExtractShuffle)
458 return true;
459
460 // If we are extracting from 2 different indexes, then one operand must be
461 // shuffled before performing the vector operation. The shuffle mask is
462 // poison except for 1 lane that is being translated to the remaining
463 // extraction lane. Therefore, it is a splat shuffle. Ex:
464 // ShufMask = { poison, poison, 0, poison }
465 // TODO: The cost model has an option for a "broadcast" shuffle
466 // (splat-from-element-0), but no option for a more general splat.
467 NewCost +=
469 }
470
471 // Aggressively form a vector op if the cost is equal because the transform
472 // may enable further optimization.
473 // Codegen can reverse this transform (scalarize) if it was not profitable.
474 return OldCost < NewCost;
475}
476
477/// Create a shuffle that translates (shifts) 1 element from the input vector
478/// to a new element location.
479static Value *createShiftShuffle(Value *Vec, unsigned OldIndex,
480 unsigned NewIndex, IRBuilder<> &Builder) {
481 // The shuffle mask is poison except for 1 lane that is being translated
482 // to the new element index. Example for OldIndex == 2 and NewIndex == 0:
483 // ShufMask = { 2, poison, poison, poison }
484 auto *VecTy = cast<FixedVectorType>(Vec->getType());
485 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem);
486 ShufMask[NewIndex] = OldIndex;
487 return Builder.CreateShuffleVector(Vec, ShufMask, "shift");
488}
489
490/// Given an extract element instruction with constant index operand, shuffle
491/// the source vector (shift the scalar element) to a NewIndex for extraction.
492/// Return null if the input can be constant folded, so that we are not creating
493/// unnecessary instructions.
495 unsigned NewIndex,
496 IRBuilder<> &Builder) {
497 // Shufflevectors can only be created for fixed-width vectors.
498 if (!isa<FixedVectorType>(ExtElt->getOperand(0)->getType()))
499 return nullptr;
500
501 // If the extract can be constant-folded, this code is unsimplified. Defer
502 // to other passes to handle that.
503 Value *X = ExtElt->getVectorOperand();
504 Value *C = ExtElt->getIndexOperand();
505 assert(isa<ConstantInt>(C) && "Expected a constant index operand");
506 if (isa<Constant>(X))
507 return nullptr;
508
509 Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(),
510 NewIndex, Builder);
511 return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex));
512}
513
514/// Try to reduce extract element costs by converting scalar compares to vector
515/// compares followed by extract.
516/// cmp (ext0 V0, C), (ext1 V1, C)
517void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0,
519 assert(isa<CmpInst>(&I) && "Expected a compare");
520 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
521 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
522 "Expected matching constant extract indexes");
523
524 // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C
525 ++NumVecCmp;
526 CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate();
527 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
528 Value *VecCmp = Builder.CreateCmp(Pred, V0, V1);
529 Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand());
530 replaceValue(I, *NewExt);
531}
532
533/// Try to reduce extract element costs by converting scalar binops to vector
534/// binops followed by extract.
535/// bo (ext0 V0, C), (ext1 V1, C)
536void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0,
538 assert(isa<BinaryOperator>(&I) && "Expected a binary operator");
539 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() ==
540 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() &&
541 "Expected matching constant extract indexes");
542
543 // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C
544 ++NumVecBO;
545 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand();
546 Value *VecBO =
547 Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1);
548
549 // All IR flags are safe to back-propagate because any potential poison
550 // created in unused vector elements is discarded by the extract.
551 if (auto *VecBOInst = dyn_cast<Instruction>(VecBO))
552 VecBOInst->copyIRFlags(&I);
553
554 Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand());
555 replaceValue(I, *NewExt);
556}
557
558/// Match an instruction with extracted vector operands.
559bool VectorCombine::foldExtractExtract(Instruction &I) {
560 // It is not safe to transform things like div, urem, etc. because we may
561 // create undefined behavior when executing those on unknown vector elements.
563 return false;
564
565 Instruction *I0, *I1;
567 if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) &&
569 return false;
570
571 Value *V0, *V1;
572 uint64_t C0, C1;
573 if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) ||
574 !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) ||
575 V0->getType() != V1->getType())
576 return false;
577
578 // If the scalar value 'I' is going to be re-inserted into a vector, then try
579 // to create an extract to that same element. The extract/insert can be
580 // reduced to a "select shuffle".
581 // TODO: If we add a larger pattern match that starts from an insert, this
582 // probably becomes unnecessary.
583 auto *Ext0 = cast<ExtractElementInst>(I0);
584 auto *Ext1 = cast<ExtractElementInst>(I1);
585 uint64_t InsertIndex = InvalidIndex;
586 if (I.hasOneUse())
587 match(I.user_back(),
588 m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex)));
589
590 ExtractElementInst *ExtractToChange;
591 if (isExtractExtractCheap(Ext0, Ext1, I, ExtractToChange, InsertIndex))
592 return false;
593
594 if (ExtractToChange) {
595 unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0;
596 ExtractElementInst *NewExtract =
597 translateExtract(ExtractToChange, CheapExtractIdx, Builder);
598 if (!NewExtract)
599 return false;
600 if (ExtractToChange == Ext0)
601 Ext0 = NewExtract;
602 else
603 Ext1 = NewExtract;
604 }
605
606 if (Pred != CmpInst::BAD_ICMP_PREDICATE)
607 foldExtExtCmp(Ext0, Ext1, I);
608 else
609 foldExtExtBinop(Ext0, Ext1, I);
610
611 Worklist.push(Ext0);
612 Worklist.push(Ext1);
613 return true;
614}
615
616/// Try to replace an extract + scalar fneg + insert with a vector fneg +
617/// shuffle.
618bool VectorCombine::foldInsExtFNeg(Instruction &I) {
619 // Match an insert (op (extract)) pattern.
620 Value *DestVec;
622 Instruction *FNeg;
623 if (!match(&I, m_InsertElt(m_Value(DestVec), m_OneUse(m_Instruction(FNeg)),
625 return false;
626
627 // Note: This handles the canonical fneg instruction and "fsub -0.0, X".
628 Value *SrcVec;
629 Instruction *Extract;
630 if (!match(FNeg, m_FNeg(m_CombineAnd(
631 m_Instruction(Extract),
633 return false;
634
635 // TODO: We could handle this with a length-changing shuffle.
636 auto *VecTy = cast<FixedVectorType>(I.getType());
637 if (SrcVec->getType() != VecTy)
638 return false;
639
640 // Ignore bogus insert/extract index.
641 unsigned NumElts = VecTy->getNumElements();
642 if (Index >= NumElts)
643 return false;
644
645 // We are inserting the negated element into the same lane that we extracted
646 // from. This is equivalent to a select-shuffle that chooses all but the
647 // negated element from the destination vector.
648 SmallVector<int> Mask(NumElts);
649 std::iota(Mask.begin(), Mask.end(), 0);
650 Mask[Index] = Index + NumElts;
651
652 Type *ScalarTy = VecTy->getScalarType();
654 InstructionCost OldCost =
655 TTI.getArithmeticInstrCost(Instruction::FNeg, ScalarTy) +
657
658 // If the extract has one use, it will be eliminated, so count it in the
659 // original cost. If it has more than one use, ignore the cost because it will
660 // be the same before/after.
661 if (Extract->hasOneUse())
662 OldCost += TTI.getVectorInstrCost(*Extract, VecTy, CostKind, Index);
663
664 InstructionCost NewCost =
665 TTI.getArithmeticInstrCost(Instruction::FNeg, VecTy) +
667
668 if (NewCost > OldCost)
669 return false;
670
671 // insertelt DestVec, (fneg (extractelt SrcVec, Index)), Index -->
672 // shuffle DestVec, (fneg SrcVec), Mask
673 Value *VecFNeg = Builder.CreateFNegFMF(SrcVec, FNeg);
674 Value *Shuf = Builder.CreateShuffleVector(DestVec, VecFNeg, Mask);
675 replaceValue(I, *Shuf);
676 return true;
677}
678
679/// If this is a bitcast of a shuffle, try to bitcast the source vector to the
680/// destination type followed by shuffle. This can enable further transforms by
681/// moving bitcasts or shuffles together.
682bool VectorCombine::foldBitcastShuf(Instruction &I) {
683 Value *V;
685 if (!match(&I, m_BitCast(
686 m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask))))))
687 return false;
688
689 // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for
690 // scalable type is unknown; Second, we cannot reason if the narrowed shuffle
691 // mask for scalable type is a splat or not.
692 // 2) Disallow non-vector casts and length-changing shuffles.
693 // TODO: We could allow any shuffle.
694 auto *SrcTy = dyn_cast<FixedVectorType>(V->getType());
695 if (!SrcTy || I.getOperand(0)->getType() != SrcTy)
696 return false;
697
698 auto *DestTy = cast<FixedVectorType>(I.getType());
699 unsigned DestNumElts = DestTy->getNumElements();
700 unsigned SrcNumElts = SrcTy->getNumElements();
701 SmallVector<int, 16> NewMask;
702 if (SrcNumElts <= DestNumElts) {
703 // The bitcast is from wide to narrow/equal elements. The shuffle mask can
704 // always be expanded to the equivalent form choosing narrower elements.
705 assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask");
706 unsigned ScaleFactor = DestNumElts / SrcNumElts;
707 narrowShuffleMaskElts(ScaleFactor, Mask, NewMask);
708 } else {
709 // The bitcast is from narrow elements to wide elements. The shuffle mask
710 // must choose consecutive elements to allow casting first.
711 assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask");
712 unsigned ScaleFactor = SrcNumElts / DestNumElts;
713 if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask))
714 return false;
715 }
716
717 // The new shuffle must not cost more than the old shuffle. The bitcast is
718 // moved ahead of the shuffle, so assume that it has the same cost as before.
721 InstructionCost SrcCost =
723 if (DestCost > SrcCost || !DestCost.isValid())
724 return false;
725
726 // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC'
727 ++NumShufOfBitcast;
728 Value *CastV = Builder.CreateBitCast(V, DestTy);
729 Value *Shuf = Builder.CreateShuffleVector(CastV, NewMask);
730 replaceValue(I, *Shuf);
731 return true;
732}
733
734/// VP Intrinsics whose vector operands are both splat values may be simplified
735/// into the scalar version of the operation and the result splatted. This
736/// can lead to scalarization down the line.
737bool VectorCombine::scalarizeVPIntrinsic(Instruction &I) {
738 if (!isa<VPIntrinsic>(I))
739 return false;
740 VPIntrinsic &VPI = cast<VPIntrinsic>(I);
741 Value *Op0 = VPI.getArgOperand(0);
742 Value *Op1 = VPI.getArgOperand(1);
743
744 if (!isSplatValue(Op0) || !isSplatValue(Op1))
745 return false;
746
747 // For the binary VP intrinsics supported here, the result on disabled lanes
748 // is a poison value. For now, only do this simplification if all lanes
749 // are active.
750 // TODO: Relax the condition that all lanes are active by using insertelement
751 // on inactive lanes.
752 auto IsAllTrueMask = [](Value *MaskVal) {
753 if (Value *SplattedVal = getSplatValue(MaskVal))
754 if (auto *ConstValue = dyn_cast<Constant>(SplattedVal))
755 return ConstValue->isAllOnesValue();
756 return false;
757 };
758 if (!IsAllTrueMask(VPI.getArgOperand(2)))
759 return false;
760
761 // Check to make sure we support scalarization of the intrinsic
762 Intrinsic::ID IntrID = VPI.getIntrinsicID();
763 if (!VPBinOpIntrinsic::isVPBinOp(IntrID))
764 return false;
765
766 // Calculate cost of splatting both operands into vectors and the vector
767 // intrinsic
768 VectorType *VecTy = cast<VectorType>(VPI.getType());
770 InstructionCost SplatCost =
771 TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind, 0) +
773
774 // Calculate the cost of the VP Intrinsic
776 for (Value *V : VPI.args())
777 Args.push_back(V->getType());
778 IntrinsicCostAttributes Attrs(IntrID, VecTy, Args);
779 InstructionCost VectorOpCost = TTI.getIntrinsicInstrCost(Attrs, CostKind);
780 InstructionCost OldCost = 2 * SplatCost + VectorOpCost;
781
782 // Determine scalar opcode
783 std::optional<unsigned> FunctionalOpcode =
785 std::optional<Intrinsic::ID> ScalarIntrID = std::nullopt;
786 if (!FunctionalOpcode) {
787 ScalarIntrID = VPI.getFunctionalIntrinsicID();
788 if (!ScalarIntrID)
789 return false;
790 }
791
792 // Calculate cost of scalarizing
793 InstructionCost ScalarOpCost = 0;
794 if (ScalarIntrID) {
795 IntrinsicCostAttributes Attrs(*ScalarIntrID, VecTy->getScalarType(), Args);
796 ScalarOpCost = TTI.getIntrinsicInstrCost(Attrs, CostKind);
797 } else {
798 ScalarOpCost =
799 TTI.getArithmeticInstrCost(*FunctionalOpcode, VecTy->getScalarType());
800 }
801
802 // The existing splats may be kept around if other instructions use them.
803 InstructionCost CostToKeepSplats =
804 (SplatCost * !Op0->hasOneUse()) + (SplatCost * !Op1->hasOneUse());
805 InstructionCost NewCost = ScalarOpCost + SplatCost + CostToKeepSplats;
806
807 LLVM_DEBUG(dbgs() << "Found a VP Intrinsic to scalarize: " << VPI
808 << "\n");
809 LLVM_DEBUG(dbgs() << "Cost of Intrinsic: " << OldCost
810 << ", Cost of scalarizing:" << NewCost << "\n");
811
812 // We want to scalarize unless the vector variant actually has lower cost.
813 if (OldCost < NewCost || !NewCost.isValid())
814 return false;
815
816 // Scalarize the intrinsic
817 ElementCount EC = cast<VectorType>(Op0->getType())->getElementCount();
818 Value *EVL = VPI.getArgOperand(3);
819 const DataLayout &DL = VPI.getModule()->getDataLayout();
820 bool MustHaveNonZeroVL =
821 IntrID == Intrinsic::vp_sdiv || IntrID == Intrinsic::vp_udiv ||
822 IntrID == Intrinsic::vp_srem || IntrID == Intrinsic::vp_urem;
823
824 if (!MustHaveNonZeroVL || isKnownNonZero(EVL, DL, 0, &AC, &VPI, &DT)) {
825 Value *ScalarOp0 = getSplatValue(Op0);
826 Value *ScalarOp1 = getSplatValue(Op1);
827 Value *ScalarVal =
828 ScalarIntrID
829 ? Builder.CreateIntrinsic(VecTy->getScalarType(), *ScalarIntrID,
830 {ScalarOp0, ScalarOp1})
831 : Builder.CreateBinOp((Instruction::BinaryOps)(*FunctionalOpcode),
832 ScalarOp0, ScalarOp1);
833 replaceValue(VPI, *Builder.CreateVectorSplat(EC, ScalarVal));
834 return true;
835 }
836 return false;
837}
838
839/// Match a vector binop or compare instruction with at least one inserted
840/// scalar operand and convert to scalar binop/cmp followed by insertelement.
841bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) {
843 Value *Ins0, *Ins1;
844 if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) &&
845 !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1))))
846 return false;
847
848 // Do not convert the vector condition of a vector select into a scalar
849 // condition. That may cause problems for codegen because of differences in
850 // boolean formats and register-file transfers.
851 // TODO: Can we account for that in the cost model?
852 bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE;
853 if (IsCmp)
854 for (User *U : I.users())
855 if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value())))
856 return false;
857
858 // Match against one or both scalar values being inserted into constant
859 // vectors:
860 // vec_op VecC0, (inselt VecC1, V1, Index)
861 // vec_op (inselt VecC0, V0, Index), VecC1
862 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index)
863 // TODO: Deal with mismatched index constants and variable indexes?
864 Constant *VecC0 = nullptr, *VecC1 = nullptr;
865 Value *V0 = nullptr, *V1 = nullptr;
866 uint64_t Index0 = 0, Index1 = 0;
867 if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0),
868 m_ConstantInt(Index0))) &&
869 !match(Ins0, m_Constant(VecC0)))
870 return false;
871 if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1),
872 m_ConstantInt(Index1))) &&
873 !match(Ins1, m_Constant(VecC1)))
874 return false;
875
876 bool IsConst0 = !V0;
877 bool IsConst1 = !V1;
878 if (IsConst0 && IsConst1)
879 return false;
880 if (!IsConst0 && !IsConst1 && Index0 != Index1)
881 return false;
882
883 // Bail for single insertion if it is a load.
884 // TODO: Handle this once getVectorInstrCost can cost for load/stores.
885 auto *I0 = dyn_cast_or_null<Instruction>(V0);
886 auto *I1 = dyn_cast_or_null<Instruction>(V1);
887 if ((IsConst0 && I1 && I1->mayReadFromMemory()) ||
888 (IsConst1 && I0 && I0->mayReadFromMemory()))
889 return false;
890
891 uint64_t Index = IsConst0 ? Index1 : Index0;
892 Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType();
893 Type *VecTy = I.getType();
894 assert(VecTy->isVectorTy() &&
895 (IsConst0 || IsConst1 || V0->getType() == V1->getType()) &&
896 (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() ||
897 ScalarTy->isPointerTy()) &&
898 "Unexpected types for insert element into binop or cmp");
899
900 unsigned Opcode = I.getOpcode();
901 InstructionCost ScalarOpCost, VectorOpCost;
902 if (IsCmp) {
903 CmpInst::Predicate Pred = cast<CmpInst>(I).getPredicate();
904 ScalarOpCost = TTI.getCmpSelInstrCost(
905 Opcode, ScalarTy, CmpInst::makeCmpResultType(ScalarTy), Pred);
906 VectorOpCost = TTI.getCmpSelInstrCost(
907 Opcode, VecTy, CmpInst::makeCmpResultType(VecTy), Pred);
908 } else {
909 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy);
910 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
911 }
912
913 // Get cost estimate for the insert element. This cost will factor into
914 // both sequences.
917 Instruction::InsertElement, VecTy, CostKind, Index);
918 InstructionCost OldCost =
919 (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + VectorOpCost;
920 InstructionCost NewCost = ScalarOpCost + InsertCost +
921 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) +
922 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost);
923
924 // We want to scalarize unless the vector variant actually has lower cost.
925 if (OldCost < NewCost || !NewCost.isValid())
926 return false;
927
928 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) -->
929 // inselt NewVecC, (scalar_op V0, V1), Index
930 if (IsCmp)
931 ++NumScalarCmp;
932 else
933 ++NumScalarBO;
934
935 // For constant cases, extract the scalar element, this should constant fold.
936 if (IsConst0)
937 V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index));
938 if (IsConst1)
939 V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index));
940
941 Value *Scalar =
942 IsCmp ? Builder.CreateCmp(Pred, V0, V1)
943 : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1);
944
945 Scalar->setName(I.getName() + ".scalar");
946
947 // All IR flags are safe to back-propagate. There is no potential for extra
948 // poison to be created by the scalar instruction.
949 if (auto *ScalarInst = dyn_cast<Instruction>(Scalar))
950 ScalarInst->copyIRFlags(&I);
951
952 // Fold the vector constants in the original vectors into a new base vector.
953 Value *NewVecC =
954 IsCmp ? Builder.CreateCmp(Pred, VecC0, VecC1)
955 : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, VecC0, VecC1);
956 Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index);
957 replaceValue(I, *Insert);
958 return true;
959}
960
961/// Try to combine a scalar binop + 2 scalar compares of extracted elements of
962/// a vector into vector operations followed by extract. Note: The SLP pass
963/// may miss this pattern because of implementation problems.
964bool VectorCombine::foldExtractedCmps(Instruction &I) {
965 // We are looking for a scalar binop of booleans.
966 // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1)
967 if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1))
968 return false;
969
970 // The compare predicates should match, and each compare should have a
971 // constant operand.
972 // TODO: Relax the one-use constraints.
973 Value *B0 = I.getOperand(0), *B1 = I.getOperand(1);
974 Instruction *I0, *I1;
975 Constant *C0, *C1;
976 CmpInst::Predicate P0, P1;
977 if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) ||
978 !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) ||
979 P0 != P1)
980 return false;
981
982 // The compare operands must be extracts of the same vector with constant
983 // extract indexes.
984 // TODO: Relax the one-use constraints.
985 Value *X;
986 uint64_t Index0, Index1;
987 if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) ||
989 return false;
990
991 auto *Ext0 = cast<ExtractElementInst>(I0);
992 auto *Ext1 = cast<ExtractElementInst>(I1);
993 ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1);
994 if (!ConvertToShuf)
995 return false;
996
997 // The original scalar pattern is:
998 // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1)
999 CmpInst::Predicate Pred = P0;
1000 unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp
1001 : Instruction::ICmp;
1002 auto *VecTy = dyn_cast<FixedVectorType>(X->getType());
1003 if (!VecTy)
1004 return false;
1005
1007 InstructionCost OldCost =
1008 TTI.getVectorInstrCost(*Ext0, VecTy, CostKind, Index0);
1009 OldCost += TTI.getVectorInstrCost(*Ext1, VecTy, CostKind, Index1);
1010 OldCost +=
1011 TTI.getCmpSelInstrCost(CmpOpcode, I0->getType(),
1012 CmpInst::makeCmpResultType(I0->getType()), Pred) *
1013 2;
1014 OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType());
1015
1016 // The proposed vector pattern is:
1017 // vcmp = cmp Pred X, VecC
1018 // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0
1019 int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0;
1020 int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1;
1021 auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType()));
1023 CmpOpcode, X->getType(), CmpInst::makeCmpResultType(X->getType()), Pred);
1024 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), PoisonMaskElem);
1025 ShufMask[CheapIndex] = ExpensiveIndex;
1027 ShufMask);
1028 NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy);
1029 NewCost += TTI.getVectorInstrCost(*Ext0, CmpTy, CostKind, CheapIndex);
1030
1031 // Aggressively form vector ops if the cost is equal because the transform
1032 // may enable further optimization.
1033 // Codegen can reverse this transform (scalarize) if it was not profitable.
1034 if (OldCost < NewCost || !NewCost.isValid())
1035 return false;
1036
1037 // Create a vector constant from the 2 scalar constants.
1038 SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(),
1039 PoisonValue::get(VecTy->getElementType()));
1040 CmpC[Index0] = C0;
1041 CmpC[Index1] = C1;
1042 Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC));
1043
1044 Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder);
1045 Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
1046 VCmp, Shuf);
1047 Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex);
1048 replaceValue(I, *NewExt);
1049 ++NumVecCmpBO;
1050 return true;
1051}
1052
1053// Check if memory loc modified between two instrs in the same BB
1056 const MemoryLocation &Loc, AAResults &AA) {
1057 unsigned NumScanned = 0;
1058 return std::any_of(Begin, End, [&](const Instruction &Instr) {
1059 return isModSet(AA.getModRefInfo(&Instr, Loc)) ||
1060 ++NumScanned > MaxInstrsToScan;
1061 });
1062}
1063
1064namespace {
1065/// Helper class to indicate whether a vector index can be safely scalarized and
1066/// if a freeze needs to be inserted.
1067class ScalarizationResult {
1068 enum class StatusTy { Unsafe, Safe, SafeWithFreeze };
1069
1070 StatusTy Status;
1071 Value *ToFreeze;
1072
1073 ScalarizationResult(StatusTy Status, Value *ToFreeze = nullptr)
1074 : Status(Status), ToFreeze(ToFreeze) {}
1075
1076public:
1077 ScalarizationResult(const ScalarizationResult &Other) = default;
1078 ~ScalarizationResult() {
1079 assert(!ToFreeze && "freeze() not called with ToFreeze being set");
1080 }
1081
1082 static ScalarizationResult unsafe() { return {StatusTy::Unsafe}; }
1083 static ScalarizationResult safe() { return {StatusTy::Safe}; }
1084 static ScalarizationResult safeWithFreeze(Value *ToFreeze) {
1085 return {StatusTy::SafeWithFreeze, ToFreeze};
1086 }
1087
1088 /// Returns true if the index can be scalarize without requiring a freeze.
1089 bool isSafe() const { return Status == StatusTy::Safe; }
1090 /// Returns true if the index cannot be scalarized.
1091 bool isUnsafe() const { return Status == StatusTy::Unsafe; }
1092 /// Returns true if the index can be scalarize, but requires inserting a
1093 /// freeze.
1094 bool isSafeWithFreeze() const { return Status == StatusTy::SafeWithFreeze; }
1095
1096 /// Reset the state of Unsafe and clear ToFreze if set.
1097 void discard() {
1098 ToFreeze = nullptr;
1099 Status = StatusTy::Unsafe;
1100 }
1101
1102 /// Freeze the ToFreeze and update the use in \p User to use it.
1103 void freeze(IRBuilder<> &Builder, Instruction &UserI) {
1104 assert(isSafeWithFreeze() &&
1105 "should only be used when freezing is required");
1106 assert(is_contained(ToFreeze->users(), &UserI) &&
1107 "UserI must be a user of ToFreeze");
1108 IRBuilder<>::InsertPointGuard Guard(Builder);
1109 Builder.SetInsertPoint(cast<Instruction>(&UserI));
1110 Value *Frozen =
1111 Builder.CreateFreeze(ToFreeze, ToFreeze->getName() + ".frozen");
1112 for (Use &U : make_early_inc_range((UserI.operands())))
1113 if (U.get() == ToFreeze)
1114 U.set(Frozen);
1115
1116 ToFreeze = nullptr;
1117 }
1118};
1119} // namespace
1120
1121/// Check if it is legal to scalarize a memory access to \p VecTy at index \p
1122/// Idx. \p Idx must access a valid vector element.
1123static ScalarizationResult canScalarizeAccess(VectorType *VecTy, Value *Idx,
1124 Instruction *CtxI,
1125 AssumptionCache &AC,
1126 const DominatorTree &DT) {
1127 // We do checks for both fixed vector types and scalable vector types.
1128 // This is the number of elements of fixed vector types,
1129 // or the minium number of elements of scalable vector types.
1130 uint64_t NumElements = VecTy->getElementCount().getKnownMinValue();
1131
1132 if (auto *C = dyn_cast<ConstantInt>(Idx)) {
1133 if (C->getValue().ult(NumElements))
1134 return ScalarizationResult::safe();
1135 return ScalarizationResult::unsafe();
1136 }
1137
1138 unsigned IntWidth = Idx->getType()->getScalarSizeInBits();
1139 APInt Zero(IntWidth, 0);
1140 APInt MaxElts(IntWidth, NumElements);
1141 ConstantRange ValidIndices(Zero, MaxElts);
1142 ConstantRange IdxRange(IntWidth, true);
1143
1144 if (isGuaranteedNotToBePoison(Idx, &AC)) {
1145 if (ValidIndices.contains(computeConstantRange(Idx, /* ForSigned */ false,
1146 true, &AC, CtxI, &DT)))
1147 return ScalarizationResult::safe();
1148 return ScalarizationResult::unsafe();
1149 }
1150
1151 // If the index may be poison, check if we can insert a freeze before the
1152 // range of the index is restricted.
1153 Value *IdxBase;
1154 ConstantInt *CI;
1155 if (match(Idx, m_And(m_Value(IdxBase), m_ConstantInt(CI)))) {
1156 IdxRange = IdxRange.binaryAnd(CI->getValue());
1157 } else if (match(Idx, m_URem(m_Value(IdxBase), m_ConstantInt(CI)))) {
1158 IdxRange = IdxRange.urem(CI->getValue());
1159 }
1160
1161 if (ValidIndices.contains(IdxRange))
1162 return ScalarizationResult::safeWithFreeze(IdxBase);
1163 return ScalarizationResult::unsafe();
1164}
1165
1166/// The memory operation on a vector of \p ScalarType had alignment of
1167/// \p VectorAlignment. Compute the maximal, but conservatively correct,
1168/// alignment that will be valid for the memory operation on a single scalar
1169/// element of the same type with index \p Idx.
1171 Type *ScalarType, Value *Idx,
1172 const DataLayout &DL) {
1173 if (auto *C = dyn_cast<ConstantInt>(Idx))
1174 return commonAlignment(VectorAlignment,
1175 C->getZExtValue() * DL.getTypeStoreSize(ScalarType));
1176 return commonAlignment(VectorAlignment, DL.getTypeStoreSize(ScalarType));
1177}
1178
1179// Combine patterns like:
1180// %0 = load <4 x i32>, <4 x i32>* %a
1181// %1 = insertelement <4 x i32> %0, i32 %b, i32 1
1182// store <4 x i32> %1, <4 x i32>* %a
1183// to:
1184// %0 = bitcast <4 x i32>* %a to i32*
1185// %1 = getelementptr inbounds i32, i32* %0, i64 0, i64 1
1186// store i32 %b, i32* %1
1187bool VectorCombine::foldSingleElementStore(Instruction &I) {
1188 auto *SI = cast<StoreInst>(&I);
1189 if (!SI->isSimple() || !isa<VectorType>(SI->getValueOperand()->getType()))
1190 return false;
1191
1192 // TODO: Combine more complicated patterns (multiple insert) by referencing
1193 // TargetTransformInfo.
1195 Value *NewElement;
1196 Value *Idx;
1197 if (!match(SI->getValueOperand(),
1198 m_InsertElt(m_Instruction(Source), m_Value(NewElement),
1199 m_Value(Idx))))
1200 return false;
1201
1202 if (auto *Load = dyn_cast<LoadInst>(Source)) {
1203 auto VecTy = cast<VectorType>(SI->getValueOperand()->getType());
1204 const DataLayout &DL = I.getModule()->getDataLayout();
1205 Value *SrcAddr = Load->getPointerOperand()->stripPointerCasts();
1206 // Don't optimize for atomic/volatile load or store. Ensure memory is not
1207 // modified between, vector type matches store size, and index is inbounds.
1208 if (!Load->isSimple() || Load->getParent() != SI->getParent() ||
1209 !DL.typeSizeEqualsStoreSize(Load->getType()) ||
1210 SrcAddr != SI->getPointerOperand()->stripPointerCasts())
1211 return false;
1212
1213 auto ScalarizableIdx = canScalarizeAccess(VecTy, Idx, Load, AC, DT);
1214 if (ScalarizableIdx.isUnsafe() ||
1215 isMemModifiedBetween(Load->getIterator(), SI->getIterator(),
1216 MemoryLocation::get(SI), AA))
1217 return false;
1218
1219 if (ScalarizableIdx.isSafeWithFreeze())
1220 ScalarizableIdx.freeze(Builder, *cast<Instruction>(Idx));
1221 Value *GEP = Builder.CreateInBoundsGEP(
1222 SI->getValueOperand()->getType(), SI->getPointerOperand(),
1223 {ConstantInt::get(Idx->getType(), 0), Idx});
1224 StoreInst *NSI = Builder.CreateStore(NewElement, GEP);
1225 NSI->copyMetadata(*SI);
1226 Align ScalarOpAlignment = computeAlignmentAfterScalarization(
1227 std::max(SI->getAlign(), Load->getAlign()), NewElement->getType(), Idx,
1228 DL);
1229 NSI->setAlignment(ScalarOpAlignment);
1230 replaceValue(I, *NSI);
1232 return true;
1233 }
1234
1235 return false;
1236}
1237
1238/// Try to scalarize vector loads feeding extractelement instructions.
1239bool VectorCombine::scalarizeLoadExtract(Instruction &I) {
1240 Value *Ptr;
1241 if (!match(&I, m_Load(m_Value(Ptr))))
1242 return false;
1243
1244 auto *VecTy = cast<VectorType>(I.getType());
1245 auto *LI = cast<LoadInst>(&I);
1246 const DataLayout &DL = I.getModule()->getDataLayout();
1247 if (LI->isVolatile() || !DL.typeSizeEqualsStoreSize(VecTy))
1248 return false;
1249
1250 InstructionCost OriginalCost =
1251 TTI.getMemoryOpCost(Instruction::Load, VecTy, LI->getAlign(),
1252 LI->getPointerAddressSpace());
1253 InstructionCost ScalarizedCost = 0;
1254
1255 Instruction *LastCheckedInst = LI;
1256 unsigned NumInstChecked = 0;
1258 // Check if all users of the load are extracts with no memory modifications
1259 // between the load and the extract. Compute the cost of both the original
1260 // code and the scalarized version.
1261 for (User *U : LI->users()) {
1262 auto *UI = dyn_cast<ExtractElementInst>(U);
1263 if (!UI || UI->getParent() != LI->getParent())
1264 return false;
1265
1266 // Check if any instruction between the load and the extract may modify
1267 // memory.
1268 if (LastCheckedInst->comesBefore(UI)) {
1269 for (Instruction &I :
1270 make_range(std::next(LI->getIterator()), UI->getIterator())) {
1271 // Bail out if we reached the check limit or the instruction may write
1272 // to memory.
1273 if (NumInstChecked == MaxInstrsToScan || I.mayWriteToMemory())
1274 return false;
1275 NumInstChecked++;
1276 }
1277 LastCheckedInst = UI;
1278 }
1279
1280 auto ScalarIdx = canScalarizeAccess(VecTy, UI->getOperand(1), &I, AC, DT);
1281 if (ScalarIdx.isUnsafe())
1282 return false;
1283 if (ScalarIdx.isSafeWithFreeze()) {
1284 NeedFreeze.try_emplace(UI, ScalarIdx);
1285 ScalarIdx.discard();
1286 }
1287
1288 auto *Index = dyn_cast<ConstantInt>(UI->getOperand(1));
1290 OriginalCost +=
1291 TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, CostKind,
1292 Index ? Index->getZExtValue() : -1);
1293 ScalarizedCost +=
1294 TTI.getMemoryOpCost(Instruction::Load, VecTy->getElementType(),
1295 Align(1), LI->getPointerAddressSpace());
1296 ScalarizedCost += TTI.getAddressComputationCost(VecTy->getElementType());
1297 }
1298
1299 if (ScalarizedCost >= OriginalCost)
1300 return false;
1301
1302 // Replace extracts with narrow scalar loads.
1303 for (User *U : LI->users()) {
1304 auto *EI = cast<ExtractElementInst>(U);
1305 Value *Idx = EI->getOperand(1);
1306
1307 // Insert 'freeze' for poison indexes.
1308 auto It = NeedFreeze.find(EI);
1309 if (It != NeedFreeze.end())
1310 It->second.freeze(Builder, *cast<Instruction>(Idx));
1311
1312 Builder.SetInsertPoint(EI);
1313 Value *GEP =
1314 Builder.CreateInBoundsGEP(VecTy, Ptr, {Builder.getInt32(0), Idx});
1315 auto *NewLoad = cast<LoadInst>(Builder.CreateLoad(
1316 VecTy->getElementType(), GEP, EI->getName() + ".scalar"));
1317
1318 Align ScalarOpAlignment = computeAlignmentAfterScalarization(
1319 LI->getAlign(), VecTy->getElementType(), Idx, DL);
1320 NewLoad->setAlignment(ScalarOpAlignment);
1321
1322 replaceValue(*EI, *NewLoad);
1323 }
1324
1325 return true;
1326}
1327
1328/// Try to convert "shuffle (binop), (binop)" with a shared binop operand into
1329/// "binop (shuffle), (shuffle)".
1330bool VectorCombine::foldShuffleOfBinops(Instruction &I) {
1331 auto *VecTy = cast<FixedVectorType>(I.getType());
1332 BinaryOperator *B0, *B1;
1334 if (!match(&I, m_Shuffle(m_OneUse(m_BinOp(B0)), m_OneUse(m_BinOp(B1)),
1335 m_Mask(Mask))) ||
1336 B0->getOpcode() != B1->getOpcode() || B0->getType() != VecTy)
1337 return false;
1338
1339 // Try to replace a binop with a shuffle if the shuffle is not costly.
1340 // The new shuffle will choose from a single, common operand, so it may be
1341 // cheaper than the existing two-operand shuffle.
1342 SmallVector<int> UnaryMask = createUnaryMask(Mask, Mask.size());
1343 Instruction::BinaryOps Opcode = B0->getOpcode();
1344 InstructionCost BinopCost = TTI.getArithmeticInstrCost(Opcode, VecTy);
1347 if (ShufCost > BinopCost)
1348 return false;
1349
1350 // If we have something like "add X, Y" and "add Z, X", swap ops to match.
1351 Value *X = B0->getOperand(0), *Y = B0->getOperand(1);
1352 Value *Z = B1->getOperand(0), *W = B1->getOperand(1);
1353 if (BinaryOperator::isCommutative(Opcode) && X != Z && Y != W)
1354 std::swap(X, Y);
1355
1356 Value *Shuf0, *Shuf1;
1357 if (X == Z) {
1358 // shuf (bo X, Y), (bo X, W) --> bo (shuf X), (shuf Y, W)
1359 Shuf0 = Builder.CreateShuffleVector(X, UnaryMask);
1360 Shuf1 = Builder.CreateShuffleVector(Y, W, Mask);
1361 } else if (Y == W) {
1362 // shuf (bo X, Y), (bo Z, Y) --> bo (shuf X, Z), (shuf Y)
1363 Shuf0 = Builder.CreateShuffleVector(X, Z, Mask);
1364 Shuf1 = Builder.CreateShuffleVector(Y, UnaryMask);
1365 } else {
1366 return false;
1367 }
1368
1369 Value *NewBO = Builder.CreateBinOp(Opcode, Shuf0, Shuf1);
1370 // Intersect flags from the old binops.
1371 if (auto *NewInst = dyn_cast<Instruction>(NewBO)) {
1372 NewInst->copyIRFlags(B0);
1373 NewInst->andIRFlags(B1);
1374 }
1375 replaceValue(I, *NewBO);
1376 return true;
1377}
1378
1379/// Given a commutative reduction, the order of the input lanes does not alter
1380/// the results. We can use this to remove certain shuffles feeding the
1381/// reduction, removing the need to shuffle at all.
1382bool VectorCombine::foldShuffleFromReductions(Instruction &I) {
1383 auto *II = dyn_cast<IntrinsicInst>(&I);
1384 if (!II)
1385 return false;
1386 switch (II->getIntrinsicID()) {
1387 case Intrinsic::vector_reduce_add:
1388 case Intrinsic::vector_reduce_mul:
1389 case Intrinsic::vector_reduce_and:
1390 case Intrinsic::vector_reduce_or:
1391 case Intrinsic::vector_reduce_xor:
1392 case Intrinsic::vector_reduce_smin:
1393 case Intrinsic::vector_reduce_smax:
1394 case Intrinsic::vector_reduce_umin:
1395 case Intrinsic::vector_reduce_umax:
1396 break;
1397 default:
1398 return false;
1399 }
1400
1401 // Find all the inputs when looking through operations that do not alter the
1402 // lane order (binops, for example). Currently we look for a single shuffle,
1403 // and can ignore splat values.
1404 std::queue<Value *> Worklist;
1406 ShuffleVectorInst *Shuffle = nullptr;
1407 if (auto *Op = dyn_cast<Instruction>(I.getOperand(0)))
1408 Worklist.push(Op);
1409
1410 while (!Worklist.empty()) {
1411 Value *CV = Worklist.front();
1412 Worklist.pop();
1413 if (Visited.contains(CV))
1414 continue;
1415
1416 // Splats don't change the order, so can be safely ignored.
1417 if (isSplatValue(CV))
1418 continue;
1419
1420 Visited.insert(CV);
1421
1422 if (auto *CI = dyn_cast<Instruction>(CV)) {
1423 if (CI->isBinaryOp()) {
1424 for (auto *Op : CI->operand_values())
1425 Worklist.push(Op);
1426 continue;
1427 } else if (auto *SV = dyn_cast<ShuffleVectorInst>(CI)) {
1428 if (Shuffle && Shuffle != SV)
1429 return false;
1430 Shuffle = SV;
1431 continue;
1432 }
1433 }
1434
1435 // Anything else is currently an unknown node.
1436 return false;
1437 }
1438
1439 if (!Shuffle)
1440 return false;
1441
1442 // Check all uses of the binary ops and shuffles are also included in the
1443 // lane-invariant operations (Visited should be the list of lanewise
1444 // instructions, including the shuffle that we found).
1445 for (auto *V : Visited)
1446 for (auto *U : V->users())
1447 if (!Visited.contains(U) && U != &I)
1448 return false;
1449
1451 dyn_cast<FixedVectorType>(II->getOperand(0)->getType());
1452 if (!VecType)
1453 return false;
1454 FixedVectorType *ShuffleInputType =
1455 dyn_cast<FixedVectorType>(Shuffle->getOperand(0)->getType());
1456 if (!ShuffleInputType)
1457 return false;
1458 int NumInputElts = ShuffleInputType->getNumElements();
1459
1460 // Find the mask from sorting the lanes into order. This is most likely to
1461 // become a identity or concat mask. Undef elements are pushed to the end.
1462 SmallVector<int> ConcatMask;
1463 Shuffle->getShuffleMask(ConcatMask);
1464 sort(ConcatMask, [](int X, int Y) { return (unsigned)X < (unsigned)Y; });
1465 bool UsesSecondVec =
1466 any_of(ConcatMask, [&](int M) { return M >= NumInputElts; });
1468 UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
1469 Shuffle->getShuffleMask());
1471 UsesSecondVec ? TTI::SK_PermuteTwoSrc : TTI::SK_PermuteSingleSrc, VecType,
1472 ConcatMask);
1473
1474 LLVM_DEBUG(dbgs() << "Found a reduction feeding from a shuffle: " << *Shuffle
1475 << "\n");
1476 LLVM_DEBUG(dbgs() << " OldCost: " << OldCost << " vs NewCost: " << NewCost
1477 << "\n");
1478 if (NewCost < OldCost) {
1479 Builder.SetInsertPoint(Shuffle);
1480 Value *NewShuffle = Builder.CreateShuffleVector(
1481 Shuffle->getOperand(0), Shuffle->getOperand(1), ConcatMask);
1482 LLVM_DEBUG(dbgs() << "Created new shuffle: " << *NewShuffle << "\n");
1483 replaceValue(*Shuffle, *NewShuffle);
1484 }
1485
1486 // See if we can re-use foldSelectShuffle, getting it to reduce the size of
1487 // the shuffle into a nicer order, as it can ignore the order of the shuffles.
1488 return foldSelectShuffle(*Shuffle, true);
1489}
1490
1491/// This method looks for groups of shuffles acting on binops, of the form:
1492/// %x = shuffle ...
1493/// %y = shuffle ...
1494/// %a = binop %x, %y
1495/// %b = binop %x, %y
1496/// shuffle %a, %b, selectmask
1497/// We may, especially if the shuffle is wider than legal, be able to convert
1498/// the shuffle to a form where only parts of a and b need to be computed. On
1499/// architectures with no obvious "select" shuffle, this can reduce the total
1500/// number of operations if the target reports them as cheaper.
1501bool VectorCombine::foldSelectShuffle(Instruction &I, bool FromReduction) {
1502 auto *SVI = cast<ShuffleVectorInst>(&I);
1503 auto *VT = cast<FixedVectorType>(I.getType());
1504 auto *Op0 = dyn_cast<Instruction>(SVI->getOperand(0));
1505 auto *Op1 = dyn_cast<Instruction>(SVI->getOperand(1));
1506 if (!Op0 || !Op1 || Op0 == Op1 || !Op0->isBinaryOp() || !Op1->isBinaryOp() ||
1507 VT != Op0->getType())
1508 return false;
1509
1510 auto *SVI0A = dyn_cast<Instruction>(Op0->getOperand(0));
1511 auto *SVI0B = dyn_cast<Instruction>(Op0->getOperand(1));
1512 auto *SVI1A = dyn_cast<Instruction>(Op1->getOperand(0));
1513 auto *SVI1B = dyn_cast<Instruction>(Op1->getOperand(1));
1514 SmallPtrSet<Instruction *, 4> InputShuffles({SVI0A, SVI0B, SVI1A, SVI1B});
1515 auto checkSVNonOpUses = [&](Instruction *I) {
1516 if (!I || I->getOperand(0)->getType() != VT)
1517 return true;
1518 return any_of(I->users(), [&](User *U) {
1519 return U != Op0 && U != Op1 &&
1520 !(isa<ShuffleVectorInst>(U) &&
1521 (InputShuffles.contains(cast<Instruction>(U)) ||
1522 isInstructionTriviallyDead(cast<Instruction>(U))));
1523 });
1524 };
1525 if (checkSVNonOpUses(SVI0A) || checkSVNonOpUses(SVI0B) ||
1526 checkSVNonOpUses(SVI1A) || checkSVNonOpUses(SVI1B))
1527 return false;
1528
1529 // Collect all the uses that are shuffles that we can transform together. We
1530 // may not have a single shuffle, but a group that can all be transformed
1531 // together profitably.
1533 auto collectShuffles = [&](Instruction *I) {
1534 for (auto *U : I->users()) {
1535 auto *SV = dyn_cast<ShuffleVectorInst>(U);
1536 if (!SV || SV->getType() != VT)
1537 return false;
1538 if ((SV->getOperand(0) != Op0 && SV->getOperand(0) != Op1) ||
1539 (SV->getOperand(1) != Op0 && SV->getOperand(1) != Op1))
1540 return false;
1541 if (!llvm::is_contained(Shuffles, SV))
1542 Shuffles.push_back(SV);
1543 }
1544 return true;
1545 };
1546 if (!collectShuffles(Op0) || !collectShuffles(Op1))
1547 return false;
1548 // From a reduction, we need to be processing a single shuffle, otherwise the
1549 // other uses will not be lane-invariant.
1550 if (FromReduction && Shuffles.size() > 1)
1551 return false;
1552
1553 // Add any shuffle uses for the shuffles we have found, to include them in our
1554 // cost calculations.
1555 if (!FromReduction) {
1556 for (ShuffleVectorInst *SV : Shuffles) {
1557 for (auto *U : SV->users()) {
1558 ShuffleVectorInst *SSV = dyn_cast<ShuffleVectorInst>(U);
1559 if (SSV && isa<UndefValue>(SSV->getOperand(1)) && SSV->getType() == VT)
1560 Shuffles.push_back(SSV);
1561 }
1562 }
1563 }
1564
1565 // For each of the output shuffles, we try to sort all the first vector
1566 // elements to the beginning, followed by the second array elements at the
1567 // end. If the binops are legalized to smaller vectors, this may reduce total
1568 // number of binops. We compute the ReconstructMask mask needed to convert
1569 // back to the original lane order.
1571 SmallVector<SmallVector<int>> OrigReconstructMasks;
1572 int MaxV1Elt = 0, MaxV2Elt = 0;
1573 unsigned NumElts = VT->getNumElements();
1574 for (ShuffleVectorInst *SVN : Shuffles) {
1576 SVN->getShuffleMask(Mask);
1577
1578 // Check the operands are the same as the original, or reversed (in which
1579 // case we need to commute the mask).
1580 Value *SVOp0 = SVN->getOperand(0);
1581 Value *SVOp1 = SVN->getOperand(1);
1582 if (isa<UndefValue>(SVOp1)) {
1583 auto *SSV = cast<ShuffleVectorInst>(SVOp0);
1584 SVOp0 = SSV->getOperand(0);
1585 SVOp1 = SSV->getOperand(1);
1586 for (unsigned I = 0, E = Mask.size(); I != E; I++) {
1587 if (Mask[I] >= static_cast<int>(SSV->getShuffleMask().size()))
1588 return false;
1589 Mask[I] = Mask[I] < 0 ? Mask[I] : SSV->getMaskValue(Mask[I]);
1590 }
1591 }
1592 if (SVOp0 == Op1 && SVOp1 == Op0) {
1593 std::swap(SVOp0, SVOp1);
1595 }
1596 if (SVOp0 != Op0 || SVOp1 != Op1)
1597 return false;
1598
1599 // Calculate the reconstruction mask for this shuffle, as the mask needed to
1600 // take the packed values from Op0/Op1 and reconstructing to the original
1601 // order.
1602 SmallVector<int> ReconstructMask;
1603 for (unsigned I = 0; I < Mask.size(); I++) {
1604 if (Mask[I] < 0) {
1605 ReconstructMask.push_back(-1);
1606 } else if (Mask[I] < static_cast<int>(NumElts)) {
1607 MaxV1Elt = std::max(MaxV1Elt, Mask[I]);
1608 auto It = find_if(V1, [&](const std::pair<int, int> &A) {
1609 return Mask[I] == A.first;
1610 });
1611 if (It != V1.end())
1612 ReconstructMask.push_back(It - V1.begin());
1613 else {
1614 ReconstructMask.push_back(V1.size());
1615 V1.emplace_back(Mask[I], V1.size());
1616 }
1617 } else {
1618 MaxV2Elt = std::max<int>(MaxV2Elt, Mask[I] - NumElts);
1619 auto It = find_if(V2, [&](const std::pair<int, int> &A) {
1620 return Mask[I] - static_cast<int>(NumElts) == A.first;
1621 });
1622 if (It != V2.end())
1623 ReconstructMask.push_back(NumElts + It - V2.begin());
1624 else {
1625 ReconstructMask.push_back(NumElts + V2.size());
1626 V2.emplace_back(Mask[I] - NumElts, NumElts + V2.size());
1627 }
1628 }
1629 }
1630
1631 // For reductions, we know that the lane ordering out doesn't alter the
1632 // result. In-order can help simplify the shuffle away.
1633 if (FromReduction)
1634 sort(ReconstructMask);
1635 OrigReconstructMasks.push_back(std::move(ReconstructMask));
1636 }
1637
1638 // If the Maximum element used from V1 and V2 are not larger than the new
1639 // vectors, the vectors are already packes and performing the optimization
1640 // again will likely not help any further. This also prevents us from getting
1641 // stuck in a cycle in case the costs do not also rule it out.
1642 if (V1.empty() || V2.empty() ||
1643 (MaxV1Elt == static_cast<int>(V1.size()) - 1 &&
1644 MaxV2Elt == static_cast<int>(V2.size()) - 1))
1645 return false;
1646
1647 // GetBaseMaskValue takes one of the inputs, which may either be a shuffle, a
1648 // shuffle of another shuffle, or not a shuffle (that is treated like a
1649 // identity shuffle).
1650 auto GetBaseMaskValue = [&](Instruction *I, int M) {
1651 auto *SV = dyn_cast<ShuffleVectorInst>(I);
1652 if (!SV)
1653 return M;
1654 if (isa<UndefValue>(SV->getOperand(1)))
1655 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
1656 if (InputShuffles.contains(SSV))
1657 return SSV->getMaskValue(SV->getMaskValue(M));
1658 return SV->getMaskValue(M);
1659 };
1660
1661 // Attempt to sort the inputs my ascending mask values to make simpler input
1662 // shuffles and push complex shuffles down to the uses. We sort on the first
1663 // of the two input shuffle orders, to try and get at least one input into a
1664 // nice order.
1665 auto SortBase = [&](Instruction *A, std::pair<int, int> X,
1666 std::pair<int, int> Y) {
1667 int MXA = GetBaseMaskValue(A, X.first);
1668 int MYA = GetBaseMaskValue(A, Y.first);
1669 return MXA < MYA;
1670 };
1671 stable_sort(V1, [&](std::pair<int, int> A, std::pair<int, int> B) {
1672 return SortBase(SVI0A, A, B);
1673 });
1674 stable_sort(V2, [&](std::pair<int, int> A, std::pair<int, int> B) {
1675 return SortBase(SVI1A, A, B);
1676 });
1677 // Calculate our ReconstructMasks from the OrigReconstructMasks and the
1678 // modified order of the input shuffles.
1679 SmallVector<SmallVector<int>> ReconstructMasks;
1680 for (const auto &Mask : OrigReconstructMasks) {
1681 SmallVector<int> ReconstructMask;
1682 for (int M : Mask) {
1683 auto FindIndex = [](const SmallVector<std::pair<int, int>> &V, int M) {
1684 auto It = find_if(V, [M](auto A) { return A.second == M; });
1685 assert(It != V.end() && "Expected all entries in Mask");
1686 return std::distance(V.begin(), It);
1687 };
1688 if (M < 0)
1689 ReconstructMask.push_back(-1);
1690 else if (M < static_cast<int>(NumElts)) {
1691 ReconstructMask.push_back(FindIndex(V1, M));
1692 } else {
1693 ReconstructMask.push_back(NumElts + FindIndex(V2, M));
1694 }
1695 }
1696 ReconstructMasks.push_back(std::move(ReconstructMask));
1697 }
1698
1699 // Calculate the masks needed for the new input shuffles, which get padded
1700 // with undef
1701 SmallVector<int> V1A, V1B, V2A, V2B;
1702 for (unsigned I = 0; I < V1.size(); I++) {
1703 V1A.push_back(GetBaseMaskValue(SVI0A, V1[I].first));
1704 V1B.push_back(GetBaseMaskValue(SVI0B, V1[I].first));
1705 }
1706 for (unsigned I = 0; I < V2.size(); I++) {
1707 V2A.push_back(GetBaseMaskValue(SVI1A, V2[I].first));
1708 V2B.push_back(GetBaseMaskValue(SVI1B, V2[I].first));
1709 }
1710 while (V1A.size() < NumElts) {
1713 }
1714 while (V2A.size() < NumElts) {
1717 }
1718
1719 auto AddShuffleCost = [&](InstructionCost C, Instruction *I) {
1720 auto *SV = dyn_cast<ShuffleVectorInst>(I);
1721 if (!SV)
1722 return C;
1723 return C + TTI.getShuffleCost(isa<UndefValue>(SV->getOperand(1))
1726 VT, SV->getShuffleMask());
1727 };
1728 auto AddShuffleMaskCost = [&](InstructionCost C, ArrayRef<int> Mask) {
1729 return C + TTI.getShuffleCost(TTI::SK_PermuteTwoSrc, VT, Mask);
1730 };
1731
1732 // Get the costs of the shuffles + binops before and after with the new
1733 // shuffle masks.
1734 InstructionCost CostBefore =
1735 TTI.getArithmeticInstrCost(Op0->getOpcode(), VT) +
1736 TTI.getArithmeticInstrCost(Op1->getOpcode(), VT);
1737 CostBefore += std::accumulate(Shuffles.begin(), Shuffles.end(),
1738 InstructionCost(0), AddShuffleCost);
1739 CostBefore += std::accumulate(InputShuffles.begin(), InputShuffles.end(),
1740 InstructionCost(0), AddShuffleCost);
1741
1742 // The new binops will be unused for lanes past the used shuffle lengths.
1743 // These types attempt to get the correct cost for that from the target.
1744 FixedVectorType *Op0SmallVT =
1745 FixedVectorType::get(VT->getScalarType(), V1.size());
1746 FixedVectorType *Op1SmallVT =
1747 FixedVectorType::get(VT->getScalarType(), V2.size());
1748 InstructionCost CostAfter =
1749 TTI.getArithmeticInstrCost(Op0->getOpcode(), Op0SmallVT) +
1750 TTI.getArithmeticInstrCost(Op1->getOpcode(), Op1SmallVT);
1751 CostAfter += std::accumulate(ReconstructMasks.begin(), ReconstructMasks.end(),
1752 InstructionCost(0), AddShuffleMaskCost);
1753 std::set<SmallVector<int>> OutputShuffleMasks({V1A, V1B, V2A, V2B});
1754 CostAfter +=
1755 std::accumulate(OutputShuffleMasks.begin(), OutputShuffleMasks.end(),
1756 InstructionCost(0), AddShuffleMaskCost);
1757
1758 LLVM_DEBUG(dbgs() << "Found a binop select shuffle pattern: " << I << "\n");
1759 LLVM_DEBUG(dbgs() << " CostBefore: " << CostBefore
1760 << " vs CostAfter: " << CostAfter << "\n");
1761 if (CostBefore <= CostAfter)
1762 return false;
1763
1764 // The cost model has passed, create the new instructions.
1765 auto GetShuffleOperand = [&](Instruction *I, unsigned Op) -> Value * {
1766 auto *SV = dyn_cast<ShuffleVectorInst>(I);
1767 if (!SV)
1768 return I;
1769 if (isa<UndefValue>(SV->getOperand(1)))
1770 if (auto *SSV = dyn_cast<ShuffleVectorInst>(SV->getOperand(0)))
1771 if (InputShuffles.contains(SSV))
1772 return SSV->getOperand(Op);
1773 return SV->getOperand(Op);
1774 };
1775 Builder.SetInsertPoint(SVI0A->getInsertionPointAfterDef());
1776 Value *NSV0A = Builder.CreateShuffleVector(GetShuffleOperand(SVI0A, 0),
1777 GetShuffleOperand(SVI0A, 1), V1A);
1778 Builder.SetInsertPoint(SVI0B->getInsertionPointAfterDef());
1779 Value *NSV0B = Builder.CreateShuffleVector(GetShuffleOperand(SVI0B, 0),
1780 GetShuffleOperand(SVI0B, 1), V1B);
1781 Builder.SetInsertPoint(SVI1A->getInsertionPointAfterDef());
1782 Value *NSV1A = Builder.CreateShuffleVector(GetShuffleOperand(SVI1A, 0),
1783 GetShuffleOperand(SVI1A, 1), V2A);
1784 Builder.SetInsertPoint(SVI1B->getInsertionPointAfterDef());
1785 Value *NSV1B = Builder.CreateShuffleVector(GetShuffleOperand(SVI1B, 0),
1786 GetShuffleOperand(SVI1B, 1), V2B);
1787 Builder.SetInsertPoint(Op0);
1788 Value *NOp0 = Builder.CreateBinOp((Instruction::BinaryOps)Op0->getOpcode(),
1789 NSV0A, NSV0B);
1790 if (auto *I = dyn_cast<Instruction>(NOp0))
1791 I->copyIRFlags(Op0, true);
1792 Builder.SetInsertPoint(Op1);
1793 Value *NOp1 = Builder.CreateBinOp((Instruction::BinaryOps)Op1->getOpcode(),
1794 NSV1A, NSV1B);
1795 if (auto *I = dyn_cast<Instruction>(NOp1))
1796 I->copyIRFlags(Op1, true);
1797
1798 for (int S = 0, E = ReconstructMasks.size(); S != E; S++) {
1799 Builder.SetInsertPoint(Shuffles[S]);
1800 Value *NSV = Builder.CreateShuffleVector(NOp0, NOp1, ReconstructMasks[S]);
1801 replaceValue(*Shuffles[S], *NSV);
1802 }
1803
1804 Worklist.pushValue(NSV0A);
1805 Worklist.pushValue(NSV0B);
1806 Worklist.pushValue(NSV1A);
1807 Worklist.pushValue(NSV1B);
1808 for (auto *S : Shuffles)
1809 Worklist.add(S);
1810 return true;
1811}
1812
1813/// This is the entry point for all transforms. Pass manager differences are
1814/// handled in the callers of this function.
1815bool VectorCombine::run() {
1817 return false;
1818
1819 // Don't attempt vectorization if the target does not support vectors.
1820 if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true)))
1821 return false;
1822
1823 bool MadeChange = false;
1824 auto FoldInst = [this, &MadeChange](Instruction &I) {
1825 Builder.SetInsertPoint(&I);
1826 bool IsFixedVectorType = isa<FixedVectorType>(I.getType());
1827 auto Opcode = I.getOpcode();
1828
1829 // These folds should be beneficial regardless of when this pass is run
1830 // in the optimization pipeline.
1831 // The type checking is for run-time efficiency. We can avoid wasting time
1832 // dispatching to folding functions if there's no chance of matching.
1833 if (IsFixedVectorType) {
1834 switch (Opcode) {
1835 case Instruction::InsertElement:
1836 MadeChange |= vectorizeLoadInsert(I);
1837 break;
1838 case Instruction::ShuffleVector:
1839 MadeChange |= widenSubvectorLoad(I);
1840 break;
1841 default:
1842 break;
1843 }
1844 }
1845
1846 // This transform works with scalable and fixed vectors
1847 // TODO: Identify and allow other scalable transforms
1848 if (isa<VectorType>(I.getType())) {
1849 MadeChange |= scalarizeBinopOrCmp(I);
1850 MadeChange |= scalarizeLoadExtract(I);
1851 MadeChange |= scalarizeVPIntrinsic(I);
1852 }
1853
1854 if (Opcode == Instruction::Store)
1855 MadeChange |= foldSingleElementStore(I);
1856
1857 // If this is an early pipeline invocation of this pass, we are done.
1858 if (TryEarlyFoldsOnly)
1859 return;
1860
1861 // Otherwise, try folds that improve codegen but may interfere with
1862 // early IR canonicalizations.
1863 // The type checking is for run-time efficiency. We can avoid wasting time
1864 // dispatching to folding functions if there's no chance of matching.
1865 if (IsFixedVectorType) {
1866 switch (Opcode) {
1867 case Instruction::InsertElement:
1868 MadeChange |= foldInsExtFNeg(I);
1869 break;
1870 case Instruction::ShuffleVector:
1871 MadeChange |= foldShuffleOfBinops(I);
1872 MadeChange |= foldSelectShuffle(I);
1873 break;
1874 case Instruction::BitCast:
1875 MadeChange |= foldBitcastShuf(I);
1876 break;
1877 }
1878 } else {
1879 switch (Opcode) {
1880 case Instruction::Call:
1881 MadeChange |= foldShuffleFromReductions(I);
1882 break;
1883 case Instruction::ICmp:
1884 case Instruction::FCmp:
1885 MadeChange |= foldExtractExtract(I);
1886 break;
1887 default:
1888 if (Instruction::isBinaryOp(Opcode)) {
1889 MadeChange |= foldExtractExtract(I);
1890 MadeChange |= foldExtractedCmps(I);
1891 }
1892 break;
1893 }
1894 }
1895 };
1896
1897 for (BasicBlock &BB : F) {
1898 // Ignore unreachable basic blocks.
1899 if (!DT.isReachableFromEntry(&BB))
1900 continue;
1901 // Use early increment range so that we can erase instructions in loop.
1902 for (Instruction &I : make_early_inc_range(BB)) {
1903 if (I.isDebugOrPseudoInst())
1904 continue;
1905 FoldInst(I);
1906 }
1907 }
1908
1909 while (!Worklist.isEmpty()) {
1910 Instruction *I = Worklist.removeOne();
1911 if (!I)
1912 continue;
1913
1916 continue;
1917 }
1918
1919 FoldInst(*I);
1920 }
1921
1922 return MadeChange;
1923}
1924
1927 auto &AC = FAM.getResult<AssumptionAnalysis>(F);
1931 VectorCombine Combiner(F, TTI, DT, AA, AC, TryEarlyFoldsOnly);
1932 if (!Combiner.run())
1933 return PreservedAnalyses::all();
1936 return PA;
1937}
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
assume Assume Builder
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 GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
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:1272
bool End
Definition: ELF_riscv.cpp:469
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:1487
#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 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:167
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 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:620
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Definition: PassManager.h:774
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.
LLVM Basic Block Representation.
Definition: BasicBlock.h:56
InstListType::iterator iterator
Instruction iterators...
Definition: BasicBlock.h:87
BinaryOps getOpcode() const
Definition: InstrTypes.h:391
Represents analyses that only rely on functions' control flow.
Definition: PassManager.h:113
Value * getArgOperand(unsigned i) const
Definition: InstrTypes.h:1357
iterator_range< User::op_iterator > args()
Iteration adapter for range-for loops.
Definition: InstrTypes.h:1348
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
Definition: InstrTypes.h:1058
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Definition: InstrTypes.h:711
bool isFPPredicate() const
Definition: InstrTypes.h:818
Combiner implementation.
Definition: Combiner.h:34
static Constant * getExtractElement(Constant *Vec, Constant *Idx, Type *OnlyIfReducedTy=nullptr)
Definition: Constants.cpp:2483
This is the shared class of boolean and integer constants.
Definition: Constants.h:78
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:136
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:1342
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:166
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:536
unsigned getNumElements() const
Definition: DerivedTypes.h:579
static FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition: Type.cpp:693
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Definition: IRBuilder.h:2628
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.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:71
bool isBinaryOp() const
Definition: Instruction.h:200
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:177
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.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:254
static PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
Definition: Constants.cpp:1743
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:152
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:158
void preserveSet()
Mark an analysis set as preserved.
Definition: PassManager.h:188
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:366
bool contains(ConstPtrType Ptr) const
Definition: SmallPtrSet.h:390
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:451
bool empty() const
Definition: SmallVector.h:94
size_t size() const
Definition: SmallVector.h:91
reference emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:941
void push_back(const T &Elt)
Definition: SmallVector.h:416
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
An instruction for storing to memory.
Definition: Instructions.h:301
void setAlignment(Align Align)
Definition: Instructions.h:349
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
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
This is an approximation of reciprocal throughput of a math/logic op.
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
unsigned getNumberOfRegisters(unsigned ClassID) 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
@ 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.
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:724
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:535
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:921
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:119
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
specific_intval< false > m_SpecificInt(APInt V)
Match a specific integer value or vector with all elements equal to the value.
Definition: PatternMatch.h:862
class_match< BinaryOperator > m_BinOp()
Match an arbitrary binary operation and ignore it.
Definition: PatternMatch.h:84
CastClass_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
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:144
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:724
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Definition: PatternMatch.h:780
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:147
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:224
cst_pred_ty< is_zero_int > m_ZeroInt()
Match an integer 0 or a vector with all elements equal to 0.
Definition: PatternMatch.h:532
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:89
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Definition: PatternMatch.h:76
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:136
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:445
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:440
bool isKnownNonZero(const Value *V, const DataLayout &DL, unsigned Depth=0, AssumptionCache *AC=nullptr, const Instruction *CxtI=nullptr, const DominatorTree *DT=nullptr, bool UseInstrInfo=true)
Return true if the given value is known to be non-zero when defined.
void stable_sort(R &&Range)
Definition: STLExtras.h:1971
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.
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:666
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 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:1734
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:398
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:1652
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:1754
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition: STLExtras.h:1884
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:350
bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
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