LLVM 24.0.0git
InstCombineVectorOps.cpp
Go to the documentation of this file.
1//===- InstCombineVectorOps.cpp -------------------------------------------===//
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 file implements instcombine for ExtractElement, InsertElement and
10// ShuffleVector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombineInternal.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/DenseMap.h"
18#include "llvm/ADT/STLExtras.h"
21#include "llvm/ADT/Statistic.h"
24#include "llvm/IR/BasicBlock.h"
25#include "llvm/IR/Constant.h"
26#include "llvm/IR/Constants.h"
28#include "llvm/IR/InstrTypes.h"
29#include "llvm/IR/Instruction.h"
31#include "llvm/IR/Operator.h"
33#include "llvm/IR/Type.h"
34#include "llvm/IR/User.h"
35#include "llvm/IR/Value.h"
39#include <cassert>
40#include <cstdint>
41#include <iterator>
42#include <utility>
43
44#define DEBUG_TYPE "instcombine"
45
46using namespace llvm;
47using namespace PatternMatch;
48
49STATISTIC(NumAggregateReconstructionsSimplified,
50 "Number of aggregate reconstructions turned into reuse of the "
51 "original aggregate");
52
53/// Return true if the value is cheaper to scalarize than it is to leave as a
54/// vector operation. If the extract index \p EI is a constant integer then
55/// some operations may be cheap to scalarize.
56///
57/// FIXME: It's possible to create more instructions than previously existed.
58static bool cheapToScalarize(Value *V, Value *EI) {
60
61 // If we can pick a scalar constant value out of a vector, that is free.
62 if (auto *C = dyn_cast<Constant>(V))
63 return CEI || C->getSplatValue();
64
66 ElementCount EC = cast<VectorType>(V->getType())->getElementCount();
67 // Index needs to be lower than the minimum size of the vector, because
68 // for scalable vector, the vector size is known at run time.
69 return CEI->getValue().ult(EC.getKnownMinValue());
70 }
71
72 // An insertelement to the same constant index as our extract will simplify
73 // to the scalar inserted element. An insertelement to a different constant
74 // index is irrelevant to our extract.
76 return CEI;
77
78 if (match(V, m_OneUse(m_Load(m_Value()))))
79 return true;
80
81 if (match(V, m_OneUse(m_UnOp())))
82 return true;
83
84 Value *V0, *V1;
85 if (match(V, m_OneUse(m_BinOp(m_Value(V0), m_Value(V1)))))
86 if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
87 return true;
88
89 CmpPredicate UnusedPred;
90 if (match(V, m_OneUse(m_Cmp(UnusedPred, m_Value(V0), m_Value(V1)))))
91 if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
92 return true;
93
94 return false;
95}
96
97// If we have a PHI node with a vector type that is only used to feed
98// itself and be an operand of extractelement at a constant location,
99// try to replace the PHI of the vector type with a PHI of a scalar type.
100Instruction *InstCombinerImpl::scalarizePHI(ExtractElementInst &EI,
101 PHINode *PN) {
102 SmallVector<Instruction *, 2> Extracts;
103 // The users we want the PHI to have are:
104 // 1) The EI ExtractElement (we already know this)
105 // 2) Possibly more ExtractElements with the same index.
106 // 3) Another operand, which will feed back into the PHI.
107 Instruction *PHIUser = nullptr;
108 for (auto *U : PN->users()) {
109 if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
110 if (EI.getIndexOperand() == EU->getIndexOperand())
111 Extracts.push_back(EU);
112 else
113 return nullptr;
114 } else if (!PHIUser) {
115 PHIUser = cast<Instruction>(U);
116 } else {
117 return nullptr;
118 }
119 }
120
121 if (!PHIUser)
122 return nullptr;
123
124 // Verify that this PHI user has one use, which is the PHI itself,
125 // and that it is a binary operation which is cheap to scalarize.
126 // otherwise return nullptr.
127 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
128 !(isa<BinaryOperator>(PHIUser)) ||
129 !cheapToScalarize(PHIUser, EI.getIndexOperand()))
130 return nullptr;
131
132 // Create a scalar PHI node that will replace the vector PHI node
133 // just before the current PHI node.
134 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
136 // Scalarize each PHI operand. A switch may produce multiple edges from the
137 // same predecessor; reuse the scalar instruction for duplicate edges.
138 SmallDenseMap<BasicBlock *, Value *, 4> ScalarizedValues;
139 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
140 Value *PHIInVal = PN->getIncomingValue(i);
141 BasicBlock *inBB = PN->getIncomingBlock(i);
142 Value *Elt = EI.getIndexOperand();
143
144 // Reuse scalar value for duplicate edges from the same predecessor.
145 if (Value *Existing = ScalarizedValues.lookup(inBB)) {
146 scalarPHI->addIncoming(Existing, inBB);
147 continue;
148 }
149
150 Value *ScalarVal;
151 // If the operand is the PHI induction variable:
152 if (PHIInVal == PHIUser) {
153 // Scalarize the binary operation. One operand is the
154 // scalar PHI, and the other is extracted from the other
155 // vector operand.
156 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
157 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
160 B0->getOperand(opId)->getName() + ".Elt"),
161 B0->getIterator());
162 // Preserve operand order for binary operation to preserve semantics of
163 // non-commutative operations.
164 Value *FirstOp = (B0->getOperand(0) == PN) ? scalarPHI : Op;
165 Value *SecondOp = (B0->getOperand(0) == PN) ? Op : scalarPHI;
167 B0->getOpcode(), FirstOp, SecondOp, B0),
168 B0->getIterator());
169 } else {
170 // Scalarize PHI input:
171 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
172 // Insert the new instruction into the predecessor basic block.
173 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
174 BasicBlock::iterator InsertPos;
175 if (pos && !isa<PHINode>(pos)) {
176 InsertPos = ++pos->getIterator();
177 } else {
178 InsertPos = inBB->getFirstInsertionPt();
179 }
180
181 ScalarVal = InsertNewInstWith(newEI, InsertPos);
182 }
183
184 ScalarizedValues[inBB] = ScalarVal;
185 scalarPHI->addIncoming(ScalarVal, inBB);
186 }
187
188 for (auto *E : Extracts) {
189 replaceInstUsesWith(*E, scalarPHI);
190 // Add old extract to worklist for DCE.
192 }
193
194 return &EI;
195}
196
197Instruction *InstCombinerImpl::foldBitcastExtElt(ExtractElementInst &Ext) {
198 Value *X;
199 uint64_t ExtIndexC;
200 if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) ||
201 !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC)))
202 return nullptr;
203
204 ElementCount NumElts =
205 cast<VectorType>(Ext.getVectorOperandType())->getElementCount();
206 Type *DestTy = Ext.getType();
207 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
208 bool IsBigEndian = DL.isBigEndian();
209
210 // If we are casting an integer to vector and extracting a portion, that is
211 // a shift-right and truncate.
212 if (X->getType()->isIntegerTy()) {
214 "Expected fixed vector type for bitcast from scalar integer");
215
216 // Big endian requires adjusting the extract index since MSB is at index 0.
217 // LittleEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 X to i8
218 // BigEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 (X >> 24) to i8
219 if (IsBigEndian)
220 ExtIndexC = NumElts.getKnownMinValue() - 1 - ExtIndexC;
221 unsigned ShiftAmountC = ExtIndexC * DestWidth;
222 if ((!ShiftAmountC ||
223 isDesirableIntType(X->getType()->getPrimitiveSizeInBits())) &&
224 Ext.getVectorOperand()->hasOneUse()) {
225 if (ShiftAmountC)
226 X = Builder.CreateLShr(X, ShiftAmountC, "extelt.offset");
227 if (DestTy->isFloatingPointTy()) {
228 Type *DstIntTy = IntegerType::getIntNTy(X->getContext(), DestWidth);
229 Value *Trunc = Builder.CreateTrunc(X, DstIntTy);
230 return new BitCastInst(Trunc, DestTy);
231 }
232 return new TruncInst(X, DestTy);
233 }
234 }
235
236 if (!X->getType()->isVectorTy())
237 return nullptr;
238
239 // If this extractelement is using a bitcast from a vector of the same number
240 // of elements, see if we can find the source element from the source vector:
241 // extelt (bitcast VecX), IndexC --> bitcast X[IndexC]
242 auto *SrcTy = cast<VectorType>(X->getType());
243 ElementCount NumSrcElts = SrcTy->getElementCount();
244 if (NumSrcElts == NumElts)
245 if (Value *Elt = findScalarElement(X, ExtIndexC))
246 return new BitCastInst(Elt, DestTy);
247
248 assert(NumSrcElts.isScalable() == NumElts.isScalable() &&
249 "Src and Dst must be the same sort of vector type");
250
251 // If the source elements are wider than the destination, try to shift and
252 // truncate a subset of scalar bits of an insert op.
253 if (NumSrcElts.getKnownMinValue() < NumElts.getKnownMinValue()) {
254 Value *Scalar;
255 Value *Vec;
256 uint64_t InsIndexC;
257 if (!match(X, m_InsertElt(m_Value(Vec), m_Value(Scalar),
258 m_ConstantInt(InsIndexC))))
259 return nullptr;
260
261 // The extract must be from the subset of vector elements that we inserted
262 // into. Example: if we inserted element 1 of a <2 x i64> and we are
263 // extracting an i16 (narrowing ratio = 4), then this extract must be from 1
264 // of elements 4-7 of the bitcasted vector.
265 unsigned NarrowingRatio =
266 NumElts.getKnownMinValue() / NumSrcElts.getKnownMinValue();
267
268 if (ExtIndexC / NarrowingRatio != InsIndexC) {
269 // Remove insertelement, if we don't use the inserted element.
270 // extractelement (bitcast (insertelement (Vec, b)), a) ->
271 // extractelement (bitcast (Vec), a)
272 // FIXME: this should be removed to SimplifyDemandedVectorElts,
273 // once scale vectors are supported.
274 if (X->hasOneUse() && Ext.getVectorOperand()->hasOneUse()) {
275 Value *NewBC = Builder.CreateBitCast(Vec, Ext.getVectorOperandType());
276 return ExtractElementInst::Create(NewBC, Ext.getIndexOperand());
277 }
278 return nullptr;
279 }
280
281 // We are extracting part of the original scalar. How that scalar is
282 // inserted into the vector depends on the endian-ness. Example:
283 // Vector Byte Elt Index: 0 1 2 3 4 5 6 7
284 // +--+--+--+--+--+--+--+--+
285 // inselt <2 x i32> V, <i32> S, 1: |V0|V1|V2|V3|S0|S1|S2|S3|
286 // extelt <4 x i16> V', 3: | |S2|S3|
287 // +--+--+--+--+--+--+--+--+
288 // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value.
289 // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value.
290 // In this example, we must right-shift little-endian. Big-endian is just a
291 // truncate.
292 unsigned Chunk = ExtIndexC % NarrowingRatio;
293 if (IsBigEndian)
294 Chunk = NarrowingRatio - 1 - Chunk;
295
296 // Bail out if this is an FP vector to FP vector sequence. That would take
297 // more instructions than we started with unless there is no shift, and it
298 // may not be handled as well in the backend.
299 bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy();
300 bool NeedDestBitcast = DestTy->isFloatingPointTy();
301 if (NeedSrcBitcast && NeedDestBitcast)
302 return nullptr;
303
304 unsigned SrcWidth = SrcTy->getScalarSizeInBits();
305 unsigned ShAmt = Chunk * DestWidth;
306
307 // TODO: This limitation is more strict than necessary. We could sum the
308 // number of new instructions and subtract the number eliminated to know if
309 // we can proceed.
310 if (!X->hasOneUse() || !Ext.getVectorOperand()->hasOneUse())
311 if (NeedSrcBitcast || NeedDestBitcast)
312 return nullptr;
313
314 if (NeedSrcBitcast) {
315 Type *SrcIntTy = IntegerType::getIntNTy(Scalar->getContext(), SrcWidth);
316 Scalar = Builder.CreateBitCast(Scalar, SrcIntTy);
317 }
318
319 if (ShAmt) {
320 // Bail out if we could end with more instructions than we started with.
321 if (!Ext.getVectorOperand()->hasOneUse())
322 return nullptr;
323 Scalar = Builder.CreateLShr(Scalar, ShAmt);
324 }
325
326 if (NeedDestBitcast) {
327 Type *DestIntTy = IntegerType::getIntNTy(Scalar->getContext(), DestWidth);
328 return new BitCastInst(Builder.CreateTrunc(Scalar, DestIntTy), DestTy);
329 }
330 return new TruncInst(Scalar, DestTy);
331 }
332
333 return nullptr;
334}
335
336/// Find elements of V demanded by UserInstr. If returns false, we were not able
337/// to determine all elements.
339 APInt &UnionUsedElts) {
340 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
341
342 switch (UserInstr->getOpcode()) {
343 case Instruction::ExtractElement: {
345 assert(EEI->getVectorOperand() == V);
347 if (EEIIndexC && EEIIndexC->getValue().ult(VWidth)) {
348 UnionUsedElts.setBit(EEIIndexC->getZExtValue());
349 return true;
350 }
351 break;
352 }
353 case Instruction::ShuffleVector: {
354 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(UserInstr);
355 unsigned MaskNumElts =
356 cast<FixedVectorType>(UserInstr->getType())->getNumElements();
357
358 for (auto I : llvm::seq(MaskNumElts)) {
359 unsigned MaskVal = Shuffle->getMaskValue(I);
360 if (MaskVal == -1u || MaskVal >= 2 * VWidth)
361 continue;
362 if (Shuffle->getOperand(0) == V && (MaskVal < VWidth))
363 UnionUsedElts.setBit(MaskVal);
364 if (Shuffle->getOperand(1) == V &&
365 ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth)))
366 UnionUsedElts.setBit(MaskVal - VWidth);
367 }
368 return true;
369 }
370 default:
371 break;
372 }
373
374 return false;
375}
376
377/// Find union of elements of V demanded by all its users.
378/// If it is known by querying findDemandedEltsBySingleUser that
379/// no user demands an element of V, then the corresponding bit
380/// remains unset in the returned value.
382 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
383
384 APInt UnionUsedElts(VWidth, 0);
385 for (const Use &U : V->uses()) {
386 if (Instruction *I = dyn_cast<Instruction>(U.getUser())) {
387 if (!findDemandedEltsBySingleUser(V, I, UnionUsedElts))
388 return APInt::getAllOnes(VWidth);
389 } else {
390 UnionUsedElts = APInt::getAllOnes(VWidth);
391 break;
392 }
393
394 if (UnionUsedElts.isAllOnes())
395 break;
396 }
397
398 return UnionUsedElts;
399}
400
401/// Given a constant index for a extractelement or insertelement instruction,
402/// return it with the canonical type if it isn't already canonical. We
403/// arbitrarily pick 64 bit as our canonical type. The actual bitwidth doesn't
404/// matter, we just want a consistent type to simplify CSE.
406 const unsigned IndexBW = IndexC->getBitWidth();
407 if (IndexBW == 64 || IndexC->getValue().getActiveBits() > 64)
408 return nullptr;
409 return ConstantInt::get(IndexC->getContext(),
410 IndexC->getValue().zextOrTrunc(64));
411}
412
414 Value *SrcVec = EI.getVectorOperand();
415 Value *Index = EI.getIndexOperand();
416 if (Value *V = simplifyExtractElementInst(SrcVec, Index,
417 SQ.getWithInstruction(&EI)))
418 return replaceInstUsesWith(EI, V);
419
420 // extractelt (select %x, %vec1, %vec2), %const ->
421 // select %x, %vec1[%const], %vec2[%const]
422 // TODO: Support constant folding of multiple select operands:
423 // extractelt (select %x, %vec1, %vec2), (select %x, %c1, %c2)
424 // If the extractelement will for instance try to do out of bounds accesses
425 // because of the values of %c1 and/or %c2, the sequence could be optimized
426 // early. This is currently not possible because constant folding will reach
427 // an unreachable assertion if it doesn't find a constant operand.
429 if (SI->getCondition()->getType()->isIntegerTy() &&
431 if (Instruction *R = FoldOpIntoSelect(EI, SI))
432 return R;
433
434 // If extracting a specified index from the vector, see if we can recursively
435 // find a previously computed scalar that was inserted into the vector.
436 auto *IndexC = dyn_cast<ConstantInt>(Index);
437 bool HasKnownValidIndex = false;
438 if (IndexC) {
439 // Canonicalize type of constant indices to i64 to simplify CSE
440 if (auto *NewIdx = getPreferredVectorIndex(IndexC))
441 return replaceOperand(EI, 1, NewIdx);
442
444 unsigned NumElts = EC.getKnownMinValue();
445 HasKnownValidIndex = IndexC->getValue().ult(NumElts);
446
448 Intrinsic::ID IID = II->getIntrinsicID();
449 // Index needs to be lower than the minimum size of the vector, because
450 // for scalable vector, the vector size is known at run time.
451 if (IID == Intrinsic::stepvector && IndexC->getValue().ult(NumElts)) {
452 Type *Ty = EI.getType();
453 unsigned BitWidth = Ty->getIntegerBitWidth();
454 Value *Idx;
455 // Return index when its value does not exceed the allowed limit
456 // for the element type of the vector.
457 // TODO: Truncate out-of-range values.
458 if (IndexC->getValue().getActiveBits() <= BitWidth)
459 Idx = ConstantInt::get(Ty, IndexC->getValue().zextOrTrunc(BitWidth));
460 else
461 return nullptr;
462 return replaceInstUsesWith(EI, Idx);
463 }
464 }
465
466 // InstSimplify should handle cases where the index is invalid.
467 // For fixed-length vector, it's invalid to extract out-of-range element.
468 if (!EC.isScalable() && IndexC->getValue().uge(NumElts))
469 return nullptr;
470
471 if (Instruction *I = foldBitcastExtElt(EI))
472 return I;
473
474 // If there's a vector PHI feeding a scalar use through this extractelement
475 // instruction, try to scalarize the PHI.
476 if (auto *Phi = dyn_cast<PHINode>(SrcVec))
477 if (Instruction *ScalarPHI = scalarizePHI(EI, Phi))
478 return ScalarPHI;
479 }
480
481 // If SrcVec is a subvector starting at index 0, extract from the
482 // wider source vector
483 Value *V;
484 if (match(SrcVec,
486 return ExtractElementInst::Create(V, Index);
487
488 // TODO come up with a n-ary matcher that subsumes both unary and
489 // binary matchers.
490 UnaryOperator *UO;
491 if (match(SrcVec, m_UnOp(UO)) && cheapToScalarize(SrcVec, Index)) {
492 // extelt (unop X), Index --> unop (extelt X, Index)
493 Value *X = UO->getOperand(0);
494 Value *E = Builder.CreateExtractElement(X, Index);
496 }
497
498 // If the binop is not speculatable, we cannot hoist the extractelement if
499 // it may make the operand poison.
500 BinaryOperator *BO;
501 if (match(SrcVec, m_BinOp(BO)) && cheapToScalarize(SrcVec, Index) &&
502 (HasKnownValidIndex ||
504 // extelt (binop X, Y), Index --> binop (extelt X, Index), (extelt Y, Index)
505 Value *X = BO->getOperand(0), *Y = BO->getOperand(1);
506 Value *E0 = Builder.CreateExtractElement(X, Index);
507 Value *E1 = Builder.CreateExtractElement(Y, Index);
508 return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), E0, E1, BO);
509 }
510
511 Value *X, *Y;
512 CmpPredicate Pred;
513 if (match(SrcVec, m_Cmp(Pred, m_Value(X), m_Value(Y))) &&
514 cheapToScalarize(SrcVec, Index)) {
515 // extelt (cmp X, Y), Index --> cmp (extelt X, Index), (extelt Y, Index)
516 Value *E0 = Builder.CreateExtractElement(X, Index);
517 Value *E1 = Builder.CreateExtractElement(Y, Index);
518 CmpInst *SrcCmpInst = cast<CmpInst>(SrcVec);
519 return CmpInst::CreateWithCopiedFlags(SrcCmpInst->getOpcode(), Pred, E0, E1,
520 SrcCmpInst);
521 }
522
523 if (auto *I = dyn_cast<Instruction>(SrcVec)) {
524 if (auto *IE = dyn_cast<InsertElementInst>(I)) {
525 // instsimplify already handled the case where the indices are constants
526 // and equal by value, if both are constants, they must not be the same
527 // value, extract from the pre-inserted value instead.
528 if (isa<Constant>(IE->getOperand(2)) && IndexC)
529 return replaceOperand(EI, 0, IE->getOperand(0));
530 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
531 auto *VecType = cast<VectorType>(GEP->getType());
532 ElementCount EC = VecType->getElementCount();
533 uint64_t IdxVal = IndexC ? IndexC->getZExtValue() : 0;
534 if (IndexC && IdxVal < EC.getKnownMinValue() && GEP->hasOneUse()) {
535 // Find out why we have a vector result - these are a few examples:
536 // 1. We have a scalar pointer and a vector of indices, or
537 // 2. We have a vector of pointers and a scalar index, or
538 // 3. We have a vector of pointers and a vector of indices, etc.
539 // Here we only consider combining when there is exactly one vector
540 // operand, since the optimization is less obviously a win due to
541 // needing more than one extractelements.
542
543 unsigned VectorOps =
544 llvm::count_if(GEP->operands(), [](const Value *V) {
545 return isa<VectorType>(V->getType());
546 });
547 if (VectorOps == 1) {
548 Value *NewPtr = GEP->getPointerOperand();
549 if (isa<VectorType>(NewPtr->getType()))
550 NewPtr = Builder.CreateExtractElement(NewPtr, IndexC);
551
553 for (unsigned I = 1; I != GEP->getNumOperands(); ++I) {
554 Value *Op = GEP->getOperand(I);
555 if (isa<VectorType>(Op->getType()))
556 NewOps.push_back(Builder.CreateExtractElement(Op, IndexC));
557 else
558 NewOps.push_back(Op);
559 }
560
562 GEP->getSourceElementType(), NewPtr, NewOps);
563 NewGEP->setNoWrapFlags(GEP->getNoWrapFlags());
564 return NewGEP;
565 }
566 }
567 } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
568 int SplatIndex = getSplatIndex(SVI->getShuffleMask());
569 // We know the all-0 splat must be reading from the first operand, even
570 // in the case of scalable vectors (vscale is always > 0).
571 if (SplatIndex == 0)
572 return ExtractElementInst::Create(SVI->getOperand(0),
573 Builder.getInt64(0));
574
575 if (isa<FixedVectorType>(SVI->getType())) {
576 std::optional<int> SrcIdx;
577 // getSplatIndex returns -1 to mean not-found.
578 if (SplatIndex != -1)
579 SrcIdx = SplatIndex;
580 else if (ConstantInt *CI = dyn_cast<ConstantInt>(Index))
581 SrcIdx = SVI->getMaskValue(CI->getZExtValue());
582
583 if (SrcIdx) {
584 Value *Src;
585 unsigned LHSWidth =
586 cast<FixedVectorType>(SVI->getOperand(0)->getType())
587 ->getNumElements();
588
589 if (*SrcIdx < 0)
591 if (*SrcIdx < (int)LHSWidth)
592 Src = SVI->getOperand(0);
593 else {
594 *SrcIdx -= LHSWidth;
595 Src = SVI->getOperand(1);
596 }
597 Type *Int64Ty = Type::getInt64Ty(EI.getContext());
599 Src, ConstantInt::get(Int64Ty, *SrcIdx, false));
600 }
601 }
602 } else if (auto *CI = dyn_cast<CastInst>(I)) {
603 // Canonicalize extractelement(cast) -> cast(extractelement).
604 // Bitcasts can change the number of vector elements, and they cost
605 // nothing.
606 // If the CI has only one use, but that use is inside a loop, this
607 // canonicalization is not profitable because it would turn a vector
608 // operation into scalar operations inside the loop. Apply the transform
609 // when:
610 // - the index is constant and CI has one use, or
611 // - the CI and EI are in the same basic block, so the cast won't be sunk
612 // into a loop.
613 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast) &&
614 (EI.getParent() == CI->getParent() || isa<ConstantInt>(Index))) {
615 Value *EE = Builder.CreateExtractElement(CI->getOperand(0), Index);
616 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
617 }
618 }
619 }
620
621 // Run demanded elements after other transforms as this can drop flags on
622 // binops. If there's two paths to the same final result, we prefer the
623 // one which doesn't force us to drop flags.
624 if (IndexC) {
626 unsigned NumElts = EC.getKnownMinValue();
627 // This instruction only demands the single element from the input vector.
628 // Skip for scalable type, the number of elements is unknown at
629 // compile-time.
630 if (!EC.isScalable() && NumElts != 1) {
631 // If the input vector has a single use, simplify it based on this use
632 // property.
633 if (SrcVec->hasOneUse()) {
634 APInt PoisonElts(NumElts, 0);
635 APInt DemandedElts(NumElts, 0);
636 DemandedElts.setBit(IndexC->getZExtValue());
637 if (Value *V =
638 SimplifyDemandedVectorElts(SrcVec, DemandedElts, PoisonElts))
639 return replaceOperand(EI, 0, V);
640 } else {
641 // If the input vector has multiple uses, simplify it based on a union
642 // of all elements used.
643 APInt DemandedElts = findDemandedEltsByAllUsers(SrcVec);
644 if (!DemandedElts.isAllOnes()) {
645 APInt PoisonElts(NumElts, 0);
647 SrcVec, DemandedElts, PoisonElts, 0 /* Depth */,
648 true /* AllowMultipleUsers */)) {
649 if (V != SrcVec) {
650 Worklist.addValue(SrcVec);
651 SrcVec->replaceAllUsesWith(V);
652 return &EI;
653 }
654 }
655 }
656 }
657 }
658 }
659 return nullptr;
660}
661
662/// If V is a shuffle of values that ONLY returns elements from either LHS or
663/// RHS, return the shuffle mask and true. Otherwise, return false.
665 SmallVectorImpl<int> &Mask) {
666 assert(LHS->getType() == RHS->getType() &&
667 "Invalid CollectSingleShuffleElements");
668 unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
669
670 if (match(V, m_Poison())) {
671 Mask.assign(NumElts, -1);
672 return true;
673 }
674
675 if (V == LHS) {
676 for (unsigned i = 0; i != NumElts; ++i)
677 Mask.push_back(i);
678 return true;
679 }
680
681 if (V == RHS) {
682 for (unsigned i = 0; i != NumElts; ++i)
683 Mask.push_back(i + NumElts);
684 return true;
685 }
686
688 // If this is an insert of an extract from some other vector, include it.
689 Value *VecOp = IEI->getOperand(0);
690 Value *ScalarOp = IEI->getOperand(1);
691 Value *IdxOp = IEI->getOperand(2);
692
693 if (!isa<ConstantInt>(IdxOp))
694 return false;
695 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
696
697 if (isa<PoisonValue>(ScalarOp)) { // inserting poison into vector.
698 // We can handle this if the vector we are inserting into is
699 // transitively ok.
700 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
701 // If so, update the mask to reflect the inserted poison.
702 Mask[InsertedIdx] = -1;
703 return true;
704 }
705 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
706 if (isa<ConstantInt>(EI->getOperand(1))) {
707 unsigned ExtractedIdx =
708 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
709 unsigned NumLHSElts =
710 cast<FixedVectorType>(LHS->getType())->getNumElements();
711
712 // This must be extracting from either LHS or RHS.
713 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
714 // We can handle this if the vector we are inserting into is
715 // transitively ok.
716 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
717 // If so, update the mask to reflect the inserted value.
718 if (EI->getOperand(0) == LHS) {
719 Mask[InsertedIdx % NumElts] = ExtractedIdx;
720 } else {
721 assert(EI->getOperand(0) == RHS);
722 Mask[InsertedIdx % NumElts] = ExtractedIdx + NumLHSElts;
723 }
724 return true;
725 }
726 }
727 }
728 }
729 }
730
731 return false;
732}
733
734/// If we have insertion into a vector that is wider than the vector that we
735/// are extracting from, try to widen the source vector to allow a single
736/// shufflevector to replace one or more insert/extract pairs.
738 ExtractElementInst *ExtElt,
739 InstCombinerImpl &IC) {
740 auto *InsVecType = cast<FixedVectorType>(InsElt->getType());
741 auto *ExtVecType = cast<FixedVectorType>(ExtElt->getVectorOperandType());
742 unsigned NumInsElts = InsVecType->getNumElements();
743 unsigned NumExtElts = ExtVecType->getNumElements();
744
745 // The inserted-to vector must be wider than the extracted-from vector.
746 if (InsVecType->getElementType() != ExtVecType->getElementType() ||
747 NumExtElts >= NumInsElts)
748 return false;
749
750 Value *ExtVecOp = ExtElt->getVectorOperand();
751 // Bail out on constant vectors.
752 if (isa<ConstantData>(ExtVecOp))
753 return false;
754
755 // Create a shuffle mask to widen the extended-from vector using poison
756 // values. The mask selects all of the values of the original vector followed
757 // by as many poison values as needed to create a vector of the same length
758 // as the inserted-to vector.
759 SmallVector<int, 16> ExtendMask;
760 for (unsigned i = 0; i < NumExtElts; ++i)
761 ExtendMask.push_back(i);
762 for (unsigned i = NumExtElts; i < NumInsElts; ++i)
763 ExtendMask.push_back(-1);
764
765 auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
766 BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
767 ? ExtVecOpInst->getParent()
768 : ExtElt->getParent();
769
770 // TODO: This restriction matches the basic block check below when creating
771 // new extractelement instructions. If that limitation is removed, this one
772 // could also be removed. But for now, we just bail out to ensure that we
773 // will replace the extractelement instruction that is feeding our
774 // insertelement instruction. This allows the insertelement to then be
775 // replaced by a shufflevector. If the insertelement is not replaced, we can
776 // induce infinite looping because there's an optimization for extractelement
777 // that will delete our widening shuffle. This would trigger another attempt
778 // here to create that shuffle, and we spin forever.
779 if (InsertionBlock != InsElt->getParent())
780 return false;
781
782 // TODO: This restriction matches the check in visitInsertElementInst() and
783 // prevents an infinite loop caused by not turning the extract/insert pair
784 // into a shuffle. We really should not need either check, but we're lacking
785 // folds for shufflevectors because we're afraid to generate shuffle masks
786 // that the backend can't handle.
787 if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
788 return false;
789
790 auto *WideVec = new ShuffleVectorInst(ExtVecOp, ExtendMask);
791
792 // Insert the new shuffle after the vector operand of the extract is defined
793 // (as long as it's not a PHI) or at the start of the basic block of the
794 // extract, so any subsequent extracts in the same basic block can use it.
795 // TODO: Insert before the earliest ExtractElementInst that is replaced.
796 if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
797 WideVec->insertAfter(ExtVecOpInst->getIterator());
798 else
799 IC.InsertNewInstWith(WideVec, ExtElt->getParent()->getFirstInsertionPt());
800
801 // WideVec is an extension of ExtVecOp to produce a more useful value for
802 // ExtractElement instructions. If ExtVecOp is an instruction, adopt its
803 // DebugLoc; if it is not, then this is materializing a constant value, so set
804 // a CompilerGenerated location.
805 if (ExtVecOpInst)
806 WideVec->setDebugLoc(ExtVecOpInst->getDebugLoc());
807 else
808 WideVec->setDebugLoc(DebugLoc::getCompilerGenerated());
809
810 // Replace extracts from the original narrow vector with extracts from the new
811 // wide vector.
812 for (User *U : ExtVecOp->users()) {
814 if (!OldExt || OldExt->getParent() != WideVec->getParent())
815 continue;
816 auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
817 IC.InsertNewInstWith(NewExt, OldExt->getIterator());
818 IC.replaceInstUsesWith(*OldExt, NewExt);
819 // Add the old extracts to the worklist for DCE. We can't remove the
820 // extracts directly, because they may still be used by the calling code.
821 IC.addToWorklist(OldExt);
822 }
823
824 return true;
825}
826
827/// We are building a shuffle to create V, which is a sequence of insertelement,
828/// extractelement pairs. If PermittedRHS is set, then we must either use it or
829/// not rely on the second vector source. Return a std::pair containing the
830/// left and right vectors of the proposed shuffle (or 0), and set the Mask
831/// parameter as required.
832///
833/// Note: we intentionally don't try to fold earlier shuffles since they have
834/// often been chosen carefully to be efficiently implementable on the target.
835using ShuffleOps = std::pair<Value *, Value *>;
836
838 Value *PermittedRHS,
839 InstCombinerImpl &IC, bool &Rerun) {
840 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
841 unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
842
843 if (match(V, m_Poison())) {
844 Mask.assign(NumElts, -1);
845 return std::make_pair(
846 PermittedRHS ? PoisonValue::get(PermittedRHS->getType()) : V, nullptr);
847 }
848
850 Mask.assign(NumElts, 0);
851 return std::make_pair(V, nullptr);
852 }
853
855 // If this is an insert of an extract from some other vector, include it.
856 Value *VecOp = IEI->getOperand(0);
857 Value *ScalarOp = IEI->getOperand(1);
858 Value *IdxOp = IEI->getOperand(2);
859
861 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
862 unsigned ExtractedIdx =
863 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
864 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
865
866 // Either the extracted from or inserted into vector must be RHSVec,
867 // otherwise we'd end up with a shuffle of three inputs.
868 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
869 Value *RHS = EI->getOperand(0);
870 ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC, Rerun);
871 assert(LR.second == nullptr || LR.second == RHS);
872
873 if (LR.first->getType() != RHS->getType()) {
874 // Although we are giving up for now, see if we can create extracts
875 // that match the inserts for another round of combining.
876 if (replaceExtractElements(IEI, EI, IC))
877 Rerun = true;
878
879 // We tried our best, but we can't find anything compatible with RHS
880 // further up the chain. Return a trivial shuffle.
881 for (unsigned i = 0; i < NumElts; ++i)
882 Mask[i] = i;
883 return std::make_pair(V, nullptr);
884 }
885
886 unsigned NumLHSElts =
887 cast<FixedVectorType>(RHS->getType())->getNumElements();
888 Mask[InsertedIdx % NumElts] = NumLHSElts + ExtractedIdx;
889 return std::make_pair(LR.first, RHS);
890 }
891
892 if (VecOp == PermittedRHS) {
893 // We've gone as far as we can: anything on the other side of the
894 // extractelement will already have been converted into a shuffle.
895 unsigned NumLHSElts =
897 ->getNumElements();
898 for (unsigned i = 0; i != NumElts; ++i)
899 Mask.push_back(i == InsertedIdx ? ExtractedIdx : NumLHSElts + i);
900 return std::make_pair(EI->getOperand(0), PermittedRHS);
901 }
902
903 // If this insertelement is a chain that comes from exactly these two
904 // vectors, return the vector and the effective shuffle.
905 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
906 collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
907 Mask))
908 return std::make_pair(EI->getOperand(0), PermittedRHS);
909 }
910 }
911 }
912
913 // Otherwise, we can't do anything fancy. Return an identity vector.
914 for (unsigned i = 0; i != NumElts; ++i)
915 Mask.push_back(i);
916 return std::make_pair(V, nullptr);
917}
918
919/// Look for chain of insertvalue's that fully define an aggregate, and trace
920/// back the values inserted, see if they are all were extractvalue'd from
921/// the same source aggregate from the exact same element indexes.
922/// If they were, just reuse the source aggregate.
923/// This potentially deals with PHI indirections.
925 InsertValueInst &OrigIVI) {
926 Type *AggTy = OrigIVI.getType();
927 unsigned NumAggElts;
928 switch (AggTy->getTypeID()) {
929 case Type::StructTyID:
930 NumAggElts = AggTy->getStructNumElements();
931 break;
932 case Type::ArrayTyID:
933 NumAggElts = AggTy->getArrayNumElements();
934 break;
935 default:
936 llvm_unreachable("Unhandled aggregate type?");
937 }
938
939 // Arbitrary aggregate size cut-off. Motivation for limit of 2 is to be able
940 // to handle clang C++ exception struct (which is hardcoded as {i8*, i32}),
941 // FIXME: any interesting patterns to be caught with larger limit?
942 assert(NumAggElts > 0 && "Aggregate should have elements.");
943 if (NumAggElts > 2)
944 return nullptr;
945
946 static constexpr auto NotFound = std::nullopt;
947 static constexpr auto FoundMismatch = nullptr;
948
949 // Try to find a value of each element of an aggregate.
950 // FIXME: deal with more complex, not one-dimensional, aggregate types
951 SmallVector<std::optional<Instruction *>, 2> AggElts(NumAggElts, NotFound);
952
953 // Do we know values for each element of the aggregate?
954 auto KnowAllElts = [&AggElts]() {
955 return !llvm::is_contained(AggElts, NotFound);
956 };
957
958 int Depth = 0;
959
960 // Arbitrary `insertvalue` visitation depth limit. Let's be okay with
961 // every element being overwritten twice, which should never happen.
962 static const int DepthLimit = 2 * NumAggElts;
963
964 // Recurse up the chain of `insertvalue` aggregate operands until either we've
965 // reconstructed full initializer or can't visit any more `insertvalue`'s.
966 for (InsertValueInst *CurrIVI = &OrigIVI;
967 Depth < DepthLimit && CurrIVI && !KnowAllElts();
968 CurrIVI = dyn_cast<InsertValueInst>(CurrIVI->getAggregateOperand()),
969 ++Depth) {
970 auto *InsertedValue =
971 dyn_cast<Instruction>(CurrIVI->getInsertedValueOperand());
972 if (!InsertedValue)
973 return nullptr; // Inserted value must be produced by an instruction.
974
975 ArrayRef<unsigned int> Indices = CurrIVI->getIndices();
976
977 // Don't bother with more than single-level aggregates.
978 if (Indices.size() != 1)
979 return nullptr; // FIXME: deal with more complex aggregates?
980
981 // Now, we may have already previously recorded the value for this element
982 // of an aggregate. If we did, that means the CurrIVI will later be
983 // overwritten with the already-recorded value. But if not, let's record it!
984 std::optional<Instruction *> &Elt = AggElts[Indices.front()];
985 Elt = Elt.value_or(InsertedValue);
986
987 // FIXME: should we handle chain-terminating undef base operand?
988 }
989
990 // Was that sufficient to deduce the full initializer for the aggregate?
991 if (!KnowAllElts())
992 return nullptr; // Give up then.
993
994 // We now want to find the source[s] of the aggregate elements we've found.
995 // And with "source" we mean the original aggregate[s] from which
996 // the inserted elements were extracted. This may require PHI translation.
997
998 enum class AggregateDescription {
999 /// When analyzing the value that was inserted into an aggregate, we did
1000 /// not manage to find defining `extractvalue` instruction to analyze.
1001 NotFound,
1002 /// When analyzing the value that was inserted into an aggregate, we did
1003 /// manage to find defining `extractvalue` instruction[s], and everything
1004 /// matched perfectly - aggregate type, element insertion/extraction index.
1005 Found,
1006 /// When analyzing the value that was inserted into an aggregate, we did
1007 /// manage to find defining `extractvalue` instruction, but there was
1008 /// a mismatch: either the source type from which the extraction was didn't
1009 /// match the aggregate type into which the insertion was,
1010 /// or the extraction/insertion channels mismatched,
1011 /// or different elements had different source aggregates.
1012 FoundMismatch
1013 };
1014 auto Describe = [](std::optional<Value *> SourceAggregate) {
1015 if (SourceAggregate == NotFound)
1016 return AggregateDescription::NotFound;
1017 if (*SourceAggregate == FoundMismatch)
1018 return AggregateDescription::FoundMismatch;
1019 return AggregateDescription::Found;
1020 };
1021
1022 // If an aggregate element is defined in UseBB, we can't use it in PredBB.
1023 bool EltDefinedInUseBB = false;
1024
1025 // Given the value \p Elt that was being inserted into element \p EltIdx of an
1026 // aggregate AggTy, see if \p Elt was originally defined by an
1027 // appropriate extractvalue (same element index, same aggregate type).
1028 // If found, return the source aggregate from which the extraction was.
1029 // If \p PredBB is provided, does PHI translation of an \p Elt first.
1030 auto FindSourceAggregate =
1031 [&](Instruction *Elt, unsigned EltIdx, std::optional<BasicBlock *> UseBB,
1032 std::optional<BasicBlock *> PredBB) -> std::optional<Value *> {
1033 // For now(?), only deal with, at most, a single level of PHI indirection.
1034 if (UseBB && PredBB) {
1035 Elt = dyn_cast<Instruction>(Elt->DoPHITranslation(*UseBB, *PredBB));
1036 if (Elt && Elt->getParent() == *UseBB)
1037 EltDefinedInUseBB = true;
1038 }
1039 // FIXME: deal with multiple levels of PHI indirection?
1040
1041 // Did we find an extraction?
1042 auto *EVI = dyn_cast_or_null<ExtractValueInst>(Elt);
1043 if (!EVI)
1044 return NotFound;
1045
1046 Value *SourceAggregate = EVI->getAggregateOperand();
1047
1048 // Is the extraction from the same type into which the insertion was?
1049 if (SourceAggregate->getType() != AggTy)
1050 return FoundMismatch;
1051 // And the element index doesn't change between extraction and insertion?
1052 if (EVI->getNumIndices() != 1 || EltIdx != EVI->getIndices().front())
1053 return FoundMismatch;
1054
1055 return SourceAggregate; // AggregateDescription::Found
1056 };
1057
1058 // Given elements AggElts that were constructing an aggregate OrigIVI,
1059 // see if we can find appropriate source aggregate for each of the elements,
1060 // and see it's the same aggregate for each element. If so, return it.
1061 auto FindCommonSourceAggregate =
1062 [&](std::optional<BasicBlock *> UseBB,
1063 std::optional<BasicBlock *> PredBB) -> std::optional<Value *> {
1064 std::optional<Value *> SourceAggregate;
1065
1066 for (auto I : enumerate(AggElts)) {
1067 assert(Describe(SourceAggregate) != AggregateDescription::FoundMismatch &&
1068 "We don't store nullptr in SourceAggregate!");
1069 assert((Describe(SourceAggregate) == AggregateDescription::Found) ==
1070 (I.index() != 0) &&
1071 "SourceAggregate should be valid after the first element,");
1072
1073 // For this element, is there a plausible source aggregate?
1074 // FIXME: we could special-case undef element, IFF we know that in the
1075 // source aggregate said element isn't poison.
1076 std::optional<Value *> SourceAggregateForElement =
1077 FindSourceAggregate(*I.value(), I.index(), UseBB, PredBB);
1078
1079 // Okay, what have we found? Does that correlate with previous findings?
1080
1081 // Regardless of whether or not we have previously found source
1082 // aggregate for previous elements (if any), if we didn't find one for
1083 // this element, passthrough whatever we have just found.
1084 if (Describe(SourceAggregateForElement) != AggregateDescription::Found)
1085 return SourceAggregateForElement;
1086
1087 // Okay, we have found source aggregate for this element.
1088 // Let's see what we already know from previous elements, if any.
1089 switch (Describe(SourceAggregate)) {
1090 case AggregateDescription::NotFound:
1091 // This is apparently the first element that we have examined.
1092 SourceAggregate = SourceAggregateForElement; // Record the aggregate!
1093 continue; // Great, now look at next element.
1094 case AggregateDescription::Found:
1095 // We have previously already successfully examined other elements.
1096 // Is this the same source aggregate we've found for other elements?
1097 if (*SourceAggregateForElement != *SourceAggregate)
1098 return FoundMismatch;
1099 continue; // Still the same aggregate, look at next element.
1100 case AggregateDescription::FoundMismatch:
1101 llvm_unreachable("Can't happen. We would have early-exited then.");
1102 };
1103 }
1104
1105 assert(Describe(SourceAggregate) == AggregateDescription::Found &&
1106 "Must be a valid Value");
1107 return *SourceAggregate;
1108 };
1109
1110 std::optional<Value *> SourceAggregate;
1111
1112 // Can we find the source aggregate without looking at predecessors?
1113 SourceAggregate = FindCommonSourceAggregate(/*UseBB=*/std::nullopt,
1114 /*PredBB=*/std::nullopt);
1115 if (Describe(SourceAggregate) != AggregateDescription::NotFound) {
1116 if (Describe(SourceAggregate) == AggregateDescription::FoundMismatch)
1117 return nullptr; // Conflicting source aggregates!
1118 ++NumAggregateReconstructionsSimplified;
1119 return replaceInstUsesWith(OrigIVI, *SourceAggregate);
1120 }
1121
1122 // Okay, apparently we need to look at predecessors.
1123
1124 // We should be smart about picking the "use" basic block, which will be the
1125 // merge point for aggregate, where we'll insert the final PHI that will be
1126 // used instead of OrigIVI. Basic block of OrigIVI is *not* the right choice.
1127 // We should look in which blocks each of the AggElts is being defined,
1128 // they all should be defined in the same basic block.
1129 BasicBlock *UseBB = nullptr;
1130
1131 for (const std::optional<Instruction *> &I : AggElts) {
1132 BasicBlock *BB = (*I)->getParent();
1133 // If it's the first instruction we've encountered, record the basic block.
1134 if (!UseBB) {
1135 UseBB = BB;
1136 continue;
1137 }
1138 // Otherwise, this must be the same basic block we've seen previously.
1139 if (UseBB != BB)
1140 return nullptr;
1141 }
1142
1143 // If *all* of the elements are basic-block-independent, meaning they are
1144 // either function arguments, or constant expressions, then if we didn't
1145 // handle them without predecessor-aware handling, we won't handle them now.
1146 if (!UseBB)
1147 return nullptr;
1148
1149 // If we didn't manage to find source aggregate without looking at
1150 // predecessors, and there are no predecessors to look at, then we're done.
1151 if (pred_empty(UseBB))
1152 return nullptr;
1153
1154 // Arbitrary predecessor count limit.
1155 static const int PredCountLimit = 64;
1156
1157 // Cache the (non-uniqified!) list of predecessors in a vector,
1158 // checking the limit at the same time for efficiency.
1159 SmallVector<BasicBlock *, 4> Preds; // May have duplicates!
1160 for (BasicBlock *Pred : predecessors(UseBB)) {
1161 // Don't bother if there are too many predecessors.
1162 if (Preds.size() >= PredCountLimit) // FIXME: only count duplicates once?
1163 return nullptr;
1164 Preds.emplace_back(Pred);
1165 }
1166
1167 // For each predecessor, what is the source aggregate,
1168 // from which all the elements were originally extracted from?
1169 // Note that we want for the map to have stable iteration order!
1171 bool FoundSrcAgg = false;
1172 for (BasicBlock *Pred : Preds) {
1173 std::pair<decltype(SourceAggregates)::iterator, bool> IV =
1174 SourceAggregates.try_emplace(Pred);
1175 // Did we already evaluate this predecessor?
1176 if (!IV.second)
1177 continue;
1178
1179 // Let's hope that when coming from predecessor Pred, all elements of the
1180 // aggregate produced by OrigIVI must have been originally extracted from
1181 // the same aggregate. Is that so? Can we find said original aggregate?
1182 SourceAggregate = FindCommonSourceAggregate(UseBB, Pred);
1183 if (Describe(SourceAggregate) == AggregateDescription::Found) {
1184 FoundSrcAgg = true;
1185 IV.first->second = *SourceAggregate;
1186 } else {
1187 // If UseBB is the single successor of Pred, we can add InsertValue to
1188 // Pred.
1189 auto *BI = dyn_cast<UncondBrInst>(Pred->getTerminator());
1190 if (!BI)
1191 return nullptr;
1192 }
1193 }
1194
1195 if (!FoundSrcAgg)
1196 return nullptr;
1197
1198 // Do some sanity check if we need to add insertvalue into predecessors.
1199 auto OrigBB = OrigIVI.getParent();
1200 for (auto &It : SourceAggregates) {
1201 if (Describe(It.second) == AggregateDescription::Found)
1202 continue;
1203
1204 // Element is defined in UseBB, so it can't be used in predecessors.
1205 if (EltDefinedInUseBB)
1206 return nullptr;
1207
1208 // Do this transformation cross loop boundary may cause dead loop. So we
1209 // should avoid this situation. But LoopInfo is not generally available, we
1210 // must be conservative here.
1211 // If OrigIVI is in UseBB and it's the only successor of PredBB, PredBB
1212 // can't be in inner loop.
1213 if (UseBB != OrigBB)
1214 return nullptr;
1215
1216 // Avoid constructing constant aggregate because constant value may expose
1217 // more optimizations.
1218 bool ConstAgg = true;
1219 for (auto Val : AggElts) {
1220 Value *Elt = (*Val)->DoPHITranslation(UseBB, It.first);
1221 if (!isa<Constant>(Elt)) {
1222 ConstAgg = false;
1223 break;
1224 }
1225 }
1226 if (ConstAgg)
1227 return nullptr;
1228 }
1229
1230 // For predecessors without appropriate source aggregate, create one in the
1231 // predecessor.
1232 for (auto &It : SourceAggregates) {
1233 if (Describe(It.second) == AggregateDescription::Found)
1234 continue;
1235
1236 BasicBlock *Pred = It.first;
1237 Builder.SetInsertPoint(Pred->getTerminator());
1238 Value *V = PoisonValue::get(AggTy);
1239 for (auto [Idx, Val] : enumerate(AggElts)) {
1240 Value *Elt = (*Val)->DoPHITranslation(UseBB, Pred);
1241 V = Builder.CreateInsertValue(V, Elt, Idx);
1242 }
1243
1244 It.second = V;
1245 }
1246
1247 // All good! Now we just need to thread the source aggregates here.
1248 // Note that we have to insert the new PHI here, ourselves, because we can't
1249 // rely on InstCombinerImpl::run() inserting it into the right basic block.
1250 // Note that the same block can be a predecessor more than once,
1251 // and we need to preserve that invariant for the PHI node.
1253 Builder.SetInsertPoint(UseBB, UseBB->getFirstNonPHIIt());
1254 auto *PHI =
1255 Builder.CreatePHI(AggTy, Preds.size(), OrigIVI.getName() + ".merged");
1256 for (BasicBlock *Pred : Preds)
1257 PHI->addIncoming(SourceAggregates[Pred], Pred);
1258
1259 ++NumAggregateReconstructionsSimplified;
1260 return replaceInstUsesWith(OrigIVI, PHI);
1261}
1262
1263/// Try to find redundant insertvalue instructions, like the following ones:
1264/// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
1265/// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
1266/// Here the second instruction inserts values at the same indices, as the
1267/// first one, making the first one redundant.
1268/// It should be transformed to:
1269/// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
1272 I.getAggregateOperand(), I.getInsertedValueOperand(), I.getIndices(),
1273 SQ.getWithInstruction(&I)))
1274 return replaceInstUsesWith(I, V);
1275
1276 bool IsRedundant = false;
1277 ArrayRef<unsigned int> FirstIndices = I.getIndices();
1278
1279 // If there is a chain of insertvalue instructions (each of them except the
1280 // last one has only one use and it's another insertvalue insn from this
1281 // chain), check if any of the 'children' uses the same indices as the first
1282 // instruction. In this case, the first one is redundant.
1283 Value *V = &I;
1284 unsigned Depth = 0;
1285 while (V->hasOneUse() && Depth < 10) {
1286 User *U = V->user_back();
1287 auto UserInsInst = dyn_cast<InsertValueInst>(U);
1288 if (!UserInsInst || U->getOperand(0) != V)
1289 break;
1290 if (UserInsInst->getIndices() == FirstIndices) {
1291 IsRedundant = true;
1292 break;
1293 }
1294 V = UserInsInst;
1295 Depth++;
1296 }
1297
1298 if (IsRedundant)
1299 return replaceInstUsesWith(I, I.getOperand(0));
1300
1302 return NewI;
1303
1304 return nullptr;
1305}
1306
1308 // Can not analyze scalable type, the number of elements is not a compile-time
1309 // constant.
1311 return false;
1312
1313 int MaskSize = Shuf.getShuffleMask().size();
1314 int VecSize =
1315 cast<FixedVectorType>(Shuf.getOperand(0)->getType())->getNumElements();
1316
1317 // A vector select does not change the size of the operands.
1318 if (MaskSize != VecSize)
1319 return false;
1320
1321 // Each mask element must be undefined or choose a vector element from one of
1322 // the source operands without crossing vector lanes.
1323 for (int i = 0; i != MaskSize; ++i) {
1324 int Elt = Shuf.getMaskValue(i);
1325 if (Elt != -1 && Elt != i && Elt != i + VecSize)
1326 return false;
1327 }
1328
1329 return true;
1330}
1331
1332/// Turn a chain of inserts that splats a value into an insert + shuffle:
1333/// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
1334/// shufflevector(insertelt(X, %k, 0), poison, zero)
1336 // We are interested in the last insert in a chain. So if this insert has a
1337 // single user and that user is an insert, bail.
1338 if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
1339 return nullptr;
1340
1341 VectorType *VecTy = InsElt.getType();
1342 // Can not handle scalable type, the number of elements is not a compile-time
1343 // constant.
1344 if (isa<ScalableVectorType>(VecTy))
1345 return nullptr;
1346 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1347
1348 // Do not try to do this for a one-element vector, since that's a nop,
1349 // and will cause an inf-loop.
1350 if (NumElements == 1)
1351 return nullptr;
1352
1353 Value *SplatVal = InsElt.getOperand(1);
1354 InsertElementInst *CurrIE = &InsElt;
1355 SmallBitVector ElementPresent(NumElements, false);
1356 InsertElementInst *FirstIE = nullptr;
1357
1358 // Walk the chain backwards, keeping track of which indices we inserted into,
1359 // until we hit something that isn't an insert of the splatted value.
1360 while (CurrIE) {
1361 auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
1362 if (!Idx || CurrIE->getOperand(1) != SplatVal)
1363 return nullptr;
1364
1365 auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
1366 // Check none of the intermediate steps have any additional uses, except
1367 // for the root insertelement instruction, which can be re-used, if it
1368 // inserts at position 0.
1369 if (CurrIE != &InsElt &&
1370 (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero())))
1371 return nullptr;
1372
1373 ElementPresent[Idx->getZExtValue()] = true;
1374 FirstIE = CurrIE;
1375 CurrIE = NextIE;
1376 }
1377
1378 // If this is just a single insertelement (not a sequence), we are done.
1379 if (FirstIE == &InsElt)
1380 return nullptr;
1381
1382 // If we are not inserting into a poison vector, make sure we've seen an
1383 // insert into every element.
1384 // TODO: If the base vector is not undef, it might be better to create a splat
1385 // and then a select-shuffle (blend) with the base vector.
1386 if (!match(FirstIE->getOperand(0), m_Poison()))
1387 if (!ElementPresent.all())
1388 return nullptr;
1389
1390 // Create the insert + shuffle.
1391 Type *Int64Ty = Type::getInt64Ty(InsElt.getContext());
1392 PoisonValue *PoisonVec = PoisonValue::get(VecTy);
1393 Constant *Zero = ConstantInt::get(Int64Ty, 0);
1394 if (!cast<ConstantInt>(FirstIE->getOperand(2))->isZero())
1395 FirstIE = InsertElementInst::Create(PoisonVec, SplatVal, Zero, "",
1396 InsElt.getIterator());
1397
1398 // Splat from element 0, but replace absent elements with poison in the mask.
1399 SmallVector<int, 16> Mask(NumElements, 0);
1400 for (unsigned i = 0; i != NumElements; ++i)
1401 if (!ElementPresent[i])
1402 Mask[i] = -1;
1403
1404 return new ShuffleVectorInst(FirstIE, Mask);
1405}
1406
1407/// Try to fold an insert element into an existing splat shuffle by changing
1408/// the shuffle's mask to include the index of this insert element.
1410 // Check if the vector operand of this insert is a canonical splat shuffle.
1411 auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
1412 if (!Shuf || !Shuf->isZeroEltSplat())
1413 return nullptr;
1414
1415 // Bail out early if shuffle is scalable type. The number of elements in
1416 // shuffle mask is unknown at compile-time.
1417 if (isa<ScalableVectorType>(Shuf->getType()))
1418 return nullptr;
1419
1420 // Check for a constant insertion index.
1421 uint64_t IdxC;
1422 if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
1423 return nullptr;
1424
1425 // Check if the splat shuffle's input is the same as this insert's scalar op.
1426 Value *X = InsElt.getOperand(1);
1427 Value *Op0 = Shuf->getOperand(0);
1428 if (!match(Op0, m_InsertElt(m_Undef(), m_Specific(X), m_ZeroInt())))
1429 return nullptr;
1430
1431 // Replace the shuffle mask element at the index of this insert with a zero.
1432 // For example:
1433 // inselt (shuf (inselt undef, X, 0), _, <0,undef,0,undef>), X, 1
1434 // --> shuf (inselt undef, X, 0), poison, <0,0,0,undef>
1435 unsigned NumMaskElts =
1436 cast<FixedVectorType>(Shuf->getType())->getNumElements();
1437 SmallVector<int, 16> NewMask(NumMaskElts);
1438 for (unsigned i = 0; i != NumMaskElts; ++i)
1439 NewMask[i] = i == IdxC ? 0 : Shuf->getMaskValue(i);
1440
1441 return new ShuffleVectorInst(Op0, NewMask);
1442}
1443
1444/// Try to fold an extract+insert element into an existing identity shuffle by
1445/// changing the shuffle's mask to include the index of this insert element.
1447 // Check if the vector operand of this insert is an identity shuffle.
1448 auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
1449 if (!Shuf || !match(Shuf->getOperand(1), m_Poison()) ||
1450 !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding()))
1451 return nullptr;
1452
1453 // Bail out early if shuffle is scalable type. The number of elements in
1454 // shuffle mask is unknown at compile-time.
1455 if (isa<ScalableVectorType>(Shuf->getType()))
1456 return nullptr;
1457
1458 // Check for a constant insertion index.
1459 uint64_t IdxC;
1460 if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
1461 return nullptr;
1462
1463 // Check if this insert's scalar op is extracted from the identity shuffle's
1464 // input vector.
1465 Value *Scalar = InsElt.getOperand(1);
1466 Value *X = Shuf->getOperand(0);
1467 if (!match(Scalar, m_ExtractElt(m_Specific(X), m_SpecificInt(IdxC))))
1468 return nullptr;
1469
1470 // Replace the shuffle mask element at the index of this extract+insert with
1471 // that same index value.
1472 // For example:
1473 // inselt (shuf X, IdMask), (extelt X, IdxC), IdxC --> shuf X, IdMask'
1474 unsigned NumMaskElts =
1475 cast<FixedVectorType>(Shuf->getType())->getNumElements();
1476 SmallVector<int, 16> NewMask(NumMaskElts);
1477 ArrayRef<int> OldMask = Shuf->getShuffleMask();
1478 for (unsigned i = 0; i != NumMaskElts; ++i) {
1479 if (i != IdxC) {
1480 // All mask elements besides the inserted element remain the same.
1481 NewMask[i] = OldMask[i];
1482 } else if (OldMask[i] == (int)IdxC) {
1483 // If the mask element was already set, there's nothing to do
1484 // (demanded elements analysis may unset it later).
1485 return nullptr;
1486 } else {
1487 assert(OldMask[i] == PoisonMaskElem &&
1488 "Unexpected shuffle mask element for identity shuffle");
1489 NewMask[i] = IdxC;
1490 }
1491 }
1492
1493 return new ShuffleVectorInst(X, Shuf->getOperand(1), NewMask);
1494}
1495
1496/// If we have an insertelement instruction feeding into another insertelement
1497/// and the 2nd is inserting a constant into the vector, canonicalize that
1498/// constant insertion before the insertion of a variable:
1499///
1500/// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
1501/// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
1502///
1503/// This has the potential of eliminating the 2nd insertelement instruction
1504/// via constant folding of the scalar constant into a vector constant.
1506 InstCombiner::BuilderTy &Builder) {
1507 auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
1508 if (!InsElt1 || !InsElt1->hasOneUse())
1509 return nullptr;
1510
1511 Value *X, *Y;
1512 Constant *ScalarC;
1513 ConstantInt *IdxC1, *IdxC2;
1514 if (match(InsElt1->getOperand(0), m_Value(X)) &&
1515 match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
1516 match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
1517 match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
1518 match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
1519 Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
1520 return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
1521 }
1522
1523 return nullptr;
1524}
1525
1526/// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
1527/// --> shufflevector X, CVec', Mask'
1529 auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
1530 // Bail out if the parent has more than one use. In that case, we'd be
1531 // replacing the insertelt with a shuffle, and that's not a clear win.
1532 if (!Inst || !Inst->hasOneUse())
1533 return nullptr;
1534 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
1535 // The shuffle must have a constant vector operand. The insertelt must have
1536 // a constant scalar being inserted at a constant position in the vector.
1537 Constant *ShufConstVec, *InsEltScalar;
1538 uint64_t InsEltIndex;
1539 if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
1540 !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
1541 !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
1542 return nullptr;
1543
1544 // Adding an element to an arbitrary shuffle could be expensive, but a
1545 // shuffle that selects elements from vectors without crossing lanes is
1546 // assumed cheap.
1547 // If we're just adding a constant into that shuffle, it will still be
1548 // cheap.
1549 if (!isShuffleEquivalentToSelect(*Shuf))
1550 return nullptr;
1551
1552 // From the above 'select' check, we know that the mask has the same number
1553 // of elements as the vector input operands. We also know that each constant
1554 // input element is used in its lane and can not be used more than once by
1555 // the shuffle. Therefore, replace the constant in the shuffle's constant
1556 // vector with the insertelt constant. Replace the constant in the shuffle's
1557 // mask vector with the insertelt index plus the length of the vector
1558 // (because the constant vector operand of a shuffle is always the 2nd
1559 // operand).
1560 ArrayRef<int> Mask = Shuf->getShuffleMask();
1561 unsigned NumElts = Mask.size();
1562 SmallVector<Constant *, 16> NewShufElts(NumElts);
1563 SmallVector<int, 16> NewMaskElts(NumElts);
1564 for (unsigned I = 0; I != NumElts; ++I) {
1565 if (I == InsEltIndex) {
1566 NewShufElts[I] = InsEltScalar;
1567 NewMaskElts[I] = InsEltIndex + NumElts;
1568 } else {
1569 // Copy over the existing values.
1570 NewShufElts[I] = ShufConstVec->getAggregateElement(I);
1571 NewMaskElts[I] = Mask[I];
1572 }
1573
1574 // Bail if we failed to find an element.
1575 if (!NewShufElts[I])
1576 return nullptr;
1577 }
1578
1579 // Create new operands for a shuffle that includes the constant of the
1580 // original insertelt. The old shuffle will be dead now.
1581 return new ShuffleVectorInst(Shuf->getOperand(0),
1582 ConstantVector::get(NewShufElts), NewMaskElts);
1583 } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
1584 // Transform sequences of insertelements ops with constant data/indexes into
1585 // a single shuffle op.
1586 // Can not handle scalable type, the number of elements needed to create
1587 // shuffle mask is not a compile-time constant.
1588 if (isa<ScalableVectorType>(InsElt.getType()))
1589 return nullptr;
1590 unsigned NumElts =
1591 cast<FixedVectorType>(InsElt.getType())->getNumElements();
1592
1593 uint64_t InsertIdx[2];
1594 Constant *Val[2];
1595 if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
1596 !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
1597 !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
1598 !match(IEI->getOperand(1), m_Constant(Val[1])))
1599 return nullptr;
1601 SmallVector<int, 16> Mask(NumElts);
1602 auto ValI = std::begin(Val);
1603 // Generate new constant vector and mask.
1604 // We have 2 values/masks from the insertelements instructions. Insert them
1605 // into new value/mask vectors.
1606 for (uint64_t I : InsertIdx) {
1607 if (!Values[I]) {
1608 Values[I] = *ValI;
1609 Mask[I] = NumElts + I;
1610 }
1611 ++ValI;
1612 }
1613 // Remaining values are filled with 'poison' values.
1614 for (unsigned I = 0; I < NumElts; ++I) {
1615 if (!Values[I]) {
1617 Mask[I] = I;
1618 }
1619 }
1620 // Create new operands for a shuffle that includes the constant of the
1621 // original insertelt.
1622 return new ShuffleVectorInst(IEI->getOperand(0),
1624 }
1625 return nullptr;
1626}
1627
1628/// If both the base vector and the inserted element are extended from the same
1629/// type, do the insert element in the narrow source type followed by extend.
1630/// TODO: This can be extended to include other cast opcodes, but particularly
1631/// if we create a wider insertelement, make sure codegen is not harmed.
1633 InstCombiner::BuilderTy &Builder) {
1634 // We are creating a vector extend. If the original vector extend has another
1635 // use, that would mean we end up with 2 vector extends, so avoid that.
1636 // TODO: We could ease the use-clause to "if at least one op has one use"
1637 // (assuming that the source types match - see next TODO comment).
1638 Value *Vec = InsElt.getOperand(0);
1639 if (!Vec->hasOneUse())
1640 return nullptr;
1641
1642 Value *Scalar = InsElt.getOperand(1);
1643 Value *X, *Y;
1644 CastInst::CastOps CastOpcode;
1645 if (match(Vec, m_FPExt(m_Value(X))) && match(Scalar, m_FPExt(m_Value(Y))))
1646 CastOpcode = Instruction::FPExt;
1647 else if (match(Vec, m_SExt(m_Value(X))) && match(Scalar, m_SExt(m_Value(Y))))
1648 CastOpcode = Instruction::SExt;
1649 else if (match(Vec, m_ZExt(m_Value(X))) && match(Scalar, m_ZExt(m_Value(Y))))
1650 CastOpcode = Instruction::ZExt;
1651 else
1652 return nullptr;
1653
1654 // TODO: We can allow mismatched types by creating an intermediate cast.
1655 if (X->getType()->getScalarType() != Y->getType())
1656 return nullptr;
1657
1658 // inselt (ext X), (ext Y), Index --> ext (inselt X, Y, Index)
1659 Value *NewInsElt = Builder.CreateInsertElement(X, Y, InsElt.getOperand(2));
1660 return CastInst::Create(CastOpcode, NewInsElt, InsElt.getType());
1661}
1662
1663/// If we are inserting 2 halves of a value into adjacent elements of a vector,
1664/// try to convert to a single insert with appropriate bitcasts.
1666 bool IsBigEndian,
1667 InstCombiner::BuilderTy &Builder) {
1668 Value *VecOp = InsElt.getOperand(0);
1669 Value *ScalarOp = InsElt.getOperand(1);
1670 Value *IndexOp = InsElt.getOperand(2);
1671
1672 // Pattern depends on endian because we expect lower index is inserted first.
1673 // Big endian:
1674 // inselt (inselt BaseVec, (trunc (lshr X, BW/2), Index0), (trunc X), Index1
1675 // Little endian:
1676 // inselt (inselt BaseVec, (trunc X), Index0), (trunc (lshr X, BW/2)), Index1
1677 // Note: It is not safe to do this transform with an arbitrary base vector
1678 // because the bitcast of that vector to fewer/larger elements could
1679 // allow poison to spill into an element that was not poison before.
1680 // TODO: Detect smaller fractions of the scalar.
1681 // TODO: One-use checks are conservative.
1682 auto *VTy = dyn_cast<FixedVectorType>(InsElt.getType());
1683 Value *Scalar0, *BaseVec;
1684 uint64_t Index0, Index1;
1685 if (!VTy || (VTy->getNumElements() & 1) ||
1686 !match(IndexOp, m_ConstantInt(Index1)) ||
1687 !match(VecOp, m_InsertElt(m_Value(BaseVec), m_Value(Scalar0),
1688 m_ConstantInt(Index0))) ||
1689 !match(BaseVec, m_Undef()))
1690 return nullptr;
1691
1692 // The first insert must be to the index one less than this one, and
1693 // the first insert must be to an even index.
1694 if (Index0 + 1 != Index1 || Index0 & 1)
1695 return nullptr;
1696
1697 // For big endian, the high half of the value should be inserted first.
1698 // For little endian, the low half of the value should be inserted first.
1699 Value *X;
1700 uint64_t ShAmt;
1701 if (IsBigEndian) {
1702 if (!match(ScalarOp, m_Trunc(m_Value(X))) ||
1703 !match(Scalar0, m_Trunc(m_LShr(m_Specific(X), m_ConstantInt(ShAmt)))))
1704 return nullptr;
1705 } else {
1706 if (!match(Scalar0, m_Trunc(m_Value(X))) ||
1707 !match(ScalarOp, m_Trunc(m_LShr(m_Specific(X), m_ConstantInt(ShAmt)))))
1708 return nullptr;
1709 }
1710
1711 Type *SrcTy = X->getType();
1712 unsigned ScalarWidth = SrcTy->getScalarSizeInBits();
1713 unsigned VecEltWidth = VTy->getScalarSizeInBits();
1714 if (ScalarWidth != VecEltWidth * 2 || ShAmt != VecEltWidth)
1715 return nullptr;
1716
1717 // Bitcast the base vector to a vector type with the source element type.
1718 Type *CastTy = FixedVectorType::get(SrcTy, VTy->getNumElements() / 2);
1719 Value *CastBaseVec = Builder.CreateBitCast(BaseVec, CastTy);
1720
1721 // Scale the insert index for a vector with half as many elements.
1722 // bitcast (inselt (bitcast BaseVec), X, NewIndex)
1723 uint64_t NewIndex = IsBigEndian ? Index1 / 2 : Index0 / 2;
1724 Value *NewInsert = Builder.CreateInsertElement(CastBaseVec, X, NewIndex);
1725 return new BitCastInst(NewInsert, VTy);
1726}
1727
1729 Value *VecOp = IE.getOperand(0);
1730 Value *ScalarOp = IE.getOperand(1);
1731 Value *IdxOp = IE.getOperand(2);
1732
1733 if (auto *V = simplifyInsertElementInst(
1734 VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE)))
1735 return replaceInstUsesWith(IE, V);
1736
1737 // Canonicalize type of constant indices to i64 to simplify CSE
1738 if (auto *IndexC = dyn_cast<ConstantInt>(IdxOp)) {
1739 if (auto *NewIdx = getPreferredVectorIndex(IndexC))
1740 return replaceOperand(IE, 2, NewIdx);
1741
1742 Value *BaseVec, *OtherScalar;
1743 uint64_t OtherIndexVal;
1744 if (match(VecOp, m_OneUse(m_InsertElt(m_Value(BaseVec),
1745 m_Value(OtherScalar),
1746 m_ConstantInt(OtherIndexVal)))) &&
1747 !isa<Constant>(OtherScalar) && OtherIndexVal > IndexC->getZExtValue()) {
1748 Value *NewIns = Builder.CreateInsertElement(BaseVec, ScalarOp, IdxOp);
1749 return InsertElementInst::Create(NewIns, OtherScalar,
1750 Builder.getInt64(OtherIndexVal));
1751 }
1752 }
1753
1754 // If the scalar is bitcast and inserted into undef, do the insert in the
1755 // source type followed by bitcast.
1756 // TODO: Generalize for insert into any constant, not just undef?
1757 Value *ScalarSrc;
1758 if (match(VecOp, m_Undef()) &&
1759 match(ScalarOp, m_OneUse(m_BitCast(m_Value(ScalarSrc)))) &&
1760 (ScalarSrc->getType()->isIntegerTy() ||
1761 ScalarSrc->getType()->isFloatingPointTy())) {
1762 // inselt undef, (bitcast ScalarSrc), IdxOp -->
1763 // bitcast (inselt undef, ScalarSrc, IdxOp)
1764 Type *ScalarTy = ScalarSrc->getType();
1765 Type *VecTy = VectorType::get(ScalarTy, IE.getType()->getElementCount());
1766 Constant *NewUndef = isa<PoisonValue>(VecOp) ? PoisonValue::get(VecTy)
1767 : UndefValue::get(VecTy);
1768 Value *NewInsElt = Builder.CreateInsertElement(NewUndef, ScalarSrc, IdxOp);
1769 return new BitCastInst(NewInsElt, IE.getType());
1770 }
1771
1772 // If the vector and scalar are both bitcast from the same element type, do
1773 // the insert in that source type followed by bitcast.
1774 Value *VecSrc;
1775 if (match(VecOp, m_BitCast(m_Value(VecSrc))) &&
1776 match(ScalarOp, m_BitCast(m_Value(ScalarSrc))) &&
1777 (VecOp->hasOneUse() || ScalarOp->hasOneUse()) &&
1778 VecSrc->getType()->isVectorTy() && !ScalarSrc->getType()->isVectorTy() &&
1779 cast<VectorType>(VecSrc->getType())->getElementType() ==
1780 ScalarSrc->getType()) {
1781 // inselt (bitcast VecSrc), (bitcast ScalarSrc), IdxOp -->
1782 // bitcast (inselt VecSrc, ScalarSrc, IdxOp)
1783 Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp);
1784 return new BitCastInst(NewInsElt, IE.getType());
1785 }
1786
1787 // If the inserted element was extracted from some other fixed-length vector
1788 // and both indexes are valid constants, try to turn this into a shuffle.
1789 // Can not handle scalable vector type, the number of elements needed to
1790 // create shuffle mask is not a compile-time constant.
1791 uint64_t InsertedIdx, ExtractedIdx;
1792 Value *ExtVecOp;
1793 if (isa<FixedVectorType>(IE.getType()) &&
1794 match(IdxOp, m_ConstantInt(InsertedIdx)) &&
1795 match(ScalarOp,
1796 m_ExtractElt(m_Value(ExtVecOp), m_ConstantInt(ExtractedIdx))) &&
1797 isa<FixedVectorType>(ExtVecOp->getType()) &&
1798 ExtractedIdx <
1799 cast<FixedVectorType>(ExtVecOp->getType())->getNumElements()) {
1800 // TODO: Looking at the user(s) to determine if this insert is a
1801 // fold-to-shuffle opportunity does not match the usual instcombine
1802 // constraints. We should decide if the transform is worthy based only
1803 // on this instruction and its operands, but that may not work currently.
1804 //
1805 // Here, we are trying to avoid creating shuffles before reaching
1806 // the end of a chain of extract-insert pairs. This is complicated because
1807 // we do not generally form arbitrary shuffle masks in instcombine
1808 // (because those may codegen poorly), but collectShuffleElements() does
1809 // exactly that.
1810 //
1811 // The rules for determining what is an acceptable target-independent
1812 // shuffle mask are fuzzy because they evolve based on the backend's
1813 // capabilities and real-world impact.
1814 auto isShuffleRootCandidate = [](InsertElementInst &Insert) {
1815 if (!Insert.hasOneUse())
1816 return true;
1817 auto *InsertUser = dyn_cast<InsertElementInst>(Insert.user_back());
1818 if (!InsertUser)
1819 return true;
1820 return false;
1821 };
1822
1823 // Try to form a shuffle from a chain of extract-insert ops.
1824 if (isShuffleRootCandidate(IE)) {
1825 bool Rerun = true;
1826 while (Rerun) {
1827 Rerun = false;
1828
1830 ShuffleOps LR =
1831 collectShuffleElements(&IE, Mask, nullptr, *this, Rerun);
1832
1833 // The proposed shuffle may be trivial, in which case we shouldn't
1834 // perform the combine.
1835 if (LR.first != &IE && LR.second != &IE) {
1836 // We now have a shuffle of LHS, RHS, Mask.
1837 if (LR.second == nullptr)
1838 LR.second = PoisonValue::get(LR.first->getType());
1839 return new ShuffleVectorInst(LR.first, LR.second, Mask);
1840 }
1841 }
1842 }
1843 }
1844
1845 if (auto VecTy = dyn_cast<FixedVectorType>(VecOp->getType())) {
1846 unsigned VWidth = VecTy->getNumElements();
1847 APInt PoisonElts(VWidth, 0);
1848 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
1849 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask,
1850 PoisonElts)) {
1851 if (V != &IE)
1852 return replaceInstUsesWith(IE, V);
1853 return &IE;
1854 }
1855 }
1856
1858 return Shuf;
1859
1860 if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder))
1861 return NewInsElt;
1862
1863 if (Instruction *Broadcast = foldInsSequenceIntoSplat(IE))
1864 return Broadcast;
1865
1867 return Splat;
1868
1869 if (Instruction *IdentityShuf = foldInsEltIntoIdentityShuffle(IE))
1870 return IdentityShuf;
1871
1872 if (Instruction *Ext = narrowInsElt(IE, Builder))
1873 return Ext;
1874
1875 if (Instruction *Ext = foldTruncInsEltPair(IE, DL.isBigEndian(), Builder))
1876 return Ext;
1877
1878 return nullptr;
1879}
1880
1881/// Return true if we can evaluate the specified expression tree if the vector
1882/// elements were shuffled in a different order.
1884 unsigned Depth = 5) {
1885 // We can always reorder the elements of a constant.
1886 if (isa<Constant>(V))
1887 return true;
1888
1889 // We won't reorder vector arguments. No IPO here.
1891 if (!I) return false;
1892
1893 // Two users may expect different orders of the elements. Don't try it.
1894 if (!I->hasOneUse())
1895 return false;
1896
1897 if (Depth == 0) return false;
1898
1899 switch (I->getOpcode()) {
1900 case Instruction::UDiv:
1901 case Instruction::SDiv:
1902 case Instruction::URem:
1903 case Instruction::SRem:
1904 // Propagating an undefined shuffle mask element to integer div/rem is not
1905 // allowed because those opcodes can create immediate undefined behavior
1906 // from an undefined element in an operand.
1907 if (llvm::is_contained(Mask, -1))
1908 return false;
1909 [[fallthrough]];
1910 case Instruction::Add:
1911 case Instruction::FAdd:
1912 case Instruction::Sub:
1913 case Instruction::FSub:
1914 case Instruction::Mul:
1915 case Instruction::FMul:
1916 case Instruction::FDiv:
1917 case Instruction::FRem:
1918 case Instruction::Shl:
1919 case Instruction::LShr:
1920 case Instruction::AShr:
1921 case Instruction::And:
1922 case Instruction::Or:
1923 case Instruction::Xor:
1924 case Instruction::ICmp:
1925 case Instruction::FCmp:
1926 case Instruction::Trunc:
1927 case Instruction::ZExt:
1928 case Instruction::SExt:
1929 case Instruction::FPToUI:
1930 case Instruction::FPToSI:
1931 case Instruction::UIToFP:
1932 case Instruction::SIToFP:
1933 case Instruction::FPTrunc:
1934 case Instruction::FPExt:
1935 case Instruction::GetElementPtr: {
1936 // Bail out if we would create longer vector ops. We could allow creating
1937 // longer vector ops, but that may result in more expensive codegen.
1938 Type *ITy = I->getType();
1939 if (ITy->isVectorTy() &&
1940 Mask.size() > cast<FixedVectorType>(ITy)->getNumElements())
1941 return false;
1942 for (Value *Operand : I->operands()) {
1943 if (!canEvaluateShuffled(Operand, Mask, Depth - 1))
1944 return false;
1945 }
1946 return true;
1947 }
1948 case Instruction::InsertElement: {
1949 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
1950 if (!CI) return false;
1951 int ElementNumber = CI->getLimitedValue();
1952
1953 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
1954 // can't put an element into multiple indices.
1955 bool SeenOnce = false;
1956 for (int I : Mask) {
1957 if (I == ElementNumber) {
1958 if (SeenOnce)
1959 return false;
1960 SeenOnce = true;
1961 }
1962 }
1963 return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1);
1964 }
1965 }
1966 return false;
1967}
1968
1969/// Rebuild a new instruction just like 'I' but with the new operands given.
1970/// In the event of type mismatch, the type of the operands is correct.
1972 IRBuilderBase &Builder) {
1973 Builder.SetInsertPoint(I);
1974 switch (I->getOpcode()) {
1975 case Instruction::Add:
1976 case Instruction::FAdd:
1977 case Instruction::Sub:
1978 case Instruction::FSub:
1979 case Instruction::Mul:
1980 case Instruction::FMul:
1981 case Instruction::UDiv:
1982 case Instruction::SDiv:
1983 case Instruction::FDiv:
1984 case Instruction::URem:
1985 case Instruction::SRem:
1986 case Instruction::FRem:
1987 case Instruction::Shl:
1988 case Instruction::LShr:
1989 case Instruction::AShr:
1990 case Instruction::And:
1991 case Instruction::Or:
1992 case Instruction::Xor: {
1994 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
1995 Value *New = Builder.CreateBinOp(cast<BinaryOperator>(I)->getOpcode(),
1996 NewOps[0], NewOps[1]);
1997 if (auto *NewI = dyn_cast<Instruction>(New)) {
1999 NewI->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
2000 NewI->setHasNoSignedWrap(BO->hasNoSignedWrap());
2001 }
2003 NewI->setIsExact(BO->isExact());
2004 }
2005 if (isa<FPMathOperator>(BO))
2006 NewI->copyFastMathFlags(I);
2007 }
2008 return New;
2009 }
2010 case Instruction::ICmp: {
2011 assert(NewOps.size() == 2 && "icmp with #ops != 2");
2012 Value *New = Builder.CreateICmp(cast<ICmpInst>(I)->getPredicate(),
2013 NewOps[0], NewOps[1]);
2014 if (auto *NewI = dyn_cast<Instruction>(New))
2015 NewI->copyIRFlags(I);
2016 return New;
2017 }
2018 case Instruction::FCmp:
2019 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
2020 return Builder.CreateFCmpFMF(cast<FCmpInst>(I)->getPredicate(), NewOps[0],
2021 NewOps[1], I);
2022 case Instruction::Trunc:
2023 case Instruction::ZExt:
2024 case Instruction::SExt:
2025 case Instruction::FPToUI:
2026 case Instruction::FPToSI:
2027 case Instruction::UIToFP:
2028 case Instruction::SIToFP:
2029 case Instruction::FPTrunc:
2030 case Instruction::FPExt: {
2031 // It's possible that the mask has a different number of elements from
2032 // the original cast. We recompute the destination type to match the mask.
2033 Type *DestTy = VectorType::get(
2034 I->getType()->getScalarType(),
2035 cast<VectorType>(NewOps[0]->getType())->getElementCount());
2036 assert(NewOps.size() == 1 && "cast with #ops != 1");
2037 Value *New =
2038 Builder.CreateCast(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy);
2039 if (auto *NewI = dyn_cast<Instruction>(New))
2040 NewI->copyIRFlags(I);
2041 return New;
2042 }
2043 case Instruction::GetElementPtr: {
2044 Value *Ptr = NewOps[0];
2045 ArrayRef<Value*> Idx = NewOps.slice(1);
2046 return Builder.CreateGEP(cast<GEPOperator>(I)->getSourceElementType(),
2047 Ptr, Idx, "",
2048 cast<GEPOperator>(I)->getNoWrapFlags());
2049 }
2050 }
2051 llvm_unreachable("failed to rebuild vector instructions");
2052}
2053
2055 IRBuilderBase &Builder) {
2056 // Mask.size() does not need to be equal to the number of vector elements.
2057
2058 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
2059 Type *EltTy = V->getType()->getScalarType();
2060
2061 if (isa<PoisonValue>(V))
2062 return PoisonValue::get(FixedVectorType::get(EltTy, Mask.size()));
2063
2064 if (match(V, m_Undef()))
2065 return UndefValue::get(FixedVectorType::get(EltTy, Mask.size()));
2066
2068 return ConstantAggregateZero::get(FixedVectorType::get(EltTy, Mask.size()));
2069
2070 if (Constant *C = dyn_cast<Constant>(V))
2072 Mask);
2073
2075 switch (I->getOpcode()) {
2076 case Instruction::Add:
2077 case Instruction::FAdd:
2078 case Instruction::Sub:
2079 case Instruction::FSub:
2080 case Instruction::Mul:
2081 case Instruction::FMul:
2082 case Instruction::UDiv:
2083 case Instruction::SDiv:
2084 case Instruction::FDiv:
2085 case Instruction::URem:
2086 case Instruction::SRem:
2087 case Instruction::FRem:
2088 case Instruction::Shl:
2089 case Instruction::LShr:
2090 case Instruction::AShr:
2091 case Instruction::And:
2092 case Instruction::Or:
2093 case Instruction::Xor:
2094 case Instruction::ICmp:
2095 case Instruction::FCmp:
2096 case Instruction::Trunc:
2097 case Instruction::ZExt:
2098 case Instruction::SExt:
2099 case Instruction::FPToUI:
2100 case Instruction::FPToSI:
2101 case Instruction::UIToFP:
2102 case Instruction::SIToFP:
2103 case Instruction::FPTrunc:
2104 case Instruction::FPExt:
2105 case Instruction::Select:
2106 case Instruction::GetElementPtr: {
2108 bool NeedsRebuild =
2109 (Mask.size() !=
2110 cast<FixedVectorType>(I->getType())->getNumElements());
2111 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
2112 Value *V;
2113 // Recursively call evaluateInDifferentElementOrder on vector arguments
2114 // as well. E.g. GetElementPtr may have scalar operands even if the
2115 // return value is a vector, so we need to examine the operand type.
2116 if (I->getOperand(i)->getType()->isVectorTy())
2117 V = evaluateInDifferentElementOrder(I->getOperand(i), Mask, Builder);
2118 else
2119 V = I->getOperand(i);
2120 NewOps.push_back(V);
2121 NeedsRebuild |= (V != I->getOperand(i));
2122 }
2123 if (NeedsRebuild)
2124 return buildNew(I, NewOps, Builder);
2125 return I;
2126 }
2127 case Instruction::InsertElement: {
2128 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
2129
2130 // The insertelement was inserting at Element. Figure out which element
2131 // that becomes after shuffling. The answer is guaranteed to be unique
2132 // by CanEvaluateShuffled.
2133 bool Found = false;
2134 int Index = 0;
2135 for (int e = Mask.size(); Index != e; ++Index) {
2136 if (Mask[Index] == Element) {
2137 Found = true;
2138 break;
2139 }
2140 }
2141
2142 // If element is not in Mask, no need to handle the operand 1 (element to
2143 // be inserted). Just evaluate values in operand 0 according to Mask.
2144 if (!Found)
2145 return evaluateInDifferentElementOrder(I->getOperand(0), Mask, Builder);
2146
2147 Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask,
2148 Builder);
2149 Builder.SetInsertPoint(I);
2150 return Builder.CreateInsertElement(V, I->getOperand(1), Index);
2151 }
2152 }
2153 llvm_unreachable("failed to reorder elements of vector instruction!");
2154}
2155
2156// Returns true if the shuffle is extracting a contiguous range of values from
2157// LHS, for example:
2158// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
2159// Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
2160// Shuffles to: |EE|FF|GG|HH|
2161// +--+--+--+--+
2163 ArrayRef<int> Mask) {
2164 unsigned LHSElems =
2165 cast<FixedVectorType>(SVI.getOperand(0)->getType())->getNumElements();
2166 unsigned MaskElems = Mask.size();
2167 unsigned BegIdx = Mask.front();
2168 unsigned EndIdx = Mask.back();
2169 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
2170 return false;
2171 for (unsigned I = 0; I != MaskElems; ++I)
2172 if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
2173 return false;
2174 return true;
2175}
2176
2177/// These are the ingredients in an alternate form binary operator as described
2178/// below.
2184 Value *V0 = nullptr, Value *V1 = nullptr) :
2185 Opcode(Opc), Op0(V0), Op1(V1) {}
2186 operator bool() const { return Opcode != 0; }
2187};
2188
2189/// Binops may be transformed into binops with different opcodes and operands.
2190/// Reverse the usual canonicalization to enable folds with the non-canonical
2191/// form of the binop. If a transform is possible, return the elements of the
2192/// new binop. If not, return invalid elements.
2194 Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1);
2195 Type *Ty = BO->getType();
2196 switch (BO->getOpcode()) {
2197 case Instruction::Shl: {
2198 // shl X, C --> mul X, (1 << C)
2199 Constant *C;
2200 if (match(BO1, m_ImmConstant(C))) {
2202 Instruction::Shl, ConstantInt::get(Ty, 1), C, DL);
2203 assert(ShlOne && "Constant folding of immediate constants failed");
2204 return {Instruction::Mul, BO0, ShlOne};
2205 }
2206 break;
2207 }
2208 case Instruction::Or: {
2209 // or disjoin X, C --> add X, C
2210 if (cast<PossiblyDisjointInst>(BO)->isDisjoint())
2211 return {Instruction::Add, BO0, BO1};
2212 break;
2213 }
2214 case Instruction::Sub:
2215 // sub 0, X --> mul X, -1
2216 if (match(BO0, m_ZeroInt()))
2217 return {Instruction::Mul, BO1, ConstantInt::getAllOnesValue(Ty)};
2218 break;
2219 default:
2220 break;
2221 }
2222 return {};
2223}
2224
2225/// A select shuffle of a select shuffle with a shared operand can be reduced
2226/// to a single select shuffle. This is an obvious improvement in IR, and the
2227/// backend is expected to lower select shuffles efficiently.
2229 assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
2230
2231 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2233 Shuf.getShuffleMask(Mask);
2234 unsigned NumElts = Mask.size();
2235
2236 // Canonicalize a select shuffle with common operand as Op1.
2237 auto *ShufOp = dyn_cast<ShuffleVectorInst>(Op0);
2238 if (ShufOp && ShufOp->isSelect() &&
2239 (ShufOp->getOperand(0) == Op1 || ShufOp->getOperand(1) == Op1)) {
2240 std::swap(Op0, Op1);
2242 }
2243
2244 ShufOp = dyn_cast<ShuffleVectorInst>(Op1);
2245 if (!ShufOp || !ShufOp->isSelect() ||
2246 (ShufOp->getOperand(0) != Op0 && ShufOp->getOperand(1) != Op0))
2247 return nullptr;
2248
2249 Value *X = ShufOp->getOperand(0), *Y = ShufOp->getOperand(1);
2251 ShufOp->getShuffleMask(Mask1);
2252 assert(Mask1.size() == NumElts && "Vector size changed with select shuffle");
2253
2254 // Canonicalize common operand (Op0) as X (first operand of first shuffle).
2255 if (Y == Op0) {
2256 std::swap(X, Y);
2258 }
2259
2260 // If the mask chooses from X (operand 0), it stays the same.
2261 // If the mask chooses from the earlier shuffle, the other mask value is
2262 // transferred to the combined select shuffle:
2263 // shuf X, (shuf X, Y, M1), M --> shuf X, Y, M'
2264 SmallVector<int, 16> NewMask(NumElts);
2265 for (unsigned i = 0; i != NumElts; ++i)
2266 NewMask[i] = Mask[i] < (signed)NumElts ? Mask[i] : Mask1[i];
2267
2268 // A select mask with undef elements might look like an identity mask.
2269 assert((ShuffleVectorInst::isSelectMask(NewMask, NumElts) ||
2270 ShuffleVectorInst::isIdentityMask(NewMask, NumElts)) &&
2271 "Unexpected shuffle mask");
2272 return new ShuffleVectorInst(X, Y, NewMask);
2273}
2274
2276 const SimplifyQuery &SQ) {
2277 assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
2278
2279 // Are we shuffling together some value and that same value after it has been
2280 // modified by a binop with a constant?
2281 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2282 Constant *C;
2283 bool Op0IsBinop;
2284 if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C))))
2285 Op0IsBinop = true;
2286 else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C))))
2287 Op0IsBinop = false;
2288 else
2289 return nullptr;
2290
2291 // The identity constant for a binop leaves a variable operand unchanged. For
2292 // a vector, this is a splat of something like 0, -1, or 1.
2293 // If there's no identity constant for this binop, we're done.
2294 auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1);
2295 BinaryOperator::BinaryOps BOpcode = BO->getOpcode();
2296 Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true);
2297 if (!IdC)
2298 return nullptr;
2299
2300 Value *X = Op0IsBinop ? Op1 : Op0;
2301
2302 // Prevent folding in the case the non-binop operand might have NaN values.
2303 // If X can have NaN elements then we have that the floating point math
2304 // operation in the transformed code may not preserve the exact NaN
2305 // bit-pattern -- e.g. `fadd sNaN, 0.0 -> qNaN`.
2306 // This makes the transformation incorrect since the original program would
2307 // have preserved the exact NaN bit-pattern.
2308 // Avoid the folding if X can have NaN elements.
2309 bool IsFloatingPointTy =
2311 if (IsFloatingPointTy && !isKnownNeverNaN(X, SQ))
2312 return nullptr;
2313
2314 // Shuffle identity constants into the lanes that return the original value.
2315 // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4}
2316 // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4}
2317 // The existing binop constant vector remains in the same operand position.
2318 ArrayRef<int> Mask = Shuf.getShuffleMask();
2319 Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) :
2321
2322 bool MightCreatePoisonOrUB =
2324 (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode));
2325 if (MightCreatePoisonOrUB)
2326 NewC = InstCombiner::getSafeVectorConstantForBinop(BOpcode, NewC, true);
2327
2328 // shuf (bop X, C), X, M --> bop X, C'
2329 // shuf X, (bop X, C), M --> bop X, C'
2330 BinaryOperator *NewBO = BinaryOperator::Create(BOpcode, X, NewC);
2331 NewBO->copyIRFlags(BO);
2332
2333 // Drop noinf FMF if X can be Inf. If X can have Inf elements and noinf FMF is
2334 // set, the transformation may generate poison where the original program
2335 // would preserve the Inf value.
2336 if (IsFloatingPointTy && NewBO->hasNoInfs() && !isKnownNeverInfinity(X, SQ))
2337 NewBO->setHasNoInfs(false);
2338
2339 // An undef shuffle mask element may propagate as an undef constant element in
2340 // the new binop. That would produce poison where the original code might not.
2341 // If we already made a safe constant, then there's no danger.
2342 if (is_contained(Mask, PoisonMaskElem) && !MightCreatePoisonOrUB)
2344 return NewBO;
2345}
2346
2347/// If we have an insert of a scalar to a non-zero element of an undefined
2348/// vector and then shuffle that value, that's the same as inserting to the zero
2349/// element and shuffling. Splatting from the zero element is recognized as the
2350/// canonical form of splat.
2352 InstCombiner::BuilderTy &Builder) {
2353 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2354 ArrayRef<int> Mask = Shuf.getShuffleMask();
2355 Value *X;
2356 uint64_t IndexC;
2357
2358 // Match a shuffle that is a splat to a non-zero element.
2360 m_ConstantInt(IndexC)))) ||
2361 !match(Op1, m_Poison()) || match(Mask, m_ZeroMask()) || IndexC == 0)
2362 return nullptr;
2363
2364 // Insert into element 0 of a poison vector.
2365 PoisonValue *PoisonVec = PoisonValue::get(Shuf.getType());
2366 Value *NewIns = Builder.CreateInsertElement(PoisonVec, X, (uint64_t)0);
2367
2368 // Splat from element 0. Any mask element that is poison remains poison.
2369 // For example:
2370 // shuf (inselt poison, X, 2), _, <2,2,undef>
2371 // --> shuf (inselt poison, X, 0), poison, <0,0,undef>
2372 unsigned NumMaskElts =
2373 cast<FixedVectorType>(Shuf.getType())->getNumElements();
2374 SmallVector<int, 16> NewMask(NumMaskElts, 0);
2375 for (unsigned i = 0; i != NumMaskElts; ++i)
2376 if (Mask[i] == PoisonMaskElem)
2377 NewMask[i] = Mask[i];
2378
2379 return new ShuffleVectorInst(NewIns, NewMask);
2380}
2381
2382/// Try to fold shuffles that are the equivalent of a vector select.
2384 if (!Shuf.isSelect())
2385 return nullptr;
2386
2387 // Canonicalize to choose from operand 0 first unless operand 1 is undefined.
2388 // Commuting undef to operand 0 conflicts with another canonicalization.
2389 unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
2390 if (!match(Shuf.getOperand(1), m_Undef()) &&
2391 Shuf.getMaskValue(0) >= (int)NumElts) {
2392 // TODO: Can we assert that both operands of a shuffle-select are not undef
2393 // (otherwise, it would have been folded by instsimplify?
2394 Shuf.commute();
2395 return &Shuf;
2396 }
2397
2399 return I;
2400
2402 Shuf, getSimplifyQuery().getWithInstruction(&Shuf)))
2403 return I;
2404
2405 BinaryOperator *B0, *B1;
2406 if (!match(Shuf.getOperand(0), m_BinOp(B0)) ||
2407 !match(Shuf.getOperand(1), m_BinOp(B1)))
2408 return nullptr;
2409
2410 // If one operand is "0 - X", allow that to be viewed as "X * -1"
2411 // (ConstantsAreOp1) by getAlternateBinop below. If the neg is not paired
2412 // with a multiply, we will exit because C0/C1 will not be set.
2413 Value *X, *Y;
2414 Constant *C0 = nullptr, *C1 = nullptr;
2415 bool ConstantsAreOp1;
2416 if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) &&
2417 match(B1, m_BinOp(m_Constant(C1), m_Value(Y))))
2418 ConstantsAreOp1 = false;
2419 else if (match(B0, m_CombineOr(m_BinOp(m_Value(X), m_Constant(C0)),
2420 m_Neg(m_Value(X)))) &&
2422 m_Neg(m_Value(Y)))))
2423 ConstantsAreOp1 = true;
2424 else
2425 return nullptr;
2426
2427 // We need matching binops to fold the lanes together.
2430 bool DropNSW = false;
2431 if (ConstantsAreOp1 && Opc0 != Opc1) {
2432 // TODO: We drop "nsw" if shift is converted into multiply because it may
2433 // not be correct when the shift amount is BitWidth - 1. We could examine
2434 // each vector element to determine if it is safe to keep that flag.
2435 if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl)
2436 DropNSW = true;
2437 if (BinopElts AltB0 = getAlternateBinop(B0, DL)) {
2438 assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop");
2439 Opc0 = AltB0.Opcode;
2440 C0 = cast<Constant>(AltB0.Op1);
2441 } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) {
2442 assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop");
2443 Opc1 = AltB1.Opcode;
2444 C1 = cast<Constant>(AltB1.Op1);
2445 }
2446 }
2447
2448 if (Opc0 != Opc1 || !C0 || !C1)
2449 return nullptr;
2450
2451 // The opcodes must be the same. Use a new name to make that clear.
2452 BinaryOperator::BinaryOps BOpc = Opc0;
2453
2454 // Select the constant elements needed for the single binop.
2455 ArrayRef<int> Mask = Shuf.getShuffleMask();
2456 Constant *NewC = ConstantExpr::getShuffleVector(C0, C1, Mask);
2457
2458 // We are moving a binop after a shuffle. When a shuffle has an undefined
2459 // mask element, the result is undefined, but it is not poison or undefined
2460 // behavior. That is not necessarily true for div/rem/shift.
2461 bool MightCreatePoisonOrUB =
2464 if (MightCreatePoisonOrUB)
2466 ConstantsAreOp1);
2467
2468 Value *V;
2469 if (X == Y) {
2470 // Remove a binop and the shuffle by rearranging the constant:
2471 // shuffle (op V, C0), (op V, C1), M --> op V, C'
2472 // shuffle (op C0, V), (op C1, V), M --> op C', V
2473 V = X;
2474 } else {
2475 // If there are 2 different variable operands, we must create a new shuffle
2476 // (select) first, so check uses to ensure that we don't end up with more
2477 // instructions than we started with.
2478 if (!B0->hasOneUse() && !B1->hasOneUse())
2479 return nullptr;
2480
2481 // If we use the original shuffle mask and op1 is *variable*, we would be
2482 // putting an undef into operand 1 of div/rem/shift. This is either UB or
2483 // poison. We do not have to guard against UB when *constants* are op1
2484 // because safe constants guarantee that we do not overflow sdiv/srem (and
2485 // there's no danger for other opcodes).
2486 // TODO: To allow this case, create a new shuffle mask with no undefs.
2487 if (MightCreatePoisonOrUB && !ConstantsAreOp1)
2488 return nullptr;
2489
2490 // Note: In general, we do not create new shuffles in InstCombine because we
2491 // do not know if a target can lower an arbitrary shuffle optimally. In this
2492 // case, the shuffle uses the existing mask, so there is no additional risk.
2493
2494 // Select the variable vectors first, then perform the binop:
2495 // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C'
2496 // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M)
2497 V = Builder.CreateShuffleVector(X, Y, Mask);
2498 }
2499
2500 Value *NewBO = ConstantsAreOp1 ? Builder.CreateBinOp(BOpc, V, NewC) :
2501 Builder.CreateBinOp(BOpc, NewC, V);
2502
2503 // Flags are intersected from the 2 source binops. But there are 2 exceptions:
2504 // 1. If we changed an opcode, poison conditions might have changed.
2505 // 2. If the shuffle had undef mask elements, the new binop might have undefs
2506 // where the original code did not. But if we already made a safe constant,
2507 // then there's no danger.
2508 if (auto *NewI = dyn_cast<Instruction>(NewBO)) {
2509 NewI->copyIRFlags(B0);
2510 NewI->andIRFlags(B1);
2511 if (DropNSW)
2512 NewI->setHasNoSignedWrap(false);
2513 if (is_contained(Mask, PoisonMaskElem) && !MightCreatePoisonOrUB)
2514 NewI->dropPoisonGeneratingFlags();
2515 }
2516 return replaceInstUsesWith(Shuf, NewBO);
2517}
2518
2519/// Convert a narrowing shuffle of a bitcasted vector into a vector truncate.
2520/// Example (little endian):
2521/// shuf (bitcast <4 x i16> X to <8 x i8>), <0, 2, 4, 6> --> trunc X to <4 x i8>
2523 bool IsBigEndian) {
2524 // This must be a bitcasted shuffle of 1 vector integer operand.
2525 Type *DestType = Shuf.getType();
2526 Value *X;
2527 if (!match(Shuf.getOperand(0), m_BitCast(m_Value(X))) ||
2528 !match(Shuf.getOperand(1), m_Poison()) || !DestType->isIntOrIntVectorTy())
2529 return nullptr;
2530
2531 // The source type must have the same number of elements as the shuffle,
2532 // and the source element type must be larger than the shuffle element type.
2533 Type *SrcType = X->getType();
2534 if (!SrcType->isVectorTy() || !SrcType->isIntOrIntVectorTy() ||
2535 cast<FixedVectorType>(SrcType)->getNumElements() !=
2536 cast<FixedVectorType>(DestType)->getNumElements() ||
2537 SrcType->getScalarSizeInBits() % DestType->getScalarSizeInBits() != 0)
2538 return nullptr;
2539
2540 assert(Shuf.changesLength() && !Shuf.increasesLength() &&
2541 "Expected a shuffle that decreases length");
2542
2543 // Last, check that the mask chooses the correct low bits for each narrow
2544 // element in the result.
2545 uint64_t TruncRatio =
2546 SrcType->getScalarSizeInBits() / DestType->getScalarSizeInBits();
2547 ArrayRef<int> Mask = Shuf.getShuffleMask();
2548 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
2549 if (Mask[i] == PoisonMaskElem)
2550 continue;
2551 uint64_t LSBIndex = IsBigEndian ? (i + 1) * TruncRatio - 1 : i * TruncRatio;
2552 assert(LSBIndex <= INT32_MAX && "Overflowed 32-bits");
2553 if (Mask[i] != (int)LSBIndex)
2554 return nullptr;
2555 }
2556
2557 return new TruncInst(X, DestType);
2558}
2559
2560/// Match a shuffle-select-shuffle pattern where the shuffles are widening and
2561/// narrowing (concatenating with poison and extracting back to the original
2562/// length). This allows replacing the wide select with a narrow select.
2564 InstCombiner::BuilderTy &Builder) {
2565 // This must be a narrowing identity shuffle. It extracts the 1st N elements
2566 // of the 1st vector operand of a shuffle.
2567 if (!match(Shuf.getOperand(1), m_Poison()) || !Shuf.isIdentityWithExtract())
2568 return nullptr;
2569
2570 // The vector being shuffled must be a vector select that we can eliminate.
2571 // TODO: The one-use requirement could be eased if X and/or Y are constants.
2572 Value *Cond, *X, *Y;
2573 if (!match(Shuf.getOperand(0),
2575 return nullptr;
2576
2577 // We need a narrow condition value. It must be extended with poison elements
2578 // and have the same number of elements as this shuffle.
2579 unsigned NarrowNumElts =
2580 cast<FixedVectorType>(Shuf.getType())->getNumElements();
2581 Value *NarrowCond;
2582 if (!match(Cond, m_OneUse(m_Shuffle(m_Value(NarrowCond), m_Poison()))) ||
2583 cast<FixedVectorType>(NarrowCond->getType())->getNumElements() !=
2584 NarrowNumElts ||
2585 !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding())
2586 return nullptr;
2587
2588 // shuf (sel (shuf NarrowCond, poison, WideMask), X, Y), poison, NarrowMask)
2589 // -->
2590 // sel NarrowCond, (shuf X, poison, NarrowMask), (shuf Y, poison, NarrowMask)
2591 Value *NarrowX = Builder.CreateShuffleVector(X, Shuf.getShuffleMask());
2592 Value *NarrowY = Builder.CreateShuffleVector(Y, Shuf.getShuffleMask());
2593 return SelectInst::Create(NarrowCond, NarrowX, NarrowY);
2594}
2595
2596/// Canonicalize FP negate/abs after shuffle.
2598 InstCombiner::BuilderTy &Builder) {
2599 auto *S0 = dyn_cast<Instruction>(Shuf.getOperand(0));
2600 Value *X;
2601 if (!S0 || !match(S0, m_CombineOr(m_FNeg(m_Value(X)), m_FAbs(m_Value(X)))))
2602 return nullptr;
2603
2604 bool IsFNeg = S0->getOpcode() == Instruction::FNeg;
2605
2606 // Match 2-input (binary) shuffle.
2607 auto *S1 = dyn_cast<Instruction>(Shuf.getOperand(1));
2608 Value *Y;
2609 if (!S1 || !match(S1, m_CombineOr(m_FNeg(m_Value(Y)), m_FAbs(m_Value(Y)))) ||
2610 S0->getOpcode() != S1->getOpcode() ||
2611 (!S0->hasOneUse() && !S1->hasOneUse()))
2612 return nullptr;
2613
2614 // shuf (fneg/fabs X), (fneg/fabs Y), Mask --> fneg/fabs (shuf X, Y, Mask)
2615 Value *NewShuf = Builder.CreateShuffleVector(X, Y, Shuf.getShuffleMask());
2616 Instruction *NewF;
2617 if (IsFNeg) {
2618 NewF = UnaryOperator::CreateFNeg(NewShuf);
2619 } else {
2621 Shuf.getModule(), Intrinsic::fabs, Shuf.getType());
2622 NewF = CallInst::Create(FAbs, {NewShuf});
2623 }
2624 NewF->copyIRFlags(S0);
2625 NewF->andIRFlags(S1);
2626 return NewF;
2627}
2628
2629/// Canonicalize casts after shuffle.
2631 InstCombiner::BuilderTy &Builder) {
2632 auto *Cast0 = dyn_cast<CastInst>(Shuf.getOperand(0));
2633 if (!Cast0)
2634 return nullptr;
2635
2636 // TODO: Allow other opcodes? That would require easing the type restrictions
2637 // below here.
2638 CastInst::CastOps CastOpcode = Cast0->getOpcode();
2639 switch (CastOpcode) {
2640 case Instruction::SExt:
2641 case Instruction::ZExt:
2642 case Instruction::FPToSI:
2643 case Instruction::FPToUI:
2644 case Instruction::SIToFP:
2645 case Instruction::UIToFP:
2646 break;
2647 default:
2648 return nullptr;
2649 }
2650
2651 VectorType *CastSrcTy = cast<VectorType>(Cast0->getSrcTy());
2652 VectorType *ShufTy = Shuf.getType();
2653 VectorType *ShufOpTy = cast<VectorType>(Shuf.getOperand(0)->getType());
2654
2655 // TODO: Allow length-increasing shuffles?
2656 if (ShufTy->getElementCount().getKnownMinValue() >
2657 ShufOpTy->getElementCount().getKnownMinValue())
2658 return nullptr;
2659
2660 // shuffle (cast X), Poison, identity-with-extract-mask -->
2661 // cast (shuffle X, Poison, identity-with-extract-mask).
2662 if (isa<PoisonValue>(Shuf.getOperand(1)) && Cast0->hasOneUse() &&
2663 Shuf.isIdentityWithExtract()) {
2664 auto *NewIns = Builder.CreateShuffleVector(Cast0->getOperand(0),
2665 PoisonValue::get(CastSrcTy),
2666 Shuf.getShuffleMask());
2667 return CastInst::Create(Cast0->getOpcode(), NewIns, Shuf.getType());
2668 }
2669
2670 auto *Cast1 = dyn_cast<CastInst>(Shuf.getOperand(1));
2671 // Do we have 2 matching cast operands?
2672 if (!Cast1 || Cast0->getOpcode() != Cast1->getOpcode() ||
2673 Cast0->getSrcTy() != Cast1->getSrcTy())
2674 return nullptr;
2675
2676 // TODO: Allow element-size-decreasing casts (ex: fptosi float to i8)?
2677 assert(isa<FixedVectorType>(CastSrcTy) && isa<FixedVectorType>(ShufOpTy) &&
2678 "Expected fixed vector operands for casts and binary shuffle");
2679 if (CastSrcTy->getPrimitiveSizeInBits() > ShufOpTy->getPrimitiveSizeInBits())
2680 return nullptr;
2681
2682 // At least one of the operands must have only one use (the shuffle).
2683 if (!Cast0->hasOneUse() && !Cast1->hasOneUse())
2684 return nullptr;
2685
2686 // shuffle (cast X), (cast Y), Mask --> cast (shuffle X, Y, Mask)
2687 Value *X = Cast0->getOperand(0);
2688 Value *Y = Cast1->getOperand(0);
2689 Value *NewShuf = Builder.CreateShuffleVector(X, Y, Shuf.getShuffleMask());
2690 return CastInst::Create(CastOpcode, NewShuf, ShufTy);
2691}
2692
2693/// Try to fold an extract subvector operation.
2695 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2696 if (!Shuf.isIdentityWithExtract() || !match(Op1, m_Poison()))
2697 return nullptr;
2698
2699 // Check if we are extracting all bits of an inserted scalar:
2700 // extract-subvec (bitcast (inselt ?, X, 0) --> bitcast X to subvec type
2701 Value *X;
2702 if (match(Op0, m_BitCast(m_InsertElt(m_Value(), m_Value(X), m_Zero()))) &&
2703 X->getType()->getPrimitiveSizeInBits() ==
2705 return new BitCastInst(X, Shuf.getType());
2706
2707 // Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask.
2708 Value *Y;
2709 ArrayRef<int> Mask;
2710 if (!match(Op0, m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask))))
2711 return nullptr;
2712
2713 // Be conservative with shuffle transforms. If we can't kill the 1st shuffle,
2714 // then combining may result in worse codegen.
2715 if (!Op0->hasOneUse())
2716 return nullptr;
2717
2718 // We are extracting a subvector from a shuffle. Remove excess elements from
2719 // the 1st shuffle mask to eliminate the extract.
2720 //
2721 // This transform is conservatively limited to identity extracts because we do
2722 // not allow arbitrary shuffle mask creation as a target-independent transform
2723 // (because we can't guarantee that will lower efficiently).
2724 //
2725 // If the extracting shuffle has an poison mask element, it transfers to the
2726 // new shuffle mask. Otherwise, copy the original mask element. Example:
2727 // shuf (shuf X, Y, <C0, C1, C2, poison, C4>), poison, <0, poison, 2, 3> -->
2728 // shuf X, Y, <C0, poison, C2, poison>
2729 unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
2730 SmallVector<int, 16> NewMask(NumElts);
2731 assert(NumElts < Mask.size() &&
2732 "Identity with extract must have less elements than its inputs");
2733
2734 for (unsigned i = 0; i != NumElts; ++i) {
2735 int ExtractMaskElt = Shuf.getMaskValue(i);
2736 int MaskElt = Mask[i];
2737 NewMask[i] = ExtractMaskElt == PoisonMaskElem ? ExtractMaskElt : MaskElt;
2738 }
2739 return new ShuffleVectorInst(X, Y, NewMask);
2740}
2741
2742/// Try to replace a shuffle with an insertelement or try to replace a shuffle
2743/// operand with the operand of an insertelement.
2745 InstCombinerImpl &IC) {
2746 Value *V0 = Shuf.getOperand(0), *V1 = Shuf.getOperand(1);
2748 Shuf.getShuffleMask(Mask);
2749
2750 int NumElts = Mask.size();
2751 int InpNumElts = cast<FixedVectorType>(V0->getType())->getNumElements();
2752
2753 // This is a specialization of a fold in SimplifyDemandedVectorElts. We may
2754 // not be able to handle it there if the insertelement has >1 use.
2755 // If the shuffle has an insertelement operand but does not choose the
2756 // inserted scalar element from that value, then we can replace that shuffle
2757 // operand with the source vector of the insertelement.
2758 Value *X;
2759 uint64_t IdxC;
2760 if (match(V0, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
2761 // shuf (inselt X, ?, IdxC), ?, Mask --> shuf X, ?, Mask
2762 if (!is_contained(Mask, (int)IdxC))
2763 return IC.replaceOperand(Shuf, 0, X);
2764 }
2765 if (match(V1, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
2766 // Offset the index constant by the vector width because we are checking for
2767 // accesses to the 2nd vector input of the shuffle.
2768 IdxC += InpNumElts;
2769 // shuf ?, (inselt X, ?, IdxC), Mask --> shuf ?, X, Mask
2770 if (!is_contained(Mask, (int)IdxC))
2771 return IC.replaceOperand(Shuf, 1, X);
2772 }
2773 // For the rest of the transform, the shuffle must not change vector sizes.
2774 // TODO: This restriction could be removed if the insert has only one use
2775 // (because the transform would require a new length-changing shuffle).
2776 if (NumElts != InpNumElts)
2777 return nullptr;
2778
2779 // shuffle (insert ?, Scalar, IndexC), V1, Mask --> insert V1, Scalar, IndexC'
2780 auto isShufflingScalarIntoOp1 = [&](Value *&Scalar, ConstantInt *&IndexC) {
2781 // We need an insertelement with a constant index.
2782 if (!match(V0, m_InsertElt(m_Value(), m_Value(Scalar),
2783 m_ConstantInt(IndexC))))
2784 return false;
2785
2786 // Test the shuffle mask to see if it splices the inserted scalar into the
2787 // operand 1 vector of the shuffle.
2788 int NewInsIndex = -1;
2789 for (int i = 0; i != NumElts; ++i) {
2790 // Ignore undef mask elements.
2791 if (Mask[i] == -1)
2792 continue;
2793
2794 // The shuffle takes elements of operand 1 without lane changes.
2795 if (Mask[i] == NumElts + i)
2796 continue;
2797
2798 // The shuffle must choose the inserted scalar exactly once.
2799 if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue())
2800 return false;
2801
2802 // The shuffle is placing the inserted scalar into element i.
2803 NewInsIndex = i;
2804 }
2805
2806 assert(NewInsIndex != -1 && "Did not fold shuffle with unused operand?");
2807
2808 // Index is updated to the potentially translated insertion lane.
2809 IndexC = ConstantInt::get(IndexC->getIntegerType(), NewInsIndex);
2810 return true;
2811 };
2812
2813 // If the shuffle is unnecessary, insert the scalar operand directly into
2814 // operand 1 of the shuffle. Example:
2815 // shuffle (insert ?, S, 1), V1, <1, 5, 6, 7> --> insert V1, S, 0
2816 Value *Scalar;
2817 ConstantInt *IndexC;
2818 if (isShufflingScalarIntoOp1(Scalar, IndexC))
2819 return InsertElementInst::Create(V1, Scalar, IndexC);
2820
2821 // Try again after commuting shuffle. Example:
2822 // shuffle V0, (insert ?, S, 0), <0, 1, 2, 4> -->
2823 // shuffle (insert ?, S, 0), V0, <4, 5, 6, 0> --> insert V0, S, 3
2824 std::swap(V0, V1);
2826 if (isShufflingScalarIntoOp1(Scalar, IndexC))
2827 return InsertElementInst::Create(V1, Scalar, IndexC);
2828
2829 return nullptr;
2830}
2831
2833 // Match the operands as identity with padding (also known as concatenation
2834 // with undef) shuffles of the same source type. The backend is expected to
2835 // recreate these concatenations from a shuffle of narrow operands.
2836 auto *Shuffle0 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(0));
2837 auto *Shuffle1 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(1));
2838 if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() ||
2839 !Shuffle1 || !Shuffle1->isIdentityWithPadding())
2840 return nullptr;
2841
2842 // We limit this transform to power-of-2 types because we expect that the
2843 // backend can convert the simplified IR patterns to identical nodes as the
2844 // original IR.
2845 // TODO: If we can verify the same behavior for arbitrary types, the
2846 // power-of-2 checks can be removed.
2847 Value *X = Shuffle0->getOperand(0);
2848 Value *Y = Shuffle1->getOperand(0);
2849 if (X->getType() != Y->getType() ||
2850 !isPowerOf2_32(cast<FixedVectorType>(Shuf.getType())->getNumElements()) ||
2852 cast<FixedVectorType>(Shuffle0->getType())->getNumElements()) ||
2853 !isPowerOf2_32(cast<FixedVectorType>(X->getType())->getNumElements()) ||
2854 match(X, m_Undef()) || match(Y, m_Undef()))
2855 return nullptr;
2856 assert(match(Shuffle0->getOperand(1), m_Undef()) &&
2857 match(Shuffle1->getOperand(1), m_Undef()) &&
2858 "Unexpected operand for identity shuffle");
2859
2860 // This is a shuffle of 2 widening shuffles. We can shuffle the narrow source
2861 // operands directly by adjusting the shuffle mask to account for the narrower
2862 // types:
2863 // shuf (widen X), (widen Y), Mask --> shuf X, Y, Mask'
2864 int NarrowElts = cast<FixedVectorType>(X->getType())->getNumElements();
2865 int WideElts = cast<FixedVectorType>(Shuffle0->getType())->getNumElements();
2866 assert(WideElts > NarrowElts && "Unexpected types for identity with padding");
2867
2868 ArrayRef<int> Mask = Shuf.getShuffleMask();
2869 SmallVector<int, 16> NewMask(Mask.size(), -1);
2870 for (int i = 0, e = Mask.size(); i != e; ++i) {
2871 if (Mask[i] == -1)
2872 continue;
2873
2874 // If this shuffle is choosing an undef element from 1 of the sources, that
2875 // element is undef.
2876 if (Mask[i] < WideElts) {
2877 if (Shuffle0->getMaskValue(Mask[i]) == -1)
2878 continue;
2879 } else {
2880 if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1)
2881 continue;
2882 }
2883
2884 // If this shuffle is choosing from the 1st narrow op, the mask element is
2885 // the same. If this shuffle is choosing from the 2nd narrow op, the mask
2886 // element is offset down to adjust for the narrow vector widths.
2887 if (Mask[i] < WideElts) {
2888 assert(Mask[i] < NarrowElts && "Unexpected shuffle mask");
2889 NewMask[i] = Mask[i];
2890 } else {
2891 assert(Mask[i] < (WideElts + NarrowElts) && "Unexpected shuffle mask");
2892 NewMask[i] = Mask[i] - (WideElts - NarrowElts);
2893 }
2894 }
2895 return new ShuffleVectorInst(X, Y, NewMask);
2896}
2897
2898// Splatting the first element of the result of a BinOp, where any of the
2899// BinOp's operands are the result of a first element splat can be simplified to
2900// splatting the first element of the result of the BinOp
2902 if (!match(SVI.getOperand(1), m_Poison()) ||
2903 !match(SVI.getShuffleMask(), m_ZeroMask()) ||
2904 !SVI.getOperand(0)->hasOneUse())
2905 return nullptr;
2906
2907 Value *Op0 = SVI.getOperand(0);
2908 Value *X, *Y;
2910 m_Value(Y))) &&
2911 !match(Op0, m_BinOp(m_Value(X),
2913 return nullptr;
2914 if (X->getType() != Y->getType())
2915 return nullptr;
2916
2917 auto *BinOp = cast<BinaryOperator>(Op0);
2919 return nullptr;
2920
2921 Value *NewBO = Builder.CreateBinOp(BinOp->getOpcode(), X, Y);
2922 if (auto NewBOI = dyn_cast<Instruction>(NewBO))
2923 NewBOI->copyIRFlags(BinOp);
2924
2925 return new ShuffleVectorInst(NewBO, SVI.getShuffleMask());
2926}
2927
2929 Value *LHS = SVI.getOperand(0);
2930 Value *RHS = SVI.getOperand(1);
2931 SimplifyQuery ShufQuery = SQ.getWithInstruction(&SVI);
2932 if (auto *V = simplifyShuffleVectorInst(LHS, RHS, SVI.getShuffleMask(),
2933 SVI.getType(), ShufQuery))
2934 return replaceInstUsesWith(SVI, V);
2935
2936 if (Instruction *I = simplifyBinOpSplats(SVI))
2937 return I;
2938
2939 // Canonicalize splat shuffle to use poison RHS. Handle this explicitly in
2940 // order to support scalable vectors.
2941 if (match(SVI.getShuffleMask(), m_ZeroMask()) && !isa<PoisonValue>(RHS))
2942 return replaceOperand(SVI, 1, PoisonValue::get(RHS->getType()));
2943
2944 if (isa<ScalableVectorType>(LHS->getType()))
2945 return nullptr;
2946
2947 unsigned VWidth = cast<FixedVectorType>(SVI.getType())->getNumElements();
2948 unsigned LHSWidth = cast<FixedVectorType>(LHS->getType())->getNumElements();
2949
2950 // shuffle (bitcast X), (bitcast Y), Mask --> bitcast (shuffle X, Y, Mask)
2951 //
2952 // if X and Y are of the same (vector) type, and the element size is not
2953 // changed by the bitcasts, we can distribute the bitcasts through the
2954 // shuffle, hopefully reducing the number of instructions. We make sure that
2955 // at least one bitcast only has one use, so we don't *increase* the number of
2956 // instructions here.
2957 Value *X, *Y;
2958 if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_BitCast(m_Value(Y))) &&
2959 X->getType()->isVectorTy() && X->getType() == Y->getType() &&
2960 X->getType()->getScalarSizeInBits() ==
2961 SVI.getType()->getScalarSizeInBits() &&
2962 (LHS->hasOneUse() || RHS->hasOneUse())) {
2963 Value *V = Builder.CreateShuffleVector(X, Y, SVI.getShuffleMask(),
2964 SVI.getName() + ".uncasted");
2965 return new BitCastInst(V, SVI.getType());
2966 }
2967
2968 ArrayRef<int> Mask = SVI.getShuffleMask();
2969
2970 // Peek through a bitcasted shuffle operand by scaling the mask. If the
2971 // simulated shuffle can simplify, then this shuffle is unnecessary:
2972 // shuf (bitcast X), undef, Mask --> bitcast X'
2973 // TODO: This could be extended to allow length-changing shuffles.
2974 // The transform might also be obsoleted if we allowed canonicalization
2975 // of bitcasted shuffles.
2976 if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_Undef()) &&
2977 X->getType()->isVectorTy() && VWidth == LHSWidth) {
2978 // Try to create a scaled mask constant.
2979 auto *XType = cast<FixedVectorType>(X->getType());
2980 unsigned XNumElts = XType->getNumElements();
2981 SmallVector<int, 16> ScaledMask;
2982 if (scaleShuffleMaskElts(XNumElts, Mask, ScaledMask)) {
2983 // If the shuffled source vector simplifies, cast that value to this
2984 // shuffle's type.
2985 if (auto *V = simplifyShuffleVectorInst(X, UndefValue::get(XType),
2986 ScaledMask, XType, ShufQuery))
2987 return BitCastInst::Create(Instruction::BitCast, V, SVI.getType());
2988 }
2989 }
2990
2991 // shuffle x, x, mask --> shuffle x, undef, mask'
2992 if (LHS == RHS) {
2993 assert(!match(RHS, m_Undef()) &&
2994 "Shuffle with 2 undef ops not simplified?");
2995 return new ShuffleVectorInst(LHS, createUnaryMask(Mask, LHSWidth));
2996 }
2997
2998 // shuffle undef, x, mask --> shuffle x, undef, mask'
2999 if (match(LHS, m_Undef())) {
3000 SVI.commute();
3001 return &SVI;
3002 }
3003
3005 return I;
3006
3007 if (Instruction *I = foldSelectShuffle(SVI))
3008 return I;
3009
3010 if (Instruction *I = foldTruncShuffle(SVI, DL.isBigEndian()))
3011 return I;
3012
3014 return I;
3015
3017 return I;
3018
3019 if (Instruction *I = foldCastShuffle(SVI, Builder))
3020 return I;
3021
3022 APInt PoisonElts(VWidth, 0);
3023 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
3024 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, PoisonElts)) {
3025 if (V != &SVI)
3026 return replaceInstUsesWith(SVI, V);
3027 return &SVI;
3028 }
3029
3031 return I;
3032
3033 // These transforms have the potential to lose undef knowledge, so they are
3034 // intentionally placed after SimplifyDemandedVectorElts().
3035 if (Instruction *I = foldShuffleWithInsert(SVI, *this))
3036 return I;
3038 return I;
3039
3040 if (match(RHS, m_Constant())) {
3041 if (auto *SI = dyn_cast<SelectInst>(LHS)) {
3042 // We cannot do this fold for elementwise select since ShuffleVector is
3043 // not elementwise.
3044 if (SI->getCondition()->getType()->isIntegerTy() &&
3045 (isa<PoisonValue>(RHS) ||
3046 isGuaranteedNotToBePoison(SI->getCondition()))) {
3047 if (Instruction *I = FoldOpIntoSelect(SVI, SI))
3048 return I;
3049 }
3050 }
3051 if (auto *PN = dyn_cast<PHINode>(LHS)) {
3052 if (Instruction *I = foldOpIntoPhi(SVI, PN, /*AllowMultipleUses=*/true))
3053 return I;
3054 }
3055 }
3056
3057 if (match(RHS, m_Poison()) && canEvaluateShuffled(LHS, Mask)) {
3059 return replaceInstUsesWith(SVI, V);
3060 }
3061
3062 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
3063 // a non-vector type. We can instead bitcast the original vector followed by
3064 // an extract of the desired element:
3065 //
3066 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
3067 // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
3068 // %1 = bitcast <4 x i8> %sroa to i32
3069 // Becomes:
3070 // %bc = bitcast <16 x i8> %in to <4 x i32>
3071 // %ext = extractelement <4 x i32> %bc, i32 0
3072 //
3073 // If the shuffle is extracting a contiguous range of values from the input
3074 // vector then each use which is a bitcast of the extracted size can be
3075 // replaced. This will work if the vector types are compatible, and the begin
3076 // index is aligned to a value in the casted vector type. If the begin index
3077 // isn't aligned then we can shuffle the original vector (keeping the same
3078 // vector type) before extracting.
3079 //
3080 // This code will bail out if the target type is fundamentally incompatible
3081 // with vectors of the source type.
3082 //
3083 // Example of <16 x i8>, target type i32:
3084 // Index range [4,8): v-----------v Will work.
3085 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
3086 // <16 x i8>: | | | | | | | | | | | | | | | | |
3087 // <4 x i32>: | | | | |
3088 // +-----------+-----------+-----------+-----------+
3089 // Index range [6,10): ^-----------^ Needs an extra shuffle.
3090 // Target type i40: ^--------------^ Won't work, bail.
3091 bool MadeChange = false;
3092 if (isShuffleExtractingFromLHS(SVI, Mask)) {
3093 Value *V = LHS;
3094 unsigned MaskElems = Mask.size();
3095 auto *SrcTy = cast<FixedVectorType>(V->getType());
3096 unsigned VecBitWidth = DL.getTypeSizeInBits(SrcTy);
3097 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
3098 assert(SrcElemBitWidth && "vector elements must have a bitwidth");
3099 unsigned SrcNumElems = SrcTy->getNumElements();
3102 for (User *U : SVI.users())
3103 if (BitCastInst *BC = dyn_cast<BitCastInst>(U)) {
3104 // Only visit bitcasts that weren't previously handled.
3105 if (BC->use_empty())
3106 continue;
3107 // Prefer to combine bitcasts of bitcasts before attempting this fold.
3108 if (BC->hasOneUse()) {
3109 auto *BC2 = dyn_cast<BitCastInst>(BC->user_back());
3110 if (BC2 && isEliminableCastPair(BC, BC2))
3111 continue;
3112 }
3113 BCs.push_back(BC);
3114 }
3115 for (BitCastInst *BC : BCs) {
3116 unsigned BegIdx = Mask.front();
3117 Type *TgtTy = BC->getDestTy();
3118 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
3119 if (!TgtElemBitWidth)
3120 continue;
3121 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
3122 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
3123 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
3124 if (!VecBitWidthsEqual)
3125 continue;
3127 continue;
3128 auto *CastSrcTy = FixedVectorType::get(TgtTy, TgtNumElems);
3129 if (!BegIsAligned) {
3130 // Shuffle the input so [0,NumElements) contains the output, and
3131 // [NumElems,SrcNumElems) is undef.
3132 SmallVector<int, 16> ShuffleMask(SrcNumElems, -1);
3133 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
3134 ShuffleMask[I] = Idx;
3135 V = Builder.CreateShuffleVector(V, ShuffleMask,
3136 SVI.getName() + ".extract");
3137 BegIdx = 0;
3138 }
3139 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
3140 assert(SrcElemsPerTgtElem);
3141 BegIdx /= SrcElemsPerTgtElem;
3142 auto [It, Inserted] = NewBCs.try_emplace(CastSrcTy);
3143 if (Inserted)
3144 It->second = Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
3145 auto *Ext = Builder.CreateExtractElement(It->second, BegIdx,
3146 SVI.getName() + ".extract");
3147 // The shufflevector isn't being replaced: the bitcast that used it
3148 // is. InstCombine will visit the newly-created instructions.
3149 replaceInstUsesWith(*BC, Ext);
3150 MadeChange = true;
3151 }
3152 }
3153
3154 // If the LHS is a shufflevector itself, see if we can combine it with this
3155 // one without producing an unusual shuffle.
3156 // Cases that might be simplified:
3157 // 1.
3158 // x1=shuffle(v1,v2,mask1)
3159 // x=shuffle(x1,undef,mask)
3160 // ==>
3161 // x=shuffle(v1,undef,newMask)
3162 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
3163 // 2.
3164 // x1=shuffle(v1,undef,mask1)
3165 // x=shuffle(x1,x2,mask)
3166 // where v1.size() == mask1.size()
3167 // ==>
3168 // x=shuffle(v1,x2,newMask)
3169 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
3170 // 3.
3171 // x2=shuffle(v2,undef,mask2)
3172 // x=shuffle(x1,x2,mask)
3173 // where v2.size() == mask2.size()
3174 // ==>
3175 // x=shuffle(x1,v2,newMask)
3176 // newMask[i] = (mask[i] < x1.size())
3177 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
3178 // 4.
3179 // x1=shuffle(v1,undef,mask1)
3180 // x2=shuffle(v2,undef,mask2)
3181 // x=shuffle(x1,x2,mask)
3182 // where v1.size() == v2.size()
3183 // ==>
3184 // x=shuffle(v1,v2,newMask)
3185 // newMask[i] = (mask[i] < x1.size())
3186 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
3187 //
3188 // Here we are really conservative:
3189 // we are absolutely afraid of producing a shuffle mask not in the input
3190 // program, because the code gen may not be smart enough to turn a merged
3191 // shuffle into two specific shuffles: it may produce worse code. As such,
3192 // we only merge two shuffles if the result is either a splat or one of the
3193 // input shuffle masks. In this case, merging the shuffles just removes
3194 // one instruction, which we know is safe. This is good for things like
3195 // turning: (splat(splat)) -> splat, or
3196 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
3199 if (LHSShuffle)
3200 if (!match(LHSShuffle->getOperand(1), m_Poison()) &&
3201 !match(RHS, m_Poison()))
3202 LHSShuffle = nullptr;
3203 if (RHSShuffle)
3204 if (!match(RHSShuffle->getOperand(1), m_Poison()))
3205 RHSShuffle = nullptr;
3206 if (!LHSShuffle && !RHSShuffle)
3207 return MadeChange ? &SVI : nullptr;
3208
3209 Value* LHSOp0 = nullptr;
3210 Value* LHSOp1 = nullptr;
3211 Value* RHSOp0 = nullptr;
3212 unsigned LHSOp0Width = 0;
3213 unsigned RHSOp0Width = 0;
3214 if (LHSShuffle) {
3215 LHSOp0 = LHSShuffle->getOperand(0);
3216 LHSOp1 = LHSShuffle->getOperand(1);
3217 LHSOp0Width = cast<FixedVectorType>(LHSOp0->getType())->getNumElements();
3218 }
3219 if (RHSShuffle) {
3220 RHSOp0 = RHSShuffle->getOperand(0);
3221 RHSOp0Width = cast<FixedVectorType>(RHSOp0->getType())->getNumElements();
3222 }
3223 Value* newLHS = LHS;
3224 Value* newRHS = RHS;
3225 if (LHSShuffle) {
3226 // case 1
3227 if (match(RHS, m_Poison())) {
3228 newLHS = LHSOp0;
3229 newRHS = LHSOp1;
3230 }
3231 // case 2 or 4
3232 else if (LHSOp0Width == LHSWidth) {
3233 newLHS = LHSOp0;
3234 }
3235 }
3236 // case 3 or 4
3237 if (RHSShuffle && RHSOp0Width == LHSWidth) {
3238 newRHS = RHSOp0;
3239 }
3240 // case 4
3241 if (LHSOp0 == RHSOp0) {
3242 newLHS = LHSOp0;
3243 newRHS = nullptr;
3244 }
3245
3246 if (newLHS == LHS && newRHS == RHS)
3247 return MadeChange ? &SVI : nullptr;
3248
3249 ArrayRef<int> LHSMask;
3250 ArrayRef<int> RHSMask;
3251 if (newLHS != LHS)
3252 LHSMask = LHSShuffle->getShuffleMask();
3253 if (RHSShuffle && newRHS != RHS)
3254 RHSMask = RHSShuffle->getShuffleMask();
3255
3256 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
3257 SmallVector<int, 16> newMask;
3258 bool isSplat = true;
3259 int SplatElt = -1;
3260 // Create a new mask for the new ShuffleVectorInst so that the new
3261 // ShuffleVectorInst is equivalent to the original one.
3262 for (unsigned i = 0; i < VWidth; ++i) {
3263 int eltMask;
3264 if (Mask[i] < 0) {
3265 // This element is a poison value.
3266 eltMask = -1;
3267 } else if (Mask[i] < (int)LHSWidth) {
3268 // This element is from left hand side vector operand.
3269 //
3270 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
3271 // new mask value for the element.
3272 if (newLHS != LHS) {
3273 eltMask = LHSMask[Mask[i]];
3274 // If the value selected is an poison value, explicitly specify it
3275 // with a -1 mask value.
3276 if (eltMask >= (int)LHSOp0Width && isa<PoisonValue>(LHSOp1))
3277 eltMask = -1;
3278 } else
3279 eltMask = Mask[i];
3280 } else {
3281 // This element is from right hand side vector operand
3282 //
3283 // If the value selected is a poison value, explicitly specify it
3284 // with a -1 mask value. (case 1)
3285 if (match(RHS, m_Poison()))
3286 eltMask = -1;
3287 // If RHS is going to be replaced (case 3 or 4), calculate the
3288 // new mask value for the element.
3289 else if (newRHS != RHS) {
3290 eltMask = RHSMask[Mask[i]-LHSWidth];
3291 // If the value selected is an poison value, explicitly specify it
3292 // with a -1 mask value.
3293 if (eltMask >= (int)RHSOp0Width) {
3294 assert(match(RHSShuffle->getOperand(1), m_Poison()) &&
3295 "should have been check above");
3296 eltMask = -1;
3297 }
3298 } else
3299 eltMask = Mask[i]-LHSWidth;
3300
3301 // If LHS's width is changed, shift the mask value accordingly.
3302 // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any
3303 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
3304 // If newRHS == newLHS, we want to remap any references from newRHS to
3305 // newLHS so that we can properly identify splats that may occur due to
3306 // obfuscation across the two vectors.
3307 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
3308 eltMask += newLHSWidth;
3309 }
3310
3311 // Check if this could still be a splat.
3312 if (eltMask >= 0) {
3313 if (SplatElt >= 0 && SplatElt != eltMask)
3314 isSplat = false;
3315 SplatElt = eltMask;
3316 }
3317
3318 newMask.push_back(eltMask);
3319 }
3320
3321 // If the result mask is equal to one of the original shuffle masks,
3322 // or is a splat, do the replacement.
3323 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
3324 if (!newRHS)
3325 newRHS = PoisonValue::get(newLHS->getType());
3326 return new ShuffleVectorInst(newLHS, newRHS, newMask);
3327 }
3328
3329 return MadeChange ? &SVI : nullptr;
3330}
3331
3332/// Given the following de-interleaving shufflevectors and the consuming zexts:
3333/// ```
3334/// %f0 = shufflevector <8 x i32> %v, <4 x i32> <i32 0, i32 2, i32 4, i32 6>
3335/// %f1 = shufflevector <8 x i32> %v, <4 x i32> <i32 1, i32 3, i32 5, i32 7>
3336/// %z0 = zext <4 x i32> %f0 to <4 x i64>
3337/// %z1 = zext <4 x i32> %f1 to <4 x i64>
3338/// ```
3339/// We can actually bitcast the input value, `%v` first before replacing zexts
3340/// with simple arithmetics on this new bitcast:
3341/// ```
3342/// %bc = bitcast <8 x i32> %v to <4 x i64>
3343// %z0 = and <4 x i64> %bc, splat (i64 4294967295)
3344// %z1 = lshr <4 x i64> %bc, splat (i64 32)
3345/// ```
3346/// This transformation is almost always benefitial as shufflevector is more
3347/// expensive than normal arithmetics.
3350 // This pattern involves bitcast that is not compatible with big endian.
3351 if (DL.isBigEndian())
3352 return nullptr;
3353
3354 // The actual value that got de-interleaved.
3355 Value *DIV;
3356
3357 using namespace PatternMatch;
3358 Instruction *SVI = nullptr, *DI = nullptr;
3359 if (!match(
3360 &RootZExt,
3363 m_Instruction(SVI, m_Shuffle(m_Value(), m_Value()))))))
3364 return nullptr;
3365
3366 auto isDeinterleaveShuffle =
3367 [](Instruction *I) -> std::pair<Value *, unsigned> {
3368 Value *V;
3369 ArrayRef<int> ShuffleMask;
3370 unsigned Index;
3371 if (match(I, m_Shuffle(m_Value(V), m_Undef(), m_Mask(ShuffleMask))) &&
3372 isa<FixedVectorType>(V->getType())) {
3373 unsigned NumInputElements =
3374 cast<VectorType>(V->getType())->getElementCount().getFixedValue();
3376 Index) &&
3377 Index < 2 &&
3379 NumInputElements) &&
3380 ShuffleMask.size() * 2 == NumInputElements)
3381 return {V, Index};
3382 }
3383 return {nullptr, UINT_MAX};
3384 };
3385
3386 // Validate either the shufflevector or the vector.deinterleave2 and obtain
3387 // the value they're de-interleaving.
3388 if (SVI) {
3389 // We will find other shufflevectors later.
3390 DIV = isDeinterleaveShuffle(SVI).first;
3391 if (!DIV)
3392 return nullptr;
3393 } else {
3394 // We should already capture the value that got de-interleaved (i.e. DIV).
3395 assert(DI && DIV);
3396 if (!all_of(DI->users(), [](User *Usr) -> bool {
3397 auto *EV = dyn_cast<ExtractValueInst>(Usr);
3398 return EV && EV->getNumIndices() == 1;
3399 }))
3400 return nullptr;
3401 }
3402
3403 auto *InputVecTy = dyn_cast<VectorType>(DIV->getType());
3404 if (!InputVecTy)
3405 return nullptr;
3406 auto *InElementTy = dyn_cast<IntegerType>(InputVecTy->getElementType());
3407 if (!InElementTy)
3408 return nullptr;
3409 if (!InputVecTy->getElementCount().isKnownEven())
3410 return nullptr;
3411
3412 // {Field instruction, Field index}
3414 if (SVI) {
3415 for (auto *Usr : DIV->users()) {
3416 auto *FieldI = dyn_cast<Instruction>(Usr);
3417 if (!FieldI)
3418 continue;
3419 auto [V, Index] = isDeinterleaveShuffle(FieldI);
3420 if (V != DIV)
3421 continue;
3422 assert(Index < 2);
3423 // Find the earliest field extraction instruction.
3424 if (FieldI->getParent() != SVI->getParent())
3425 continue;
3426 if (FieldI != SVI && FieldI->comesBefore(SVI))
3427 SVI = FieldI;
3428 Fields.push_back({FieldI, Index});
3429 }
3430 } else {
3431 // llvm.vector.deinterleave2.
3432 for (User *Field : DI->users()) {
3433 auto *FieldI = cast<ExtractValueInst>(Field);
3434 unsigned FieldIdx = *FieldI->idx_begin();
3435 assert(FieldIdx < 2);
3436 Fields.push_back({FieldI, FieldIdx});
3437 }
3438 }
3439
3440 // {field to be replaced, field index}
3441 SmallVector<std::pair<ZExtInst *, unsigned>, 4> FieldReplacements;
3442 // We commit the transformation only if all the field users can be replaced,
3443 // otherwise the primary de-interleaving construction, regardless of
3444 // llvm.vector.deinterleave2 or shufflevectors, will still be there.
3445 for (auto [Field, FieldIdx] : Fields) {
3446 for (User *FieldUsr : Field->users()) {
3447 auto *ZExt = dyn_cast<ZExtInst>(FieldUsr);
3448 if (!ZExt)
3449 return nullptr;
3450 // Only if it's doubling the element size.
3451 if (ZExt->getDestTy() != ZExt->getSrcTy()->getExtendedType())
3452 return nullptr;
3453 FieldReplacements.push_back({ZExt, FieldIdx});
3454 }
3455 }
3456
3457 // This will insert replacement instructions before all the fields users.
3458 Builder.SetInsertPoint(DI ? DI : SVI);
3459
3460 // Double the element size but half the vector length.
3461 auto *BitcastedTy = VectorType::getExtendedElementVectorType(InputVecTy);
3462 BitcastedTy = VectorType::getHalfElementsVectorType(BitcastedTy);
3463 // Since we're going to "merge" lanes via bitcast, we need to freeze any
3464 // potential poison lanes first.
3465 Value *Freeze = Builder.CreateFreeze(DIV);
3466 Value *Bitcast = Builder.CreateBitCast(Freeze, BitcastedTy);
3467 unsigned InElementBitWidth = InElementTy->getBitWidth();
3468 auto Mask = APInt::getLowBitsSet(InElementBitWidth * 2, InElementBitWidth);
3469 Value *NewField0 = Builder.CreateAnd(Bitcast, Mask);
3470 Value *NewField1 = Builder.CreateLShr(Bitcast, InElementBitWidth);
3471
3472 for (auto [I, Idx] : FieldReplacements) {
3473 assert(Idx < 2 && "unsupported field index");
3474 replaceInstUsesWith(*I, Idx ? NewField1 : NewField0);
3475 // Make sure the old ZExt are in the worklist so that they
3476 // can be removed in the following iterations.
3478 }
3479
3480 return &RootZExt;
3481}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
constexpr LLT S1
Rewrite undef for PHI
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
#define X(NUM, ENUM, NAME)
Definition ELF.h:856
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
This file defines the DenseMap class.
Hexagon Common GEP
This file provides internal interfaces used to implement the InstCombine.
static Instruction * foldConstantInsEltIntoShuffle(InsertElementInst &InsElt)
insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex --> shufflevector X,...
static Value * evaluateInDifferentElementOrder(Value *V, ArrayRef< int > Mask, IRBuilderBase &Builder)
static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, SmallVectorImpl< int > &Mask)
If V is a shuffle of values that ONLY returns elements from either LHS or RHS, return the shuffle mas...
static ShuffleOps collectShuffleElements(Value *V, SmallVectorImpl< int > &Mask, Value *PermittedRHS, InstCombinerImpl &IC, bool &Rerun)
static APInt findDemandedEltsByAllUsers(Value *V)
Find union of elements of V demanded by all its users.
static Instruction * foldTruncInsEltPair(InsertElementInst &InsElt, bool IsBigEndian, InstCombiner::BuilderTy &Builder)
If we are inserting 2 halves of a value into adjacent elements of a vector, try to convert to a singl...
static Instruction * foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf, const SimplifyQuery &SQ)
static Instruction * foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf)
static Instruction * foldIdentityExtractShuffle(ShuffleVectorInst &Shuf)
Try to fold an extract subvector operation.
static bool findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr, APInt &UnionUsedElts)
Find elements of V demanded by UserInstr.
static Instruction * foldInsEltIntoSplat(InsertElementInst &InsElt)
Try to fold an insert element into an existing splat shuffle by changing the shuffle's mask to includ...
std::pair< Value *, Value * > ShuffleOps
We are building a shuffle to create V, which is a sequence of insertelement, extractelement pairs.
static Instruction * foldShuffleWithInsert(ShuffleVectorInst &Shuf, InstCombinerImpl &IC)
Try to replace a shuffle with an insertelement or try to replace a shuffle operand with the operand o...
static Instruction * canonicalizeInsertSplat(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder)
If we have an insert of a scalar to a non-zero element of an undefined vector and then shuffle that v...
static Instruction * foldTruncShuffle(ShuffleVectorInst &Shuf, bool IsBigEndian)
Convert a narrowing shuffle of a bitcasted vector into a vector truncate.
static bool replaceExtractElements(InsertElementInst *InsElt, ExtractElementInst *ExtElt, InstCombinerImpl &IC)
If we have insertion into a vector that is wider than the vector that we are extracting from,...
static bool cheapToScalarize(Value *V, Value *EI)
Return true if the value is cheaper to scalarize than it is to leave as a vector operation.
static Value * buildNew(Instruction *I, ArrayRef< Value * > NewOps, IRBuilderBase &Builder)
Rebuild a new instruction just like 'I' but with the new operands given.
static bool canEvaluateShuffled(Value *V, ArrayRef< int > Mask, unsigned Depth=5)
Return true if we can evaluate the specified expression tree if the vector elements were shuffled in ...
static Instruction * foldSelectShuffleOfSelectShuffle(ShuffleVectorInst &Shuf)
A select shuffle of a select shuffle with a shared operand can be reduced to a single select shuffle.
static Instruction * hoistInsEltConst(InsertElementInst &InsElt2, InstCombiner::BuilderTy &Builder)
If we have an insertelement instruction feeding into another insertelement and the 2nd is inserting a...
static Instruction * foldShuffleOfUnaryOps(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder)
Canonicalize FP negate/abs after shuffle.
static Instruction * foldCastShuffle(ShuffleVectorInst &Shuf, InstCombiner::BuilderTy &Builder)
Canonicalize casts after shuffle.
static Instruction * narrowInsElt(InsertElementInst &InsElt, InstCombiner::BuilderTy &Builder)
If both the base vector and the inserted element are extended from the same type, do the insert eleme...
static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf)
static Instruction * foldInsSequenceIntoSplat(InsertElementInst &InsElt)
Turn a chain of inserts that splats a value into an insert + shuffle: insertelt(insertelt(insertelt(i...
static Instruction * foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt)
Try to fold an extract+insert element into an existing identity shuffle by changing the shuffle's mas...
static ConstantInt * getPreferredVectorIndex(ConstantInt *IndexC)
Given a constant index for a extractelement or insertelement instruction, return it with the canonica...
static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI, ArrayRef< int > Mask)
static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL)
Binops may be transformed into binops with different opcodes and operands.
This file provides the interface for the instcombine pass implementation.
static bool isSplat(Value *V)
Return true if V is a splat of a value (which is used when multiplying a matrix with a scalar).
#define I(x, y, z)
Definition MD5.cpp:57
uint64_t IntrinsicInst * II
OptimizedStructLayoutField Field
const SmallVectorImpl< MachineOperand > & Cond
This file contains some templates that are useful if you are working with the STL at all.
This file implements the SmallBitVector class.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition Statistic.h:171
static TableGen::Emitter::Opt Y("gen-skeleton-entry", EmitSkeleton, "Generate example skeleton entry")
static SDValue narrowVectorSelect(SDNode *N, SelectionDAG &DAG, const SDLoc &DL, const X86Subtarget &Subtarget)
If both arms of a vector select are concatenated vectors, split the select, and concatenate the resul...
Value * RHS
Value * LHS
static const uint32_t IV[8]
Definition blake3_impl.h:83
Class for arbitrary precision integers.
Definition APInt.h:78
static APInt getAllOnes(unsigned numBits)
Return an APInt of a specified width with all bits set.
Definition APInt.h:235
LLVM_ABI APInt zextOrTrunc(unsigned width) const
Zero extend or truncate to width.
Definition APInt.cpp:1076
unsigned getActiveBits() const
Compute the number of active bits in the value.
Definition APInt.h:1537
void setBit(unsigned BitPosition)
Set the given bit to 1 whose position is given as "bitPosition".
Definition APInt.h:1355
bool isAllOnes() const
Determine if all bits are set. This is true for zero-width values.
Definition APInt.h:372
bool ult(const APInt &RHS) const
Unsigned less than comparison.
Definition APInt.h:1120
static APInt getLowBitsSet(unsigned numBits, unsigned loBitsSet)
Constructs an APInt value that has the bottom loBitsSet bits set.
Definition APInt.h:307
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
const T & front() const
Get the first element.
Definition ArrayRef.h:144
size_t size() const
Get the array size.
Definition ArrayRef.h:141
ArrayRef< T > slice(size_t N, size_t M) const
slice(n, m) - Chop off the first N elements of the array, and keep M elements in the array.
Definition ArrayRef.h:185
LLVM Basic Block Representation.
Definition BasicBlock.h:62
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
Definition BasicBlock.h:213
InstListType::iterator iterator
Instruction iterators...
Definition BasicBlock.h:170
BinaryOps getOpcode() const
Definition InstrTypes.h:409
static LLVM_ABI BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), InsertPosition InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
static BinaryOperator * CreateWithCopiedFlags(BinaryOps Opc, Value *V1, Value *V2, Value *CopyO, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:254
This class represents a no-op cast from one type to another.
static CallInst * Create(FunctionType *Ty, Value *F, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
static LLVM_ABI CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
This class is the base class for the comparison instructions.
Definition InstrTypes.h:728
static LLVM_ABI CmpInst * CreateWithCopiedFlags(OtherOps Op, Predicate Pred, Value *S1, Value *S2, const Instruction *FlagsSource, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Construct a compare instruction, given the opcode, the predicate, the two operands and the instructio...
OtherOps getOpcode() const
Get the opcode casted to the right type.
Definition InstrTypes.h:823
An abstraction over a floating-point predicate, and a pack of an integer predicate with samesign info...
static LLVM_ABI ConstantAggregateZero * get(Type *Ty)
static LLVM_ABI Constant * getShuffleVector(Constant *V1, Constant *V2, ArrayRef< int > Mask, Type *OnlyIfReducedTy=nullptr)
static LLVM_ABI Constant * getBinOpIdentity(unsigned Opcode, Type *Ty, bool AllowRHSConstant=false, bool NSZ=false)
Return the identity constant for a binary opcode.
This is the shared class of boolean and integer constants.
Definition Constants.h:87
uint64_t getLimitedValue(uint64_t Limit=~0ULL) const
getLimitedValue - If the value is smaller than the specified limit, return it, otherwise return the l...
Definition Constants.h:269
unsigned getBitWidth() const
getBitWidth - Return the scalar bitwidth of this constant.
Definition Constants.h:162
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition Constants.h:168
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition Constants.h:159
static LLVM_ABI Constant * get(ArrayRef< Constant * > V)
This is an important base class in LLVM.
Definition Constant.h:43
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
LLVM_ABI Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:64
static DebugLoc getCompilerGenerated()
Definition DebugLoc.h:154
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:250
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Definition DenseMap.h:299
This instruction extracts a single (scalar) element from a VectorType value.
static ExtractElementInst * Create(Value *Vec, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
VectorType * getVectorOperandType() const
static LLVM_ABI FixedVectorType * get(Type *ElementType, unsigned NumElts)
Definition Type.cpp:867
an instruction for type-safe pointer arithmetic to access elements of arrays and structs
static GetElementPtrInst * Create(Type *PointeeType, Value *Ptr, ArrayRef< Value * > IdxList, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
LLVM_ABI void setNoWrapFlags(GEPNoWrapFlags NW)
Set nowrap flags for GEP instruction.
Common base class shared among various IRBuilders.
Definition IRBuilder.h:114
This instruction inserts a single (scalar) element into a VectorType value.
static InsertElementInst * Create(Value *Vec, Value *NewElt, Value *Idx, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
VectorType * getType() const
Overload to return most specific vector type.
This instruction inserts a struct field of array element value into an aggregate value.
Instruction * foldExtractionOfVectorDeinterleave(ZExtInst &RootZExt)
Instruction * foldOpIntoPhi(Instruction &I, PHINode *PN, bool AllowMultipleUses=false)
Given a binary operator, cast instruction, or select which has a PHI node as operand #0,...
Value * SimplifyDemandedVectorElts(Value *V, APInt DemandedElts, APInt &PoisonElts, unsigned Depth=0, bool AllowMultipleUsers=false) override
The specified value produces a vector with any number of elements.
Instruction * foldSelectShuffle(ShuffleVectorInst &Shuf)
Try to fold shuffles that are the equivalent of a vector select.
Instruction * FoldOpIntoSelect(Instruction &Op, SelectInst *SI, bool FoldWithMultiUse=false, bool SimplifyBothArms=false)
Given an instruction with a select as one operand and a constant as the other operand,...
Instruction * visitInsertValueInst(InsertValueInst &IV)
Try to find redundant insertvalue instructions, like the following ones: %0 = insertvalue { i8,...
Instruction * visitInsertElementInst(InsertElementInst &IE)
Instruction * visitExtractElementInst(ExtractElementInst &EI)
Instruction * simplifyBinOpSplats(ShuffleVectorInst &SVI)
Instruction * foldAggregateConstructionIntoAggregateReuse(InsertValueInst &OrigIVI)
Look for chain of insertvalue's that fully define an aggregate, and trace back the values inserted,...
Instruction * visitShuffleVectorInst(ShuffleVectorInst &SVI)
SimplifyQuery SQ
Instruction * replaceInstUsesWith(Instruction &I, Value *V)
A combiner-aware RAUW-like routine.
InstructionWorklist & Worklist
A worklist of the instructions that need to be simplified.
Instruction * InsertNewInstWith(Instruction *New, BasicBlock::iterator Old)
Same as InsertNewInstBefore, but also sets the debug loc.
const DataLayout & DL
IRBuilder< TargetFolder, IRBuilderInstCombineInserter > BuilderTy
An IRBuilder that automatically inserts new instructions into the worklist.
void addToWorklist(Instruction *I)
Instruction * replaceOperand(Instruction &I, unsigned OpNum, Value *V)
Replace operand of instruction and add old operand to the worklist.
static Constant * getSafeVectorConstantForBinop(BinaryOperator::BinaryOps Opcode, Constant *In, bool IsRHSConstant)
Some binary operators require special handling to avoid poison and undefined behavior.
const SimplifyQuery & getSimplifyQuery() const
LLVM_ABI bool hasNoUnsignedWrap() const LLVM_READONLY
Determine whether the no unsigned wrap flag is set.
LLVM_ABI bool hasNoInfs() const LLVM_READONLY
Determine whether the no-infs flag is set.
LLVM_ABI bool hasNoSignedWrap() const LLVM_READONLY
Determine whether the no signed wrap flag is set.
LLVM_ABI void copyIRFlags(const Value *V, bool IncludeWrapFlags=true)
Convenience method to copy supported exact, fast-math, and (optionally) wrapping flags from V to this...
LLVM_ABI const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
LLVM_ABI void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
LLVM_ABI bool isExact() const LLVM_READONLY
Determine whether the exact flag is set.
LLVM_ABI void setHasNoInfs(bool B)
Set or clear the no-infs flag on this instruction, which must be an operator which supports this flag...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
bool isShift() const
LLVM_ABI void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
bool isIntDivRem() const
A wrapper class for inspecting calls to intrinsic functions.
std::pair< iterator, bool > try_emplace(const KeyT &Key, Ts &&...Args)
Definition MapVector.h:118
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
In order to facilitate speculative execution, many instructions do not invoke immediate undefined beh...
Definition Constants.h:1679
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
This class represents the LLVM 'select' instruction.
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", InsertPosition InsertBefore=nullptr, const Instruction *MDFrom=nullptr)
This instruction constructs a fixed permutation of two input vectors.
bool changesLength() const
Return true if this shuffle returns a vector with a different number of elements than its source vect...
int getMaskValue(unsigned Elt) const
Return the shuffle mask value of this instruction for the given element index.
static LLVM_ABI bool isSelectMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from its source vectors without lane crossings.
VectorType * getType() const
Overload to return most specific vector type.
bool increasesLength() const
Return true if this shuffle returns a vector with a greater number of elements than its source vector...
LLVM_ABI bool isIdentityWithExtract() const
Return true if this shuffle extracts the first N elements of exactly one source vector.
static LLVM_ABI bool isSingleSourceMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector.
static LLVM_ABI void getShuffleMask(const Constant *Mask, SmallVectorImpl< int > &Result)
Convert the input shuffle mask operand to a vector of integers.
bool isSelect() const
Return true if this shuffle chooses elements from its source vectors without lane crossings and all o...
static LLVM_ABI bool isDeInterleaveMaskOfFactor(ArrayRef< int > Mask, unsigned Factor, unsigned &Index)
Check if the mask is a DE-interleave mask of the given factor Factor like: <Index,...
static LLVM_ABI bool isIdentityMask(ArrayRef< int > Mask, int NumSrcElts)
Return true if this shuffle mask chooses elements from exactly one source vector without lane crossin...
static void commuteShuffleMask(MutableArrayRef< int > Mask, unsigned InVecNumElts)
Change values in a shuffle permute mask assuming the two vector operands of length InVecNumElts have ...
LLVM_ABI void commute()
Swap the operands and adjust the mask to preserve the semantics of the instruction.
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
bool all() const
Returns true if all bits are set.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
reference emplace_back(ArgTypes &&... Args)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class represents a truncation of integer types.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
static LLVM_ABI IntegerType * getInt64Ty(LLVMContext &C)
Definition Type.cpp:310
bool isVectorTy() const
True if this is an instance of VectorType.
Definition Type.h:288
bool isIntOrIntVectorTy() const
Return true if this is an integer type or a vector of integer types.
Definition Type.h:263
LLVM_ABI unsigned getStructNumElements() const
LLVM_ABI uint64_t getArrayNumElements() const
@ ArrayTyID
Arrays.
Definition Type.h:76
@ StructTyID
Structures.
Definition Type.h:75
Type * getScalarType() const
If this is a vector type, return the element type, otherwise return 'this'.
Definition Type.h:368
LLVM_ABI TypeSize getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
Definition Type.cpp:197
LLVM_ABI unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type.
Definition Type.cpp:232
bool isFloatingPointTy() const
Return true if this is one of the floating-point types.
Definition Type.h:186
bool isIntegerTy() const
True if this is an instance of IntegerType.
Definition Type.h:257
TypeID getTypeID() const
Return the type id for the type.
Definition Type.h:138
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:313
static UnaryOperator * CreateWithCopiedFlags(UnaryOps Opc, Value *V, Instruction *CopyO, const Twine &Name="", InsertPosition InsertBefore=nullptr)
Definition InstrTypes.h:148
UnaryOps getOpcode() const
Definition InstrTypes.h:163
static LLVM_ABI UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
A Use represents the edge between a Value definition and its users.
Definition Use.h:35
Value * getOperand(unsigned i) const
Definition User.h:207
LLVM Value Representation.
Definition Value.h:75
Type * getType() const
All values are typed, get the type of this value.
Definition Value.h:255
LLVM_ABI const Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const
Translate PHI node to its predecessor from the given basic block.
Definition Value.cpp:1128
bool hasOneUse() const
Return true if there is exactly one use of this value.
Definition Value.h:439
LLVM_ABI void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition Value.cpp:553
LLVMContext & getContext() const
All values hold a context through their type.
Definition Value.h:258
iterator_range< user_iterator > users()
Definition Value.h:426
User * user_back()
Definition Value.h:412
iterator_range< use_iterator > uses()
Definition Value.h:380
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
Definition Value.cpp:319
static VectorType * getHalfElementsVectorType(VectorType *VTy)
This static method returns a VectorType with half as many elements as the input type and the same ele...
static VectorType * getExtendedElementVectorType(VectorType *VTy)
This static method is like getInteger except that the element types are twice as wide as the elements...
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
static LLVM_ABI VectorType * get(Type *ElementType, ElementCount EC)
This static method is the primary way to construct an VectorType.
static LLVM_ABI bool isValidElementType(Type *ElemTy)
Return true if the specified type is valid as a element type.
Type * getElementType() const
This class represents zero extension of integer types.
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:168
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:165
const ParentTy * getParent() const
Definition ilist_node.h:34
self_iterator getIterator()
Definition ilist_node.h:123
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
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.
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
@ BasicBlock
Various leaf nodes.
Definition ISDOpcodes.h:81
LLVM_ABI Function * getOrInsertDeclaration(Module *M, ID id, ArrayRef< Type * > OverloadTys={})
Look up the Function declaration of the intrinsic id in the Module M.
@ Bitcast
Perform the operation on a different, but equivalently sized type.
BinaryOpc_match< LHS, RHS, false > m_BinOp(unsigned Opcode, const LHS &L, const RHS &R)
SpecificConstantMatch m_ZeroInt()
Convenience matchers for specific integer values.
BinaryOp_match< SpecificConstantMatch, SrcTy, TargetOpcode::G_SUB > m_Neg(const SrcTy &&Src)
Matches a register negated by a G_SUB.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
match_combine_or< Ty... > m_CombineOr(const Ty &...Ps)
Combine pattern matchers matching any of Ps patterns.
auto m_Cmp()
Matches any compare instruction and ignore it.
auto m_Poison()
Match an arbitrary poison constant.
CastInst_match< OpTy, TruncInst > m_Trunc(const OpTy &Op)
Matches Trunc.
specific_intval< false > m_SpecificInt(const APInt &V)
Match a specific integer value or vector with all elements equal to the value.
bool match(Val *V, const Pattern &P)
match_bind< Instruction > m_Instruction(Instruction *&I)
Match an instruction, capturing it if we match.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
TwoOps_match< Val_t, Idx_t, Instruction::ExtractElement > m_ExtractElt(const Val_t &Val, const Idx_t &Idx)
Matches ExtractElementInst.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_BinOp()
Match an arbitrary binary operation and ignore it.
ExtractValue_match< Ind, Val_t > m_ExtractValue(const Val_t &V)
Match a single index ExtractValue instruction.
auto m_Value()
Match an arbitrary value and ignore it.
auto m_Constant()
Match an arbitrary Constant and ignore it.
TwoOps_match< V1_t, V2_t, Instruction::ShuffleVector > m_Shuffle(const V1_t &v1, const V2_t &v2)
Matches ShuffleVectorInst independently of mask value.
CastInst_match< OpTy, FPExtInst > m_FPExt(const OpTy &Op)
OneOps_match< OpTy, Instruction::Load > m_Load(const OpTy &Op)
Matches LoadInst.
CastInst_match< OpTy, ZExtInst > m_ZExt(const OpTy &Op)
Matches ZExt.
match_immconstant_ty m_ImmConstant()
Match an arbitrary immediate Constant and ignore it.
CastOperator_match< OpTy, Instruction::BitCast > m_BitCast(const OpTy &Op)
Matches BitCast.
auto m_Intrinsic(const Ts &...Ops)
Match intrinsic calls like this: m_Intrinsic<Intrinsic::fabs>(m_Value(X))
auto m_Deinterleave2(const Opnd &Op)
auto m_FAbs(const Opnd0 &Op0)
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
FNeg_match< OpTy > m_FNeg(const OpTy &X)
Match 'fneg X' as 'fsub -0.0, X'.
auto m_UnOp()
Match an arbitrary unary operation and ignore it.
auto m_Undef()
Match an arbitrary undef constant.
CastInst_match< OpTy, SExtInst > m_SExt(const OpTy &Op)
Matches SExt.
is_zero m_Zero()
Match any null constant or a vector with all elements equal to 0.
ThreeOps_match< Val_t, Elt_t, Idx_t, Instruction::InsertElement > m_InsertElt(const Val_t &Val, const Elt_t &Elt, const Idx_t &Idx)
Matches InsertElementInst.
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
Definition BasicBlock.h:73
This is an optimization pass for GlobalISel generic memory operations.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1739
LLVM_ABI bool isKnownNeverInfinity(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not an infinity or if the floating-point vector val...
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
auto enumerate(FirstRange &&First, RestRanges &&...Rest)
Given two or more input ranges, returns a new range whose values are tuples (A, B,...
Definition STLExtras.h:2554
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
LLVM_ABI 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 ...
LLVM_ABI Value * simplifyShuffleVectorInst(Value *Op0, Value *Op1, ArrayRef< int > Mask, Type *RetTy, const SimplifyQuery &Q)
Given operands for a ShuffleVectorInst, fold the result or return null.
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
Definition InstrProf.h:143
auto dyn_cast_or_null(const Y &Val)
Definition Casting.h:753
constexpr bool isPowerOf2_32(uint32_t Value)
Return true if the argument is a power of two > 0.
Definition MathExtras.h:280
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
Definition Casting.h:547
LLVM_ABI Value * simplifyInsertValueInst(Value *Agg, Value *Val, ArrayRef< unsigned > Idxs, const SimplifyQuery &Q)
Given operands for an InsertValueInst, fold the result or return null.
LLVM_ABI Constant * ConstantFoldBinaryOpOperands(unsigned Opcode, Constant *LHS, Constant *RHS, const DataLayout &DL)
Attempt to constant fold a binary operation with the specified operands.
constexpr int PoisonMaskElem
LLVM_ABI Value * findScalarElement(Value *V, unsigned EltNo)
Given a vector and an element number, see if the scalar value is already around as a register,...
DWARFExpression::Operation Op
bool isSafeToSpeculativelyExecuteWithVariableReplaced(const Instruction *I, bool IgnoreUBImplyingAttrs=true)
Don't use information from its non-constant operands.
LLVM_ABI Value * simplifyInsertElementInst(Value *Vec, Value *Elt, Value *Idx, const SimplifyQuery &Q)
Given operands for an InsertElement, fold the result or return null.
constexpr unsigned BitWidth
auto count_if(R &&Range, UnaryPredicate P)
Wrapper function around std::count_if to count the number of times an element satisfying a given pred...
Definition STLExtras.h:2019
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVM_ABI bool isKnownNeverNaN(const Value *V, const SimplifyQuery &SQ, unsigned Depth=0)
Return true if the floating-point scalar value is not a NaN or if the floating-point vector value has...
constexpr auto seq(T Begin, T End)
Iterate over an integral type from Begin up to - but not including - End.
Definition Sequence.h:341
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1947
bool pred_empty(const BasicBlock *BB)
Definition CFG.h:107
LLVM_ABI bool isGuaranteedNotToBePoison(const Value *V, AssumptionCache *AC=nullptr, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr, unsigned Depth=0)
Returns true if V cannot be poison, but may be undef.
LLVM_ABI Value * simplifyExtractElementInst(Value *Vec, Value *Idx, const SimplifyQuery &Q)
Given operands for an ExtractElementInst, fold the result or return null.
LLVM_ABI bool scaleShuffleMaskElts(unsigned NumDstElts, ArrayRef< int > Mask, SmallVectorImpl< int > &ScaledMask)
Attempt to narrow/widen the Mask shuffle mask to the NumDstElts target width.
LLVM_ABI int getSplatIndex(ArrayRef< int > Mask)
If all non-negative Mask elements are the same value, return that value.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition BitVector.h:880
These are the ingredients in an alternate form binary operator as described below.
BinopElts(BinaryOperator::BinaryOps Opc=(BinaryOperator::BinaryOps) 0, Value *V0=nullptr, Value *V1=nullptr)
BinaryOperator::BinaryOps Opcode
A MapVector that performs no allocations if smaller than a certain size.
Definition MapVector.h:342