xref: /freebsd-src/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineVectorOps.cpp (revision 0eae32dcef82f6f06de6419a0d623d7def0cc8f6)
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"
19 #include "llvm/ADT/SmallBitVector.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/VectorUtils.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/Constant.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/User.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Transforms/InstCombine/InstCombiner.h"
39 #include <cassert>
40 #include <cstdint>
41 #include <iterator>
42 #include <utility>
43 
44 #define DEBUG_TYPE "instcombine"
45 #include "llvm/Transforms/Utils/InstructionWorklist.h"
46 
47 using namespace llvm;
48 using namespace PatternMatch;
49 
50 STATISTIC(NumAggregateReconstructionsSimplified,
51           "Number of aggregate reconstructions turned into reuse of the "
52           "original aggregate");
53 
54 /// Return true if the value is cheaper to scalarize than it is to leave as a
55 /// vector operation. If the extract index \p EI is a constant integer then
56 /// some operations may be cheap to scalarize.
57 ///
58 /// FIXME: It's possible to create more instructions than previously existed.
59 static bool cheapToScalarize(Value *V, Value *EI) {
60   ConstantInt *CEI = dyn_cast<ConstantInt>(EI);
61 
62   // If we can pick a scalar constant value out of a vector, that is free.
63   if (auto *C = dyn_cast<Constant>(V))
64     return CEI || C->getSplatValue();
65 
66   if (CEI && match(V, m_Intrinsic<Intrinsic::experimental_stepvector>())) {
67     ElementCount EC = cast<VectorType>(V->getType())->getElementCount();
68     // Index needs to be lower than the minimum size of the vector, because
69     // for scalable vector, the vector size is known at run time.
70     return CEI->getValue().ult(EC.getKnownMinValue());
71   }
72 
73   // An insertelement to the same constant index as our extract will simplify
74   // to the scalar inserted element. An insertelement to a different constant
75   // index is irrelevant to our extract.
76   if (match(V, m_InsertElt(m_Value(), m_Value(), m_ConstantInt())))
77     return CEI;
78 
79   if (match(V, m_OneUse(m_Load(m_Value()))))
80     return true;
81 
82   if (match(V, m_OneUse(m_UnOp())))
83     return true;
84 
85   Value *V0, *V1;
86   if (match(V, m_OneUse(m_BinOp(m_Value(V0), m_Value(V1)))))
87     if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
88       return true;
89 
90   CmpInst::Predicate UnusedPred;
91   if (match(V, m_OneUse(m_Cmp(UnusedPred, m_Value(V0), m_Value(V1)))))
92     if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
93       return true;
94 
95   return false;
96 }
97 
98 // If we have a PHI node with a vector type that is only used to feed
99 // itself and be an operand of extractelement at a constant location,
100 // try to replace the PHI of the vector type with a PHI of a scalar type.
101 Instruction *InstCombinerImpl::scalarizePHI(ExtractElementInst &EI,
102                                             PHINode *PN) {
103   SmallVector<Instruction *, 2> Extracts;
104   // The users we want the PHI to have are:
105   // 1) The EI ExtractElement (we already know this)
106   // 2) Possibly more ExtractElements with the same index.
107   // 3) Another operand, which will feed back into the PHI.
108   Instruction *PHIUser = nullptr;
109   for (auto U : PN->users()) {
110     if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
111       if (EI.getIndexOperand() == EU->getIndexOperand())
112         Extracts.push_back(EU);
113       else
114         return nullptr;
115     } else if (!PHIUser) {
116       PHIUser = cast<Instruction>(U);
117     } else {
118       return nullptr;
119     }
120   }
121 
122   if (!PHIUser)
123     return nullptr;
124 
125   // Verify that this PHI user has one use, which is the PHI itself,
126   // and that it is a binary operation which is cheap to scalarize.
127   // otherwise return nullptr.
128   if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
129       !(isa<BinaryOperator>(PHIUser)) ||
130       !cheapToScalarize(PHIUser, EI.getIndexOperand()))
131     return nullptr;
132 
133   // Create a scalar PHI node that will replace the vector PHI node
134   // just before the current PHI node.
135   PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
136       PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
137   // Scalarize each PHI operand.
138   for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
139     Value *PHIInVal = PN->getIncomingValue(i);
140     BasicBlock *inBB = PN->getIncomingBlock(i);
141     Value *Elt = EI.getIndexOperand();
142     // If the operand is the PHI induction variable:
143     if (PHIInVal == PHIUser) {
144       // Scalarize the binary operation. Its first operand is the
145       // scalar PHI, and the second operand is extracted from the other
146       // vector operand.
147       BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
148       unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
149       Value *Op = InsertNewInstWith(
150           ExtractElementInst::Create(B0->getOperand(opId), Elt,
151                                      B0->getOperand(opId)->getName() + ".Elt"),
152           *B0);
153       Value *newPHIUser = InsertNewInstWith(
154           BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
155                                                 scalarPHI, Op, B0), *B0);
156       scalarPHI->addIncoming(newPHIUser, inBB);
157     } else {
158       // Scalarize PHI input:
159       Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
160       // Insert the new instruction into the predecessor basic block.
161       Instruction *pos = dyn_cast<Instruction>(PHIInVal);
162       BasicBlock::iterator InsertPos;
163       if (pos && !isa<PHINode>(pos)) {
164         InsertPos = ++pos->getIterator();
165       } else {
166         InsertPos = inBB->getFirstInsertionPt();
167       }
168 
169       InsertNewInstWith(newEI, *InsertPos);
170 
171       scalarPHI->addIncoming(newEI, inBB);
172     }
173   }
174 
175   for (auto E : Extracts)
176     replaceInstUsesWith(*E, scalarPHI);
177 
178   return &EI;
179 }
180 
181 Instruction *InstCombinerImpl::foldBitcastExtElt(ExtractElementInst &Ext) {
182   Value *X;
183   uint64_t ExtIndexC;
184   if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) ||
185       !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC)))
186     return nullptr;
187 
188   ElementCount NumElts =
189       cast<VectorType>(Ext.getVectorOperandType())->getElementCount();
190   Type *DestTy = Ext.getType();
191   bool IsBigEndian = DL.isBigEndian();
192 
193   // If we are casting an integer to vector and extracting a portion, that is
194   // a shift-right and truncate.
195   // TODO: Allow FP dest type by casting the trunc to FP?
196   if (X->getType()->isIntegerTy() && DestTy->isIntegerTy() &&
197       isDesirableIntType(X->getType()->getPrimitiveSizeInBits())) {
198     assert(isa<FixedVectorType>(Ext.getVectorOperand()->getType()) &&
199            "Expected fixed vector type for bitcast from scalar integer");
200 
201     // Big endian requires adjusting the extract index since MSB is at index 0.
202     // LittleEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 X to i8
203     // BigEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 (X >> 24) to i8
204     if (IsBigEndian)
205       ExtIndexC = NumElts.getKnownMinValue() - 1 - ExtIndexC;
206     unsigned ShiftAmountC = ExtIndexC * DestTy->getPrimitiveSizeInBits();
207     if (!ShiftAmountC || Ext.getVectorOperand()->hasOneUse()) {
208       Value *Lshr = Builder.CreateLShr(X, ShiftAmountC, "extelt.offset");
209       return new TruncInst(Lshr, DestTy);
210     }
211   }
212 
213   if (!X->getType()->isVectorTy())
214     return nullptr;
215 
216   // If this extractelement is using a bitcast from a vector of the same number
217   // of elements, see if we can find the source element from the source vector:
218   // extelt (bitcast VecX), IndexC --> bitcast X[IndexC]
219   auto *SrcTy = cast<VectorType>(X->getType());
220   ElementCount NumSrcElts = SrcTy->getElementCount();
221   if (NumSrcElts == NumElts)
222     if (Value *Elt = findScalarElement(X, ExtIndexC))
223       return new BitCastInst(Elt, DestTy);
224 
225   assert(NumSrcElts.isScalable() == NumElts.isScalable() &&
226          "Src and Dst must be the same sort of vector type");
227 
228   // If the source elements are wider than the destination, try to shift and
229   // truncate a subset of scalar bits of an insert op.
230   if (NumSrcElts.getKnownMinValue() < NumElts.getKnownMinValue()) {
231     Value *Scalar;
232     uint64_t InsIndexC;
233     if (!match(X, m_InsertElt(m_Value(), m_Value(Scalar),
234                               m_ConstantInt(InsIndexC))))
235       return nullptr;
236 
237     // The extract must be from the subset of vector elements that we inserted
238     // into. Example: if we inserted element 1 of a <2 x i64> and we are
239     // extracting an i16 (narrowing ratio = 4), then this extract must be from 1
240     // of elements 4-7 of the bitcasted vector.
241     unsigned NarrowingRatio =
242         NumElts.getKnownMinValue() / NumSrcElts.getKnownMinValue();
243     if (ExtIndexC / NarrowingRatio != InsIndexC)
244       return nullptr;
245 
246     // We are extracting part of the original scalar. How that scalar is
247     // inserted into the vector depends on the endian-ness. Example:
248     //              Vector Byte Elt Index:    0  1  2  3  4  5  6  7
249     //                                       +--+--+--+--+--+--+--+--+
250     // inselt <2 x i32> V, <i32> S, 1:       |V0|V1|V2|V3|S0|S1|S2|S3|
251     // extelt <4 x i16> V', 3:               |                 |S2|S3|
252     //                                       +--+--+--+--+--+--+--+--+
253     // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value.
254     // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value.
255     // In this example, we must right-shift little-endian. Big-endian is just a
256     // truncate.
257     unsigned Chunk = ExtIndexC % NarrowingRatio;
258     if (IsBigEndian)
259       Chunk = NarrowingRatio - 1 - Chunk;
260 
261     // Bail out if this is an FP vector to FP vector sequence. That would take
262     // more instructions than we started with unless there is no shift, and it
263     // may not be handled as well in the backend.
264     bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy();
265     bool NeedDestBitcast = DestTy->isFloatingPointTy();
266     if (NeedSrcBitcast && NeedDestBitcast)
267       return nullptr;
268 
269     unsigned SrcWidth = SrcTy->getScalarSizeInBits();
270     unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
271     unsigned ShAmt = Chunk * DestWidth;
272 
273     // TODO: This limitation is more strict than necessary. We could sum the
274     // number of new instructions and subtract the number eliminated to know if
275     // we can proceed.
276     if (!X->hasOneUse() || !Ext.getVectorOperand()->hasOneUse())
277       if (NeedSrcBitcast || NeedDestBitcast)
278         return nullptr;
279 
280     if (NeedSrcBitcast) {
281       Type *SrcIntTy = IntegerType::getIntNTy(Scalar->getContext(), SrcWidth);
282       Scalar = Builder.CreateBitCast(Scalar, SrcIntTy);
283     }
284 
285     if (ShAmt) {
286       // Bail out if we could end with more instructions than we started with.
287       if (!Ext.getVectorOperand()->hasOneUse())
288         return nullptr;
289       Scalar = Builder.CreateLShr(Scalar, ShAmt);
290     }
291 
292     if (NeedDestBitcast) {
293       Type *DestIntTy = IntegerType::getIntNTy(Scalar->getContext(), DestWidth);
294       return new BitCastInst(Builder.CreateTrunc(Scalar, DestIntTy), DestTy);
295     }
296     return new TruncInst(Scalar, DestTy);
297   }
298 
299   return nullptr;
300 }
301 
302 /// Find elements of V demanded by UserInstr.
303 static APInt findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr) {
304   unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
305 
306   // Conservatively assume that all elements are needed.
307   APInt UsedElts(APInt::getAllOnes(VWidth));
308 
309   switch (UserInstr->getOpcode()) {
310   case Instruction::ExtractElement: {
311     ExtractElementInst *EEI = cast<ExtractElementInst>(UserInstr);
312     assert(EEI->getVectorOperand() == V);
313     ConstantInt *EEIIndexC = dyn_cast<ConstantInt>(EEI->getIndexOperand());
314     if (EEIIndexC && EEIIndexC->getValue().ult(VWidth)) {
315       UsedElts = APInt::getOneBitSet(VWidth, EEIIndexC->getZExtValue());
316     }
317     break;
318   }
319   case Instruction::ShuffleVector: {
320     ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(UserInstr);
321     unsigned MaskNumElts =
322         cast<FixedVectorType>(UserInstr->getType())->getNumElements();
323 
324     UsedElts = APInt(VWidth, 0);
325     for (unsigned i = 0; i < MaskNumElts; i++) {
326       unsigned MaskVal = Shuffle->getMaskValue(i);
327       if (MaskVal == -1u || MaskVal >= 2 * VWidth)
328         continue;
329       if (Shuffle->getOperand(0) == V && (MaskVal < VWidth))
330         UsedElts.setBit(MaskVal);
331       if (Shuffle->getOperand(1) == V &&
332           ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth)))
333         UsedElts.setBit(MaskVal - VWidth);
334     }
335     break;
336   }
337   default:
338     break;
339   }
340   return UsedElts;
341 }
342 
343 /// Find union of elements of V demanded by all its users.
344 /// If it is known by querying findDemandedEltsBySingleUser that
345 /// no user demands an element of V, then the corresponding bit
346 /// remains unset in the returned value.
347 static APInt findDemandedEltsByAllUsers(Value *V) {
348   unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
349 
350   APInt UnionUsedElts(VWidth, 0);
351   for (const Use &U : V->uses()) {
352     if (Instruction *I = dyn_cast<Instruction>(U.getUser())) {
353       UnionUsedElts |= findDemandedEltsBySingleUser(V, I);
354     } else {
355       UnionUsedElts = APInt::getAllOnes(VWidth);
356       break;
357     }
358 
359     if (UnionUsedElts.isAllOnes())
360       break;
361   }
362 
363   return UnionUsedElts;
364 }
365 
366 /// Given a constant index for a extractelement or insertelement instruction,
367 /// return it with the canonical type if it isn't already canonical.  We
368 /// arbitrarily pick 64 bit as our canonical type.  The actual bitwidth doesn't
369 /// matter, we just want a consistent type to simplify CSE.
370 ConstantInt *getPreferredVectorIndex(ConstantInt *IndexC) {
371   const unsigned IndexBW = IndexC->getType()->getBitWidth();
372   if (IndexBW == 64 || IndexC->getValue().getActiveBits() > 64)
373     return nullptr;
374   return ConstantInt::get(IndexC->getContext(),
375                           IndexC->getValue().zextOrTrunc(64));
376 }
377 
378 Instruction *InstCombinerImpl::visitExtractElementInst(ExtractElementInst &EI) {
379   Value *SrcVec = EI.getVectorOperand();
380   Value *Index = EI.getIndexOperand();
381   if (Value *V = SimplifyExtractElementInst(SrcVec, Index,
382                                             SQ.getWithInstruction(&EI)))
383     return replaceInstUsesWith(EI, V);
384 
385   // If extracting a specified index from the vector, see if we can recursively
386   // find a previously computed scalar that was inserted into the vector.
387   auto *IndexC = dyn_cast<ConstantInt>(Index);
388   if (IndexC) {
389     // Canonicalize type of constant indices to i64 to simplify CSE
390     if (auto *NewIdx = getPreferredVectorIndex(IndexC))
391       return replaceOperand(EI, 1, NewIdx);
392 
393     ElementCount EC = EI.getVectorOperandType()->getElementCount();
394     unsigned NumElts = EC.getKnownMinValue();
395 
396     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(SrcVec)) {
397       Intrinsic::ID IID = II->getIntrinsicID();
398       // Index needs to be lower than the minimum size of the vector, because
399       // for scalable vector, the vector size is known at run time.
400       if (IID == Intrinsic::experimental_stepvector &&
401           IndexC->getValue().ult(NumElts)) {
402         Type *Ty = EI.getType();
403         unsigned BitWidth = Ty->getIntegerBitWidth();
404         Value *Idx;
405         // Return index when its value does not exceed the allowed limit
406         // for the element type of the vector, otherwise return undefined.
407         if (IndexC->getValue().getActiveBits() <= BitWidth)
408           Idx = ConstantInt::get(Ty, IndexC->getValue().zextOrTrunc(BitWidth));
409         else
410           Idx = UndefValue::get(Ty);
411         return replaceInstUsesWith(EI, Idx);
412       }
413     }
414 
415     // InstSimplify should handle cases where the index is invalid.
416     // For fixed-length vector, it's invalid to extract out-of-range element.
417     if (!EC.isScalable() && IndexC->getValue().uge(NumElts))
418       return nullptr;
419 
420     if (Instruction *I = foldBitcastExtElt(EI))
421       return I;
422 
423     // If there's a vector PHI feeding a scalar use through this extractelement
424     // instruction, try to scalarize the PHI.
425     if (auto *Phi = dyn_cast<PHINode>(SrcVec))
426       if (Instruction *ScalarPHI = scalarizePHI(EI, Phi))
427         return ScalarPHI;
428   }
429 
430   // TODO come up with a n-ary matcher that subsumes both unary and
431   // binary matchers.
432   UnaryOperator *UO;
433   if (match(SrcVec, m_UnOp(UO)) && cheapToScalarize(SrcVec, Index)) {
434     // extelt (unop X), Index --> unop (extelt X, Index)
435     Value *X = UO->getOperand(0);
436     Value *E = Builder.CreateExtractElement(X, Index);
437     return UnaryOperator::CreateWithCopiedFlags(UO->getOpcode(), E, UO);
438   }
439 
440   BinaryOperator *BO;
441   if (match(SrcVec, m_BinOp(BO)) && cheapToScalarize(SrcVec, Index)) {
442     // extelt (binop X, Y), Index --> binop (extelt X, Index), (extelt Y, Index)
443     Value *X = BO->getOperand(0), *Y = BO->getOperand(1);
444     Value *E0 = Builder.CreateExtractElement(X, Index);
445     Value *E1 = Builder.CreateExtractElement(Y, Index);
446     return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), E0, E1, BO);
447   }
448 
449   Value *X, *Y;
450   CmpInst::Predicate Pred;
451   if (match(SrcVec, m_Cmp(Pred, m_Value(X), m_Value(Y))) &&
452       cheapToScalarize(SrcVec, Index)) {
453     // extelt (cmp X, Y), Index --> cmp (extelt X, Index), (extelt Y, Index)
454     Value *E0 = Builder.CreateExtractElement(X, Index);
455     Value *E1 = Builder.CreateExtractElement(Y, Index);
456     return CmpInst::Create(cast<CmpInst>(SrcVec)->getOpcode(), Pred, E0, E1);
457   }
458 
459   if (auto *I = dyn_cast<Instruction>(SrcVec)) {
460     if (auto *IE = dyn_cast<InsertElementInst>(I)) {
461       // instsimplify already handled the case where the indices are constants
462       // and equal by value, if both are constants, they must not be the same
463       // value, extract from the pre-inserted value instead.
464       if (isa<Constant>(IE->getOperand(2)) && IndexC)
465         return replaceOperand(EI, 0, IE->getOperand(0));
466     } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
467       auto *VecType = cast<VectorType>(GEP->getType());
468       ElementCount EC = VecType->getElementCount();
469       uint64_t IdxVal = IndexC ? IndexC->getZExtValue() : 0;
470       if (IndexC && IdxVal < EC.getKnownMinValue() && GEP->hasOneUse()) {
471         // Find out why we have a vector result - these are a few examples:
472         //  1. We have a scalar pointer and a vector of indices, or
473         //  2. We have a vector of pointers and a scalar index, or
474         //  3. We have a vector of pointers and a vector of indices, etc.
475         // Here we only consider combining when there is exactly one vector
476         // operand, since the optimization is less obviously a win due to
477         // needing more than one extractelements.
478 
479         unsigned VectorOps =
480             llvm::count_if(GEP->operands(), [](const Value *V) {
481               return isa<VectorType>(V->getType());
482             });
483         if (VectorOps == 1) {
484           Value *NewPtr = GEP->getPointerOperand();
485           if (isa<VectorType>(NewPtr->getType()))
486             NewPtr = Builder.CreateExtractElement(NewPtr, IndexC);
487 
488           SmallVector<Value *> NewOps;
489           for (unsigned I = 1; I != GEP->getNumOperands(); ++I) {
490             Value *Op = GEP->getOperand(I);
491             if (isa<VectorType>(Op->getType()))
492               NewOps.push_back(Builder.CreateExtractElement(Op, IndexC));
493             else
494               NewOps.push_back(Op);
495           }
496 
497           GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
498               cast<PointerType>(NewPtr->getType())->getElementType(), NewPtr,
499               NewOps);
500           NewGEP->setIsInBounds(GEP->isInBounds());
501           return NewGEP;
502         }
503       }
504     } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
505       // If this is extracting an element from a shufflevector, figure out where
506       // it came from and extract from the appropriate input element instead.
507       // Restrict the following transformation to fixed-length vector.
508       if (isa<FixedVectorType>(SVI->getType()) && isa<ConstantInt>(Index)) {
509         int SrcIdx =
510             SVI->getMaskValue(cast<ConstantInt>(Index)->getZExtValue());
511         Value *Src;
512         unsigned LHSWidth = cast<FixedVectorType>(SVI->getOperand(0)->getType())
513                                 ->getNumElements();
514 
515         if (SrcIdx < 0)
516           return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
517         if (SrcIdx < (int)LHSWidth)
518           Src = SVI->getOperand(0);
519         else {
520           SrcIdx -= LHSWidth;
521           Src = SVI->getOperand(1);
522         }
523         Type *Int32Ty = Type::getInt32Ty(EI.getContext());
524         return ExtractElementInst::Create(
525             Src, ConstantInt::get(Int32Ty, SrcIdx, false));
526       }
527     } else if (auto *CI = dyn_cast<CastInst>(I)) {
528       // Canonicalize extractelement(cast) -> cast(extractelement).
529       // Bitcasts can change the number of vector elements, and they cost
530       // nothing.
531       if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
532         Value *EE = Builder.CreateExtractElement(CI->getOperand(0), Index);
533         return CastInst::Create(CI->getOpcode(), EE, EI.getType());
534       }
535     }
536   }
537 
538   // Run demanded elements after other transforms as this can drop flags on
539   // binops.  If there's two paths to the same final result, we prefer the
540   // one which doesn't force us to drop flags.
541   if (IndexC) {
542     ElementCount EC = EI.getVectorOperandType()->getElementCount();
543     unsigned NumElts = EC.getKnownMinValue();
544     // This instruction only demands the single element from the input vector.
545     // Skip for scalable type, the number of elements is unknown at
546     // compile-time.
547     if (!EC.isScalable() && NumElts != 1) {
548       // If the input vector has a single use, simplify it based on this use
549       // property.
550       if (SrcVec->hasOneUse()) {
551         APInt UndefElts(NumElts, 0);
552         APInt DemandedElts(NumElts, 0);
553         DemandedElts.setBit(IndexC->getZExtValue());
554         if (Value *V =
555                 SimplifyDemandedVectorElts(SrcVec, DemandedElts, UndefElts))
556           return replaceOperand(EI, 0, V);
557       } else {
558         // If the input vector has multiple uses, simplify it based on a union
559         // of all elements used.
560         APInt DemandedElts = findDemandedEltsByAllUsers(SrcVec);
561         if (!DemandedElts.isAllOnes()) {
562           APInt UndefElts(NumElts, 0);
563           if (Value *V = SimplifyDemandedVectorElts(
564                   SrcVec, DemandedElts, UndefElts, 0 /* Depth */,
565                   true /* AllowMultipleUsers */)) {
566             if (V != SrcVec) {
567               SrcVec->replaceAllUsesWith(V);
568               return &EI;
569             }
570           }
571         }
572       }
573     }
574   }
575   return nullptr;
576 }
577 
578 /// If V is a shuffle of values that ONLY returns elements from either LHS or
579 /// RHS, return the shuffle mask and true. Otherwise, return false.
580 static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
581                                          SmallVectorImpl<int> &Mask) {
582   assert(LHS->getType() == RHS->getType() &&
583          "Invalid CollectSingleShuffleElements");
584   unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
585 
586   if (match(V, m_Undef())) {
587     Mask.assign(NumElts, -1);
588     return true;
589   }
590 
591   if (V == LHS) {
592     for (unsigned i = 0; i != NumElts; ++i)
593       Mask.push_back(i);
594     return true;
595   }
596 
597   if (V == RHS) {
598     for (unsigned i = 0; i != NumElts; ++i)
599       Mask.push_back(i + NumElts);
600     return true;
601   }
602 
603   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
604     // If this is an insert of an extract from some other vector, include it.
605     Value *VecOp    = IEI->getOperand(0);
606     Value *ScalarOp = IEI->getOperand(1);
607     Value *IdxOp    = IEI->getOperand(2);
608 
609     if (!isa<ConstantInt>(IdxOp))
610       return false;
611     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
612 
613     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
614       // We can handle this if the vector we are inserting into is
615       // transitively ok.
616       if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
617         // If so, update the mask to reflect the inserted undef.
618         Mask[InsertedIdx] = -1;
619         return true;
620       }
621     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
622       if (isa<ConstantInt>(EI->getOperand(1))) {
623         unsigned ExtractedIdx =
624         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
625         unsigned NumLHSElts =
626             cast<FixedVectorType>(LHS->getType())->getNumElements();
627 
628         // This must be extracting from either LHS or RHS.
629         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
630           // We can handle this if the vector we are inserting into is
631           // transitively ok.
632           if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
633             // If so, update the mask to reflect the inserted value.
634             if (EI->getOperand(0) == LHS) {
635               Mask[InsertedIdx % NumElts] = ExtractedIdx;
636             } else {
637               assert(EI->getOperand(0) == RHS);
638               Mask[InsertedIdx % NumElts] = ExtractedIdx + NumLHSElts;
639             }
640             return true;
641           }
642         }
643       }
644     }
645   }
646 
647   return false;
648 }
649 
650 /// If we have insertion into a vector that is wider than the vector that we
651 /// are extracting from, try to widen the source vector to allow a single
652 /// shufflevector to replace one or more insert/extract pairs.
653 static void replaceExtractElements(InsertElementInst *InsElt,
654                                    ExtractElementInst *ExtElt,
655                                    InstCombinerImpl &IC) {
656   auto *InsVecType = cast<FixedVectorType>(InsElt->getType());
657   auto *ExtVecType = cast<FixedVectorType>(ExtElt->getVectorOperandType());
658   unsigned NumInsElts = InsVecType->getNumElements();
659   unsigned NumExtElts = ExtVecType->getNumElements();
660 
661   // The inserted-to vector must be wider than the extracted-from vector.
662   if (InsVecType->getElementType() != ExtVecType->getElementType() ||
663       NumExtElts >= NumInsElts)
664     return;
665 
666   // Create a shuffle mask to widen the extended-from vector using poison
667   // values. The mask selects all of the values of the original vector followed
668   // by as many poison values as needed to create a vector of the same length
669   // as the inserted-to vector.
670   SmallVector<int, 16> ExtendMask;
671   for (unsigned i = 0; i < NumExtElts; ++i)
672     ExtendMask.push_back(i);
673   for (unsigned i = NumExtElts; i < NumInsElts; ++i)
674     ExtendMask.push_back(-1);
675 
676   Value *ExtVecOp = ExtElt->getVectorOperand();
677   auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
678   BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
679                                    ? ExtVecOpInst->getParent()
680                                    : ExtElt->getParent();
681 
682   // TODO: This restriction matches the basic block check below when creating
683   // new extractelement instructions. If that limitation is removed, this one
684   // could also be removed. But for now, we just bail out to ensure that we
685   // will replace the extractelement instruction that is feeding our
686   // insertelement instruction. This allows the insertelement to then be
687   // replaced by a shufflevector. If the insertelement is not replaced, we can
688   // induce infinite looping because there's an optimization for extractelement
689   // that will delete our widening shuffle. This would trigger another attempt
690   // here to create that shuffle, and we spin forever.
691   if (InsertionBlock != InsElt->getParent())
692     return;
693 
694   // TODO: This restriction matches the check in visitInsertElementInst() and
695   // prevents an infinite loop caused by not turning the extract/insert pair
696   // into a shuffle. We really should not need either check, but we're lacking
697   // folds for shufflevectors because we're afraid to generate shuffle masks
698   // that the backend can't handle.
699   if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
700     return;
701 
702   auto *WideVec = new ShuffleVectorInst(ExtVecOp, ExtendMask);
703 
704   // Insert the new shuffle after the vector operand of the extract is defined
705   // (as long as it's not a PHI) or at the start of the basic block of the
706   // extract, so any subsequent extracts in the same basic block can use it.
707   // TODO: Insert before the earliest ExtractElementInst that is replaced.
708   if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
709     WideVec->insertAfter(ExtVecOpInst);
710   else
711     IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
712 
713   // Replace extracts from the original narrow vector with extracts from the new
714   // wide vector.
715   for (User *U : ExtVecOp->users()) {
716     ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
717     if (!OldExt || OldExt->getParent() != WideVec->getParent())
718       continue;
719     auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
720     NewExt->insertAfter(OldExt);
721     IC.replaceInstUsesWith(*OldExt, NewExt);
722   }
723 }
724 
725 /// We are building a shuffle to create V, which is a sequence of insertelement,
726 /// extractelement pairs. If PermittedRHS is set, then we must either use it or
727 /// not rely on the second vector source. Return a std::pair containing the
728 /// left and right vectors of the proposed shuffle (or 0), and set the Mask
729 /// parameter as required.
730 ///
731 /// Note: we intentionally don't try to fold earlier shuffles since they have
732 /// often been chosen carefully to be efficiently implementable on the target.
733 using ShuffleOps = std::pair<Value *, Value *>;
734 
735 static ShuffleOps collectShuffleElements(Value *V, SmallVectorImpl<int> &Mask,
736                                          Value *PermittedRHS,
737                                          InstCombinerImpl &IC) {
738   assert(V->getType()->isVectorTy() && "Invalid shuffle!");
739   unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
740 
741   if (match(V, m_Undef())) {
742     Mask.assign(NumElts, -1);
743     return std::make_pair(
744         PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
745   }
746 
747   if (isa<ConstantAggregateZero>(V)) {
748     Mask.assign(NumElts, 0);
749     return std::make_pair(V, nullptr);
750   }
751 
752   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
753     // If this is an insert of an extract from some other vector, include it.
754     Value *VecOp    = IEI->getOperand(0);
755     Value *ScalarOp = IEI->getOperand(1);
756     Value *IdxOp    = IEI->getOperand(2);
757 
758     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
759       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
760         unsigned ExtractedIdx =
761           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
762         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
763 
764         // Either the extracted from or inserted into vector must be RHSVec,
765         // otherwise we'd end up with a shuffle of three inputs.
766         if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
767           Value *RHS = EI->getOperand(0);
768           ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
769           assert(LR.second == nullptr || LR.second == RHS);
770 
771           if (LR.first->getType() != RHS->getType()) {
772             // Although we are giving up for now, see if we can create extracts
773             // that match the inserts for another round of combining.
774             replaceExtractElements(IEI, EI, IC);
775 
776             // We tried our best, but we can't find anything compatible with RHS
777             // further up the chain. Return a trivial shuffle.
778             for (unsigned i = 0; i < NumElts; ++i)
779               Mask[i] = i;
780             return std::make_pair(V, nullptr);
781           }
782 
783           unsigned NumLHSElts =
784               cast<FixedVectorType>(RHS->getType())->getNumElements();
785           Mask[InsertedIdx % NumElts] = NumLHSElts + ExtractedIdx;
786           return std::make_pair(LR.first, RHS);
787         }
788 
789         if (VecOp == PermittedRHS) {
790           // We've gone as far as we can: anything on the other side of the
791           // extractelement will already have been converted into a shuffle.
792           unsigned NumLHSElts =
793               cast<FixedVectorType>(EI->getOperand(0)->getType())
794                   ->getNumElements();
795           for (unsigned i = 0; i != NumElts; ++i)
796             Mask.push_back(i == InsertedIdx ? ExtractedIdx : NumLHSElts + i);
797           return std::make_pair(EI->getOperand(0), PermittedRHS);
798         }
799 
800         // If this insertelement is a chain that comes from exactly these two
801         // vectors, return the vector and the effective shuffle.
802         if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
803             collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
804                                          Mask))
805           return std::make_pair(EI->getOperand(0), PermittedRHS);
806       }
807     }
808   }
809 
810   // Otherwise, we can't do anything fancy. Return an identity vector.
811   for (unsigned i = 0; i != NumElts; ++i)
812     Mask.push_back(i);
813   return std::make_pair(V, nullptr);
814 }
815 
816 /// Look for chain of insertvalue's that fully define an aggregate, and trace
817 /// back the values inserted, see if they are all were extractvalue'd from
818 /// the same source aggregate from the exact same element indexes.
819 /// If they were, just reuse the source aggregate.
820 /// This potentially deals with PHI indirections.
821 Instruction *InstCombinerImpl::foldAggregateConstructionIntoAggregateReuse(
822     InsertValueInst &OrigIVI) {
823   Type *AggTy = OrigIVI.getType();
824   unsigned NumAggElts;
825   switch (AggTy->getTypeID()) {
826   case Type::StructTyID:
827     NumAggElts = AggTy->getStructNumElements();
828     break;
829   case Type::ArrayTyID:
830     NumAggElts = AggTy->getArrayNumElements();
831     break;
832   default:
833     llvm_unreachable("Unhandled aggregate type?");
834   }
835 
836   // Arbitrary aggregate size cut-off. Motivation for limit of 2 is to be able
837   // to handle clang C++ exception struct (which is hardcoded as {i8*, i32}),
838   // FIXME: any interesting patterns to be caught with larger limit?
839   assert(NumAggElts > 0 && "Aggregate should have elements.");
840   if (NumAggElts > 2)
841     return nullptr;
842 
843   static constexpr auto NotFound = None;
844   static constexpr auto FoundMismatch = nullptr;
845 
846   // Try to find a value of each element of an aggregate.
847   // FIXME: deal with more complex, not one-dimensional, aggregate types
848   SmallVector<Optional<Instruction *>, 2> AggElts(NumAggElts, NotFound);
849 
850   // Do we know values for each element of the aggregate?
851   auto KnowAllElts = [&AggElts]() {
852     return all_of(AggElts,
853                   [](Optional<Instruction *> Elt) { return Elt != NotFound; });
854   };
855 
856   int Depth = 0;
857 
858   // Arbitrary `insertvalue` visitation depth limit. Let's be okay with
859   // every element being overwritten twice, which should never happen.
860   static const int DepthLimit = 2 * NumAggElts;
861 
862   // Recurse up the chain of `insertvalue` aggregate operands until either we've
863   // reconstructed full initializer or can't visit any more `insertvalue`'s.
864   for (InsertValueInst *CurrIVI = &OrigIVI;
865        Depth < DepthLimit && CurrIVI && !KnowAllElts();
866        CurrIVI = dyn_cast<InsertValueInst>(CurrIVI->getAggregateOperand()),
867                        ++Depth) {
868     auto *InsertedValue =
869         dyn_cast<Instruction>(CurrIVI->getInsertedValueOperand());
870     if (!InsertedValue)
871       return nullptr; // Inserted value must be produced by an instruction.
872 
873     ArrayRef<unsigned int> Indices = CurrIVI->getIndices();
874 
875     // Don't bother with more than single-level aggregates.
876     if (Indices.size() != 1)
877       return nullptr; // FIXME: deal with more complex aggregates?
878 
879     // Now, we may have already previously recorded the value for this element
880     // of an aggregate. If we did, that means the CurrIVI will later be
881     // overwritten with the already-recorded value. But if not, let's record it!
882     Optional<Instruction *> &Elt = AggElts[Indices.front()];
883     Elt = Elt.getValueOr(InsertedValue);
884 
885     // FIXME: should we handle chain-terminating undef base operand?
886   }
887 
888   // Was that sufficient to deduce the full initializer for the aggregate?
889   if (!KnowAllElts())
890     return nullptr; // Give up then.
891 
892   // We now want to find the source[s] of the aggregate elements we've found.
893   // And with "source" we mean the original aggregate[s] from which
894   // the inserted elements were extracted. This may require PHI translation.
895 
896   enum class AggregateDescription {
897     /// When analyzing the value that was inserted into an aggregate, we did
898     /// not manage to find defining `extractvalue` instruction to analyze.
899     NotFound,
900     /// When analyzing the value that was inserted into an aggregate, we did
901     /// manage to find defining `extractvalue` instruction[s], and everything
902     /// matched perfectly - aggregate type, element insertion/extraction index.
903     Found,
904     /// When analyzing the value that was inserted into an aggregate, we did
905     /// manage to find defining `extractvalue` instruction, but there was
906     /// a mismatch: either the source type from which the extraction was didn't
907     /// match the aggregate type into which the insertion was,
908     /// or the extraction/insertion channels mismatched,
909     /// or different elements had different source aggregates.
910     FoundMismatch
911   };
912   auto Describe = [](Optional<Value *> SourceAggregate) {
913     if (SourceAggregate == NotFound)
914       return AggregateDescription::NotFound;
915     if (*SourceAggregate == FoundMismatch)
916       return AggregateDescription::FoundMismatch;
917     return AggregateDescription::Found;
918   };
919 
920   // Given the value \p Elt that was being inserted into element \p EltIdx of an
921   // aggregate AggTy, see if \p Elt was originally defined by an
922   // appropriate extractvalue (same element index, same aggregate type).
923   // If found, return the source aggregate from which the extraction was.
924   // If \p PredBB is provided, does PHI translation of an \p Elt first.
925   auto FindSourceAggregate =
926       [&](Instruction *Elt, unsigned EltIdx, Optional<BasicBlock *> UseBB,
927           Optional<BasicBlock *> PredBB) -> Optional<Value *> {
928     // For now(?), only deal with, at most, a single level of PHI indirection.
929     if (UseBB && PredBB)
930       Elt = dyn_cast<Instruction>(Elt->DoPHITranslation(*UseBB, *PredBB));
931     // FIXME: deal with multiple levels of PHI indirection?
932 
933     // Did we find an extraction?
934     auto *EVI = dyn_cast_or_null<ExtractValueInst>(Elt);
935     if (!EVI)
936       return NotFound;
937 
938     Value *SourceAggregate = EVI->getAggregateOperand();
939 
940     // Is the extraction from the same type into which the insertion was?
941     if (SourceAggregate->getType() != AggTy)
942       return FoundMismatch;
943     // And the element index doesn't change between extraction and insertion?
944     if (EVI->getNumIndices() != 1 || EltIdx != EVI->getIndices().front())
945       return FoundMismatch;
946 
947     return SourceAggregate; // AggregateDescription::Found
948   };
949 
950   // Given elements AggElts that were constructing an aggregate OrigIVI,
951   // see if we can find appropriate source aggregate for each of the elements,
952   // and see it's the same aggregate for each element. If so, return it.
953   auto FindCommonSourceAggregate =
954       [&](Optional<BasicBlock *> UseBB,
955           Optional<BasicBlock *> PredBB) -> Optional<Value *> {
956     Optional<Value *> SourceAggregate;
957 
958     for (auto I : enumerate(AggElts)) {
959       assert(Describe(SourceAggregate) != AggregateDescription::FoundMismatch &&
960              "We don't store nullptr in SourceAggregate!");
961       assert((Describe(SourceAggregate) == AggregateDescription::Found) ==
962                  (I.index() != 0) &&
963              "SourceAggregate should be valid after the first element,");
964 
965       // For this element, is there a plausible source aggregate?
966       // FIXME: we could special-case undef element, IFF we know that in the
967       //        source aggregate said element isn't poison.
968       Optional<Value *> SourceAggregateForElement =
969           FindSourceAggregate(*I.value(), I.index(), UseBB, PredBB);
970 
971       // Okay, what have we found? Does that correlate with previous findings?
972 
973       // Regardless of whether or not we have previously found source
974       // aggregate for previous elements (if any), if we didn't find one for
975       // this element, passthrough whatever we have just found.
976       if (Describe(SourceAggregateForElement) != AggregateDescription::Found)
977         return SourceAggregateForElement;
978 
979       // Okay, we have found source aggregate for this element.
980       // Let's see what we already know from previous elements, if any.
981       switch (Describe(SourceAggregate)) {
982       case AggregateDescription::NotFound:
983         // This is apparently the first element that we have examined.
984         SourceAggregate = SourceAggregateForElement; // Record the aggregate!
985         continue; // Great, now look at next element.
986       case AggregateDescription::Found:
987         // We have previously already successfully examined other elements.
988         // Is this the same source aggregate we've found for other elements?
989         if (*SourceAggregateForElement != *SourceAggregate)
990           return FoundMismatch;
991         continue; // Still the same aggregate, look at next element.
992       case AggregateDescription::FoundMismatch:
993         llvm_unreachable("Can't happen. We would have early-exited then.");
994       };
995     }
996 
997     assert(Describe(SourceAggregate) == AggregateDescription::Found &&
998            "Must be a valid Value");
999     return *SourceAggregate;
1000   };
1001 
1002   Optional<Value *> SourceAggregate;
1003 
1004   // Can we find the source aggregate without looking at predecessors?
1005   SourceAggregate = FindCommonSourceAggregate(/*UseBB=*/None, /*PredBB=*/None);
1006   if (Describe(SourceAggregate) != AggregateDescription::NotFound) {
1007     if (Describe(SourceAggregate) == AggregateDescription::FoundMismatch)
1008       return nullptr; // Conflicting source aggregates!
1009     ++NumAggregateReconstructionsSimplified;
1010     return replaceInstUsesWith(OrigIVI, *SourceAggregate);
1011   }
1012 
1013   // Okay, apparently we need to look at predecessors.
1014 
1015   // We should be smart about picking the "use" basic block, which will be the
1016   // merge point for aggregate, where we'll insert the final PHI that will be
1017   // used instead of OrigIVI. Basic block of OrigIVI is *not* the right choice.
1018   // We should look in which blocks each of the AggElts is being defined,
1019   // they all should be defined in the same basic block.
1020   BasicBlock *UseBB = nullptr;
1021 
1022   for (const Optional<Instruction *> &I : AggElts) {
1023     BasicBlock *BB = (*I)->getParent();
1024     // If it's the first instruction we've encountered, record the basic block.
1025     if (!UseBB) {
1026       UseBB = BB;
1027       continue;
1028     }
1029     // Otherwise, this must be the same basic block we've seen previously.
1030     if (UseBB != BB)
1031       return nullptr;
1032   }
1033 
1034   // If *all* of the elements are basic-block-independent, meaning they are
1035   // either function arguments, or constant expressions, then if we didn't
1036   // handle them without predecessor-aware handling, we won't handle them now.
1037   if (!UseBB)
1038     return nullptr;
1039 
1040   // If we didn't manage to find source aggregate without looking at
1041   // predecessors, and there are no predecessors to look at, then we're done.
1042   if (pred_empty(UseBB))
1043     return nullptr;
1044 
1045   // Arbitrary predecessor count limit.
1046   static const int PredCountLimit = 64;
1047 
1048   // Cache the (non-uniqified!) list of predecessors in a vector,
1049   // checking the limit at the same time for efficiency.
1050   SmallVector<BasicBlock *, 4> Preds; // May have duplicates!
1051   for (BasicBlock *Pred : predecessors(UseBB)) {
1052     // Don't bother if there are too many predecessors.
1053     if (Preds.size() >= PredCountLimit) // FIXME: only count duplicates once?
1054       return nullptr;
1055     Preds.emplace_back(Pred);
1056   }
1057 
1058   // For each predecessor, what is the source aggregate,
1059   // from which all the elements were originally extracted from?
1060   // Note that we want for the map to have stable iteration order!
1061   SmallDenseMap<BasicBlock *, Value *, 4> SourceAggregates;
1062   for (BasicBlock *Pred : Preds) {
1063     std::pair<decltype(SourceAggregates)::iterator, bool> IV =
1064         SourceAggregates.insert({Pred, nullptr});
1065     // Did we already evaluate this predecessor?
1066     if (!IV.second)
1067       continue;
1068 
1069     // Let's hope that when coming from predecessor Pred, all elements of the
1070     // aggregate produced by OrigIVI must have been originally extracted from
1071     // the same aggregate. Is that so? Can we find said original aggregate?
1072     SourceAggregate = FindCommonSourceAggregate(UseBB, Pred);
1073     if (Describe(SourceAggregate) != AggregateDescription::Found)
1074       return nullptr; // Give up.
1075     IV.first->second = *SourceAggregate;
1076   }
1077 
1078   // All good! Now we just need to thread the source aggregates here.
1079   // Note that we have to insert the new PHI here, ourselves, because we can't
1080   // rely on InstCombinerImpl::run() inserting it into the right basic block.
1081   // Note that the same block can be a predecessor more than once,
1082   // and we need to preserve that invariant for the PHI node.
1083   BuilderTy::InsertPointGuard Guard(Builder);
1084   Builder.SetInsertPoint(UseBB->getFirstNonPHI());
1085   auto *PHI =
1086       Builder.CreatePHI(AggTy, Preds.size(), OrigIVI.getName() + ".merged");
1087   for (BasicBlock *Pred : Preds)
1088     PHI->addIncoming(SourceAggregates[Pred], Pred);
1089 
1090   ++NumAggregateReconstructionsSimplified;
1091   return replaceInstUsesWith(OrigIVI, PHI);
1092 }
1093 
1094 /// Try to find redundant insertvalue instructions, like the following ones:
1095 ///  %0 = insertvalue { i8, i32 } undef, i8 %x, 0
1096 ///  %1 = insertvalue { i8, i32 } %0,    i8 %y, 0
1097 /// Here the second instruction inserts values at the same indices, as the
1098 /// first one, making the first one redundant.
1099 /// It should be transformed to:
1100 ///  %0 = insertvalue { i8, i32 } undef, i8 %y, 0
1101 Instruction *InstCombinerImpl::visitInsertValueInst(InsertValueInst &I) {
1102   bool IsRedundant = false;
1103   ArrayRef<unsigned int> FirstIndices = I.getIndices();
1104 
1105   // If there is a chain of insertvalue instructions (each of them except the
1106   // last one has only one use and it's another insertvalue insn from this
1107   // chain), check if any of the 'children' uses the same indices as the first
1108   // instruction. In this case, the first one is redundant.
1109   Value *V = &I;
1110   unsigned Depth = 0;
1111   while (V->hasOneUse() && Depth < 10) {
1112     User *U = V->user_back();
1113     auto UserInsInst = dyn_cast<InsertValueInst>(U);
1114     if (!UserInsInst || U->getOperand(0) != V)
1115       break;
1116     if (UserInsInst->getIndices() == FirstIndices) {
1117       IsRedundant = true;
1118       break;
1119     }
1120     V = UserInsInst;
1121     Depth++;
1122   }
1123 
1124   if (IsRedundant)
1125     return replaceInstUsesWith(I, I.getOperand(0));
1126 
1127   if (Instruction *NewI = foldAggregateConstructionIntoAggregateReuse(I))
1128     return NewI;
1129 
1130   return nullptr;
1131 }
1132 
1133 static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) {
1134   // Can not analyze scalable type, the number of elements is not a compile-time
1135   // constant.
1136   if (isa<ScalableVectorType>(Shuf.getOperand(0)->getType()))
1137     return false;
1138 
1139   int MaskSize = Shuf.getShuffleMask().size();
1140   int VecSize =
1141       cast<FixedVectorType>(Shuf.getOperand(0)->getType())->getNumElements();
1142 
1143   // A vector select does not change the size of the operands.
1144   if (MaskSize != VecSize)
1145     return false;
1146 
1147   // Each mask element must be undefined or choose a vector element from one of
1148   // the source operands without crossing vector lanes.
1149   for (int i = 0; i != MaskSize; ++i) {
1150     int Elt = Shuf.getMaskValue(i);
1151     if (Elt != -1 && Elt != i && Elt != i + VecSize)
1152       return false;
1153   }
1154 
1155   return true;
1156 }
1157 
1158 /// Turn a chain of inserts that splats a value into an insert + shuffle:
1159 /// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
1160 /// shufflevector(insertelt(X, %k, 0), poison, zero)
1161 static Instruction *foldInsSequenceIntoSplat(InsertElementInst &InsElt) {
1162   // We are interested in the last insert in a chain. So if this insert has a
1163   // single user and that user is an insert, bail.
1164   if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
1165     return nullptr;
1166 
1167   VectorType *VecTy = InsElt.getType();
1168   // Can not handle scalable type, the number of elements is not a compile-time
1169   // constant.
1170   if (isa<ScalableVectorType>(VecTy))
1171     return nullptr;
1172   unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1173 
1174   // Do not try to do this for a one-element vector, since that's a nop,
1175   // and will cause an inf-loop.
1176   if (NumElements == 1)
1177     return nullptr;
1178 
1179   Value *SplatVal = InsElt.getOperand(1);
1180   InsertElementInst *CurrIE = &InsElt;
1181   SmallBitVector ElementPresent(NumElements, false);
1182   InsertElementInst *FirstIE = nullptr;
1183 
1184   // Walk the chain backwards, keeping track of which indices we inserted into,
1185   // until we hit something that isn't an insert of the splatted value.
1186   while (CurrIE) {
1187     auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
1188     if (!Idx || CurrIE->getOperand(1) != SplatVal)
1189       return nullptr;
1190 
1191     auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
1192     // Check none of the intermediate steps have any additional uses, except
1193     // for the root insertelement instruction, which can be re-used, if it
1194     // inserts at position 0.
1195     if (CurrIE != &InsElt &&
1196         (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero())))
1197       return nullptr;
1198 
1199     ElementPresent[Idx->getZExtValue()] = true;
1200     FirstIE = CurrIE;
1201     CurrIE = NextIE;
1202   }
1203 
1204   // If this is just a single insertelement (not a sequence), we are done.
1205   if (FirstIE == &InsElt)
1206     return nullptr;
1207 
1208   // If we are not inserting into an undef vector, make sure we've seen an
1209   // insert into every element.
1210   // TODO: If the base vector is not undef, it might be better to create a splat
1211   //       and then a select-shuffle (blend) with the base vector.
1212   if (!match(FirstIE->getOperand(0), m_Undef()))
1213     if (!ElementPresent.all())
1214       return nullptr;
1215 
1216   // Create the insert + shuffle.
1217   Type *Int32Ty = Type::getInt32Ty(InsElt.getContext());
1218   PoisonValue *PoisonVec = PoisonValue::get(VecTy);
1219   Constant *Zero = ConstantInt::get(Int32Ty, 0);
1220   if (!cast<ConstantInt>(FirstIE->getOperand(2))->isZero())
1221     FirstIE = InsertElementInst::Create(PoisonVec, SplatVal, Zero, "", &InsElt);
1222 
1223   // Splat from element 0, but replace absent elements with undef in the mask.
1224   SmallVector<int, 16> Mask(NumElements, 0);
1225   for (unsigned i = 0; i != NumElements; ++i)
1226     if (!ElementPresent[i])
1227       Mask[i] = -1;
1228 
1229   return new ShuffleVectorInst(FirstIE, Mask);
1230 }
1231 
1232 /// Try to fold an insert element into an existing splat shuffle by changing
1233 /// the shuffle's mask to include the index of this insert element.
1234 static Instruction *foldInsEltIntoSplat(InsertElementInst &InsElt) {
1235   // Check if the vector operand of this insert is a canonical splat shuffle.
1236   auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
1237   if (!Shuf || !Shuf->isZeroEltSplat())
1238     return nullptr;
1239 
1240   // Bail out early if shuffle is scalable type. The number of elements in
1241   // shuffle mask is unknown at compile-time.
1242   if (isa<ScalableVectorType>(Shuf->getType()))
1243     return nullptr;
1244 
1245   // Check for a constant insertion index.
1246   uint64_t IdxC;
1247   if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
1248     return nullptr;
1249 
1250   // Check if the splat shuffle's input is the same as this insert's scalar op.
1251   Value *X = InsElt.getOperand(1);
1252   Value *Op0 = Shuf->getOperand(0);
1253   if (!match(Op0, m_InsertElt(m_Undef(), m_Specific(X), m_ZeroInt())))
1254     return nullptr;
1255 
1256   // Replace the shuffle mask element at the index of this insert with a zero.
1257   // For example:
1258   // inselt (shuf (inselt undef, X, 0), _, <0,undef,0,undef>), X, 1
1259   //   --> shuf (inselt undef, X, 0), poison, <0,0,0,undef>
1260   unsigned NumMaskElts =
1261       cast<FixedVectorType>(Shuf->getType())->getNumElements();
1262   SmallVector<int, 16> NewMask(NumMaskElts);
1263   for (unsigned i = 0; i != NumMaskElts; ++i)
1264     NewMask[i] = i == IdxC ? 0 : Shuf->getMaskValue(i);
1265 
1266   return new ShuffleVectorInst(Op0, NewMask);
1267 }
1268 
1269 /// Try to fold an extract+insert element into an existing identity shuffle by
1270 /// changing the shuffle's mask to include the index of this insert element.
1271 static Instruction *foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt) {
1272   // Check if the vector operand of this insert is an identity shuffle.
1273   auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
1274   if (!Shuf || !match(Shuf->getOperand(1), m_Undef()) ||
1275       !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding()))
1276     return nullptr;
1277 
1278   // Bail out early if shuffle is scalable type. The number of elements in
1279   // shuffle mask is unknown at compile-time.
1280   if (isa<ScalableVectorType>(Shuf->getType()))
1281     return nullptr;
1282 
1283   // Check for a constant insertion index.
1284   uint64_t IdxC;
1285   if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
1286     return nullptr;
1287 
1288   // Check if this insert's scalar op is extracted from the identity shuffle's
1289   // input vector.
1290   Value *Scalar = InsElt.getOperand(1);
1291   Value *X = Shuf->getOperand(0);
1292   if (!match(Scalar, m_ExtractElt(m_Specific(X), m_SpecificInt(IdxC))))
1293     return nullptr;
1294 
1295   // Replace the shuffle mask element at the index of this extract+insert with
1296   // that same index value.
1297   // For example:
1298   // inselt (shuf X, IdMask), (extelt X, IdxC), IdxC --> shuf X, IdMask'
1299   unsigned NumMaskElts =
1300       cast<FixedVectorType>(Shuf->getType())->getNumElements();
1301   SmallVector<int, 16> NewMask(NumMaskElts);
1302   ArrayRef<int> OldMask = Shuf->getShuffleMask();
1303   for (unsigned i = 0; i != NumMaskElts; ++i) {
1304     if (i != IdxC) {
1305       // All mask elements besides the inserted element remain the same.
1306       NewMask[i] = OldMask[i];
1307     } else if (OldMask[i] == (int)IdxC) {
1308       // If the mask element was already set, there's nothing to do
1309       // (demanded elements analysis may unset it later).
1310       return nullptr;
1311     } else {
1312       assert(OldMask[i] == UndefMaskElem &&
1313              "Unexpected shuffle mask element for identity shuffle");
1314       NewMask[i] = IdxC;
1315     }
1316   }
1317 
1318   return new ShuffleVectorInst(X, Shuf->getOperand(1), NewMask);
1319 }
1320 
1321 /// If we have an insertelement instruction feeding into another insertelement
1322 /// and the 2nd is inserting a constant into the vector, canonicalize that
1323 /// constant insertion before the insertion of a variable:
1324 ///
1325 /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
1326 /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
1327 ///
1328 /// This has the potential of eliminating the 2nd insertelement instruction
1329 /// via constant folding of the scalar constant into a vector constant.
1330 static Instruction *hoistInsEltConst(InsertElementInst &InsElt2,
1331                                      InstCombiner::BuilderTy &Builder) {
1332   auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
1333   if (!InsElt1 || !InsElt1->hasOneUse())
1334     return nullptr;
1335 
1336   Value *X, *Y;
1337   Constant *ScalarC;
1338   ConstantInt *IdxC1, *IdxC2;
1339   if (match(InsElt1->getOperand(0), m_Value(X)) &&
1340       match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
1341       match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
1342       match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
1343       match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
1344     Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
1345     return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
1346   }
1347 
1348   return nullptr;
1349 }
1350 
1351 /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
1352 /// --> shufflevector X, CVec', Mask'
1353 static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) {
1354   auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
1355   // Bail out if the parent has more than one use. In that case, we'd be
1356   // replacing the insertelt with a shuffle, and that's not a clear win.
1357   if (!Inst || !Inst->hasOneUse())
1358     return nullptr;
1359   if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
1360     // The shuffle must have a constant vector operand. The insertelt must have
1361     // a constant scalar being inserted at a constant position in the vector.
1362     Constant *ShufConstVec, *InsEltScalar;
1363     uint64_t InsEltIndex;
1364     if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
1365         !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
1366         !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
1367       return nullptr;
1368 
1369     // Adding an element to an arbitrary shuffle could be expensive, but a
1370     // shuffle that selects elements from vectors without crossing lanes is
1371     // assumed cheap.
1372     // If we're just adding a constant into that shuffle, it will still be
1373     // cheap.
1374     if (!isShuffleEquivalentToSelect(*Shuf))
1375       return nullptr;
1376 
1377     // From the above 'select' check, we know that the mask has the same number
1378     // of elements as the vector input operands. We also know that each constant
1379     // input element is used in its lane and can not be used more than once by
1380     // the shuffle. Therefore, replace the constant in the shuffle's constant
1381     // vector with the insertelt constant. Replace the constant in the shuffle's
1382     // mask vector with the insertelt index plus the length of the vector
1383     // (because the constant vector operand of a shuffle is always the 2nd
1384     // operand).
1385     ArrayRef<int> Mask = Shuf->getShuffleMask();
1386     unsigned NumElts = Mask.size();
1387     SmallVector<Constant *, 16> NewShufElts(NumElts);
1388     SmallVector<int, 16> NewMaskElts(NumElts);
1389     for (unsigned I = 0; I != NumElts; ++I) {
1390       if (I == InsEltIndex) {
1391         NewShufElts[I] = InsEltScalar;
1392         NewMaskElts[I] = InsEltIndex + NumElts;
1393       } else {
1394         // Copy over the existing values.
1395         NewShufElts[I] = ShufConstVec->getAggregateElement(I);
1396         NewMaskElts[I] = Mask[I];
1397       }
1398 
1399       // Bail if we failed to find an element.
1400       if (!NewShufElts[I])
1401         return nullptr;
1402     }
1403 
1404     // Create new operands for a shuffle that includes the constant of the
1405     // original insertelt. The old shuffle will be dead now.
1406     return new ShuffleVectorInst(Shuf->getOperand(0),
1407                                  ConstantVector::get(NewShufElts), NewMaskElts);
1408   } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
1409     // Transform sequences of insertelements ops with constant data/indexes into
1410     // a single shuffle op.
1411     // Can not handle scalable type, the number of elements needed to create
1412     // shuffle mask is not a compile-time constant.
1413     if (isa<ScalableVectorType>(InsElt.getType()))
1414       return nullptr;
1415     unsigned NumElts =
1416         cast<FixedVectorType>(InsElt.getType())->getNumElements();
1417 
1418     uint64_t InsertIdx[2];
1419     Constant *Val[2];
1420     if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
1421         !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
1422         !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
1423         !match(IEI->getOperand(1), m_Constant(Val[1])))
1424       return nullptr;
1425     SmallVector<Constant *, 16> Values(NumElts);
1426     SmallVector<int, 16> Mask(NumElts);
1427     auto ValI = std::begin(Val);
1428     // Generate new constant vector and mask.
1429     // We have 2 values/masks from the insertelements instructions. Insert them
1430     // into new value/mask vectors.
1431     for (uint64_t I : InsertIdx) {
1432       if (!Values[I]) {
1433         Values[I] = *ValI;
1434         Mask[I] = NumElts + I;
1435       }
1436       ++ValI;
1437     }
1438     // Remaining values are filled with 'undef' values.
1439     for (unsigned I = 0; I < NumElts; ++I) {
1440       if (!Values[I]) {
1441         Values[I] = UndefValue::get(InsElt.getType()->getElementType());
1442         Mask[I] = I;
1443       }
1444     }
1445     // Create new operands for a shuffle that includes the constant of the
1446     // original insertelt.
1447     return new ShuffleVectorInst(IEI->getOperand(0),
1448                                  ConstantVector::get(Values), Mask);
1449   }
1450   return nullptr;
1451 }
1452 
1453 /// If both the base vector and the inserted element are extended from the same
1454 /// type, do the insert element in the narrow source type followed by extend.
1455 /// TODO: This can be extended to include other cast opcodes, but particularly
1456 ///       if we create a wider insertelement, make sure codegen is not harmed.
1457 static Instruction *narrowInsElt(InsertElementInst &InsElt,
1458                                  InstCombiner::BuilderTy &Builder) {
1459   // We are creating a vector extend. If the original vector extend has another
1460   // use, that would mean we end up with 2 vector extends, so avoid that.
1461   // TODO: We could ease the use-clause to "if at least one op has one use"
1462   //       (assuming that the source types match - see next TODO comment).
1463   Value *Vec = InsElt.getOperand(0);
1464   if (!Vec->hasOneUse())
1465     return nullptr;
1466 
1467   Value *Scalar = InsElt.getOperand(1);
1468   Value *X, *Y;
1469   CastInst::CastOps CastOpcode;
1470   if (match(Vec, m_FPExt(m_Value(X))) && match(Scalar, m_FPExt(m_Value(Y))))
1471     CastOpcode = Instruction::FPExt;
1472   else if (match(Vec, m_SExt(m_Value(X))) && match(Scalar, m_SExt(m_Value(Y))))
1473     CastOpcode = Instruction::SExt;
1474   else if (match(Vec, m_ZExt(m_Value(X))) && match(Scalar, m_ZExt(m_Value(Y))))
1475     CastOpcode = Instruction::ZExt;
1476   else
1477     return nullptr;
1478 
1479   // TODO: We can allow mismatched types by creating an intermediate cast.
1480   if (X->getType()->getScalarType() != Y->getType())
1481     return nullptr;
1482 
1483   // inselt (ext X), (ext Y), Index --> ext (inselt X, Y, Index)
1484   Value *NewInsElt = Builder.CreateInsertElement(X, Y, InsElt.getOperand(2));
1485   return CastInst::Create(CastOpcode, NewInsElt, InsElt.getType());
1486 }
1487 
1488 Instruction *InstCombinerImpl::visitInsertElementInst(InsertElementInst &IE) {
1489   Value *VecOp    = IE.getOperand(0);
1490   Value *ScalarOp = IE.getOperand(1);
1491   Value *IdxOp    = IE.getOperand(2);
1492 
1493   if (auto *V = SimplifyInsertElementInst(
1494           VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE)))
1495     return replaceInstUsesWith(IE, V);
1496 
1497   // Canonicalize type of constant indices to i64 to simplify CSE
1498   if (auto *IndexC = dyn_cast<ConstantInt>(IdxOp))
1499     if (auto *NewIdx = getPreferredVectorIndex(IndexC))
1500       return replaceOperand(IE, 2, NewIdx);
1501 
1502   // If the scalar is bitcast and inserted into undef, do the insert in the
1503   // source type followed by bitcast.
1504   // TODO: Generalize for insert into any constant, not just undef?
1505   Value *ScalarSrc;
1506   if (match(VecOp, m_Undef()) &&
1507       match(ScalarOp, m_OneUse(m_BitCast(m_Value(ScalarSrc)))) &&
1508       (ScalarSrc->getType()->isIntegerTy() ||
1509        ScalarSrc->getType()->isFloatingPointTy())) {
1510     // inselt undef, (bitcast ScalarSrc), IdxOp -->
1511     //   bitcast (inselt undef, ScalarSrc, IdxOp)
1512     Type *ScalarTy = ScalarSrc->getType();
1513     Type *VecTy = VectorType::get(ScalarTy, IE.getType()->getElementCount());
1514     UndefValue *NewUndef = UndefValue::get(VecTy);
1515     Value *NewInsElt = Builder.CreateInsertElement(NewUndef, ScalarSrc, IdxOp);
1516     return new BitCastInst(NewInsElt, IE.getType());
1517   }
1518 
1519   // If the vector and scalar are both bitcast from the same element type, do
1520   // the insert in that source type followed by bitcast.
1521   Value *VecSrc;
1522   if (match(VecOp, m_BitCast(m_Value(VecSrc))) &&
1523       match(ScalarOp, m_BitCast(m_Value(ScalarSrc))) &&
1524       (VecOp->hasOneUse() || ScalarOp->hasOneUse()) &&
1525       VecSrc->getType()->isVectorTy() && !ScalarSrc->getType()->isVectorTy() &&
1526       cast<VectorType>(VecSrc->getType())->getElementType() ==
1527           ScalarSrc->getType()) {
1528     // inselt (bitcast VecSrc), (bitcast ScalarSrc), IdxOp -->
1529     //   bitcast (inselt VecSrc, ScalarSrc, IdxOp)
1530     Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp);
1531     return new BitCastInst(NewInsElt, IE.getType());
1532   }
1533 
1534   // If the inserted element was extracted from some other fixed-length vector
1535   // and both indexes are valid constants, try to turn this into a shuffle.
1536   // Can not handle scalable vector type, the number of elements needed to
1537   // create shuffle mask is not a compile-time constant.
1538   uint64_t InsertedIdx, ExtractedIdx;
1539   Value *ExtVecOp;
1540   if (isa<FixedVectorType>(IE.getType()) &&
1541       match(IdxOp, m_ConstantInt(InsertedIdx)) &&
1542       match(ScalarOp,
1543             m_ExtractElt(m_Value(ExtVecOp), m_ConstantInt(ExtractedIdx))) &&
1544       isa<FixedVectorType>(ExtVecOp->getType()) &&
1545       ExtractedIdx <
1546           cast<FixedVectorType>(ExtVecOp->getType())->getNumElements()) {
1547     // TODO: Looking at the user(s) to determine if this insert is a
1548     // fold-to-shuffle opportunity does not match the usual instcombine
1549     // constraints. We should decide if the transform is worthy based only
1550     // on this instruction and its operands, but that may not work currently.
1551     //
1552     // Here, we are trying to avoid creating shuffles before reaching
1553     // the end of a chain of extract-insert pairs. This is complicated because
1554     // we do not generally form arbitrary shuffle masks in instcombine
1555     // (because those may codegen poorly), but collectShuffleElements() does
1556     // exactly that.
1557     //
1558     // The rules for determining what is an acceptable target-independent
1559     // shuffle mask are fuzzy because they evolve based on the backend's
1560     // capabilities and real-world impact.
1561     auto isShuffleRootCandidate = [](InsertElementInst &Insert) {
1562       if (!Insert.hasOneUse())
1563         return true;
1564       auto *InsertUser = dyn_cast<InsertElementInst>(Insert.user_back());
1565       if (!InsertUser)
1566         return true;
1567       return false;
1568     };
1569 
1570     // Try to form a shuffle from a chain of extract-insert ops.
1571     if (isShuffleRootCandidate(IE)) {
1572       SmallVector<int, 16> Mask;
1573       ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
1574 
1575       // The proposed shuffle may be trivial, in which case we shouldn't
1576       // perform the combine.
1577       if (LR.first != &IE && LR.second != &IE) {
1578         // We now have a shuffle of LHS, RHS, Mask.
1579         if (LR.second == nullptr)
1580           LR.second = UndefValue::get(LR.first->getType());
1581         return new ShuffleVectorInst(LR.first, LR.second, Mask);
1582       }
1583     }
1584   }
1585 
1586   if (auto VecTy = dyn_cast<FixedVectorType>(VecOp->getType())) {
1587     unsigned VWidth = VecTy->getNumElements();
1588     APInt UndefElts(VWidth, 0);
1589     APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
1590     if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
1591       if (V != &IE)
1592         return replaceInstUsesWith(IE, V);
1593       return &IE;
1594     }
1595   }
1596 
1597   if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE))
1598     return Shuf;
1599 
1600   if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder))
1601     return NewInsElt;
1602 
1603   if (Instruction *Broadcast = foldInsSequenceIntoSplat(IE))
1604     return Broadcast;
1605 
1606   if (Instruction *Splat = foldInsEltIntoSplat(IE))
1607     return Splat;
1608 
1609   if (Instruction *IdentityShuf = foldInsEltIntoIdentityShuffle(IE))
1610     return IdentityShuf;
1611 
1612   if (Instruction *Ext = narrowInsElt(IE, Builder))
1613     return Ext;
1614 
1615   return nullptr;
1616 }
1617 
1618 /// Return true if we can evaluate the specified expression tree if the vector
1619 /// elements were shuffled in a different order.
1620 static bool canEvaluateShuffled(Value *V, ArrayRef<int> Mask,
1621                                 unsigned Depth = 5) {
1622   // We can always reorder the elements of a constant.
1623   if (isa<Constant>(V))
1624     return true;
1625 
1626   // We won't reorder vector arguments. No IPO here.
1627   Instruction *I = dyn_cast<Instruction>(V);
1628   if (!I) return false;
1629 
1630   // Two users may expect different orders of the elements. Don't try it.
1631   if (!I->hasOneUse())
1632     return false;
1633 
1634   if (Depth == 0) return false;
1635 
1636   switch (I->getOpcode()) {
1637     case Instruction::UDiv:
1638     case Instruction::SDiv:
1639     case Instruction::URem:
1640     case Instruction::SRem:
1641       // Propagating an undefined shuffle mask element to integer div/rem is not
1642       // allowed because those opcodes can create immediate undefined behavior
1643       // from an undefined element in an operand.
1644       if (llvm::is_contained(Mask, -1))
1645         return false;
1646       LLVM_FALLTHROUGH;
1647     case Instruction::Add:
1648     case Instruction::FAdd:
1649     case Instruction::Sub:
1650     case Instruction::FSub:
1651     case Instruction::Mul:
1652     case Instruction::FMul:
1653     case Instruction::FDiv:
1654     case Instruction::FRem:
1655     case Instruction::Shl:
1656     case Instruction::LShr:
1657     case Instruction::AShr:
1658     case Instruction::And:
1659     case Instruction::Or:
1660     case Instruction::Xor:
1661     case Instruction::ICmp:
1662     case Instruction::FCmp:
1663     case Instruction::Trunc:
1664     case Instruction::ZExt:
1665     case Instruction::SExt:
1666     case Instruction::FPToUI:
1667     case Instruction::FPToSI:
1668     case Instruction::UIToFP:
1669     case Instruction::SIToFP:
1670     case Instruction::FPTrunc:
1671     case Instruction::FPExt:
1672     case Instruction::GetElementPtr: {
1673       // Bail out if we would create longer vector ops. We could allow creating
1674       // longer vector ops, but that may result in more expensive codegen.
1675       Type *ITy = I->getType();
1676       if (ITy->isVectorTy() &&
1677           Mask.size() > cast<FixedVectorType>(ITy)->getNumElements())
1678         return false;
1679       for (Value *Operand : I->operands()) {
1680         if (!canEvaluateShuffled(Operand, Mask, Depth - 1))
1681           return false;
1682       }
1683       return true;
1684     }
1685     case Instruction::InsertElement: {
1686       ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
1687       if (!CI) return false;
1688       int ElementNumber = CI->getLimitedValue();
1689 
1690       // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
1691       // can't put an element into multiple indices.
1692       bool SeenOnce = false;
1693       for (int i = 0, e = Mask.size(); i != e; ++i) {
1694         if (Mask[i] == ElementNumber) {
1695           if (SeenOnce)
1696             return false;
1697           SeenOnce = true;
1698         }
1699       }
1700       return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1);
1701     }
1702   }
1703   return false;
1704 }
1705 
1706 /// Rebuild a new instruction just like 'I' but with the new operands given.
1707 /// In the event of type mismatch, the type of the operands is correct.
1708 static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
1709   // We don't want to use the IRBuilder here because we want the replacement
1710   // instructions to appear next to 'I', not the builder's insertion point.
1711   switch (I->getOpcode()) {
1712     case Instruction::Add:
1713     case Instruction::FAdd:
1714     case Instruction::Sub:
1715     case Instruction::FSub:
1716     case Instruction::Mul:
1717     case Instruction::FMul:
1718     case Instruction::UDiv:
1719     case Instruction::SDiv:
1720     case Instruction::FDiv:
1721     case Instruction::URem:
1722     case Instruction::SRem:
1723     case Instruction::FRem:
1724     case Instruction::Shl:
1725     case Instruction::LShr:
1726     case Instruction::AShr:
1727     case Instruction::And:
1728     case Instruction::Or:
1729     case Instruction::Xor: {
1730       BinaryOperator *BO = cast<BinaryOperator>(I);
1731       assert(NewOps.size() == 2 && "binary operator with #ops != 2");
1732       BinaryOperator *New =
1733           BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
1734                                  NewOps[0], NewOps[1], "", BO);
1735       if (isa<OverflowingBinaryOperator>(BO)) {
1736         New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
1737         New->setHasNoSignedWrap(BO->hasNoSignedWrap());
1738       }
1739       if (isa<PossiblyExactOperator>(BO)) {
1740         New->setIsExact(BO->isExact());
1741       }
1742       if (isa<FPMathOperator>(BO))
1743         New->copyFastMathFlags(I);
1744       return New;
1745     }
1746     case Instruction::ICmp:
1747       assert(NewOps.size() == 2 && "icmp with #ops != 2");
1748       return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
1749                           NewOps[0], NewOps[1]);
1750     case Instruction::FCmp:
1751       assert(NewOps.size() == 2 && "fcmp with #ops != 2");
1752       return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
1753                           NewOps[0], NewOps[1]);
1754     case Instruction::Trunc:
1755     case Instruction::ZExt:
1756     case Instruction::SExt:
1757     case Instruction::FPToUI:
1758     case Instruction::FPToSI:
1759     case Instruction::UIToFP:
1760     case Instruction::SIToFP:
1761     case Instruction::FPTrunc:
1762     case Instruction::FPExt: {
1763       // It's possible that the mask has a different number of elements from
1764       // the original cast. We recompute the destination type to match the mask.
1765       Type *DestTy = VectorType::get(
1766           I->getType()->getScalarType(),
1767           cast<VectorType>(NewOps[0]->getType())->getElementCount());
1768       assert(NewOps.size() == 1 && "cast with #ops != 1");
1769       return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
1770                               "", I);
1771     }
1772     case Instruction::GetElementPtr: {
1773       Value *Ptr = NewOps[0];
1774       ArrayRef<Value*> Idx = NewOps.slice(1);
1775       GetElementPtrInst *GEP = GetElementPtrInst::Create(
1776           cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
1777       GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
1778       return GEP;
1779     }
1780   }
1781   llvm_unreachable("failed to rebuild vector instructions");
1782 }
1783 
1784 static Value *evaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
1785   // Mask.size() does not need to be equal to the number of vector elements.
1786 
1787   assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
1788   Type *EltTy = V->getType()->getScalarType();
1789   Type *I32Ty = IntegerType::getInt32Ty(V->getContext());
1790   if (match(V, m_Undef()))
1791     return UndefValue::get(FixedVectorType::get(EltTy, Mask.size()));
1792 
1793   if (isa<ConstantAggregateZero>(V))
1794     return ConstantAggregateZero::get(FixedVectorType::get(EltTy, Mask.size()));
1795 
1796   if (Constant *C = dyn_cast<Constant>(V))
1797     return ConstantExpr::getShuffleVector(C, PoisonValue::get(C->getType()),
1798                                           Mask);
1799 
1800   Instruction *I = cast<Instruction>(V);
1801   switch (I->getOpcode()) {
1802     case Instruction::Add:
1803     case Instruction::FAdd:
1804     case Instruction::Sub:
1805     case Instruction::FSub:
1806     case Instruction::Mul:
1807     case Instruction::FMul:
1808     case Instruction::UDiv:
1809     case Instruction::SDiv:
1810     case Instruction::FDiv:
1811     case Instruction::URem:
1812     case Instruction::SRem:
1813     case Instruction::FRem:
1814     case Instruction::Shl:
1815     case Instruction::LShr:
1816     case Instruction::AShr:
1817     case Instruction::And:
1818     case Instruction::Or:
1819     case Instruction::Xor:
1820     case Instruction::ICmp:
1821     case Instruction::FCmp:
1822     case Instruction::Trunc:
1823     case Instruction::ZExt:
1824     case Instruction::SExt:
1825     case Instruction::FPToUI:
1826     case Instruction::FPToSI:
1827     case Instruction::UIToFP:
1828     case Instruction::SIToFP:
1829     case Instruction::FPTrunc:
1830     case Instruction::FPExt:
1831     case Instruction::Select:
1832     case Instruction::GetElementPtr: {
1833       SmallVector<Value*, 8> NewOps;
1834       bool NeedsRebuild =
1835           (Mask.size() !=
1836            cast<FixedVectorType>(I->getType())->getNumElements());
1837       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
1838         Value *V;
1839         // Recursively call evaluateInDifferentElementOrder on vector arguments
1840         // as well. E.g. GetElementPtr may have scalar operands even if the
1841         // return value is a vector, so we need to examine the operand type.
1842         if (I->getOperand(i)->getType()->isVectorTy())
1843           V = evaluateInDifferentElementOrder(I->getOperand(i), Mask);
1844         else
1845           V = I->getOperand(i);
1846         NewOps.push_back(V);
1847         NeedsRebuild |= (V != I->getOperand(i));
1848       }
1849       if (NeedsRebuild) {
1850         return buildNew(I, NewOps);
1851       }
1852       return I;
1853     }
1854     case Instruction::InsertElement: {
1855       int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
1856 
1857       // The insertelement was inserting at Element. Figure out which element
1858       // that becomes after shuffling. The answer is guaranteed to be unique
1859       // by CanEvaluateShuffled.
1860       bool Found = false;
1861       int Index = 0;
1862       for (int e = Mask.size(); Index != e; ++Index) {
1863         if (Mask[Index] == Element) {
1864           Found = true;
1865           break;
1866         }
1867       }
1868 
1869       // If element is not in Mask, no need to handle the operand 1 (element to
1870       // be inserted). Just evaluate values in operand 0 according to Mask.
1871       if (!Found)
1872         return evaluateInDifferentElementOrder(I->getOperand(0), Mask);
1873 
1874       Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask);
1875       return InsertElementInst::Create(V, I->getOperand(1),
1876                                        ConstantInt::get(I32Ty, Index), "", I);
1877     }
1878   }
1879   llvm_unreachable("failed to reorder elements of vector instruction!");
1880 }
1881 
1882 // Returns true if the shuffle is extracting a contiguous range of values from
1883 // LHS, for example:
1884 //                 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1885 //   Input:        |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
1886 //   Shuffles to:  |EE|FF|GG|HH|
1887 //                 +--+--+--+--+
1888 static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
1889                                        ArrayRef<int> Mask) {
1890   unsigned LHSElems =
1891       cast<FixedVectorType>(SVI.getOperand(0)->getType())->getNumElements();
1892   unsigned MaskElems = Mask.size();
1893   unsigned BegIdx = Mask.front();
1894   unsigned EndIdx = Mask.back();
1895   if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
1896     return false;
1897   for (unsigned I = 0; I != MaskElems; ++I)
1898     if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
1899       return false;
1900   return true;
1901 }
1902 
1903 /// These are the ingredients in an alternate form binary operator as described
1904 /// below.
1905 struct BinopElts {
1906   BinaryOperator::BinaryOps Opcode;
1907   Value *Op0;
1908   Value *Op1;
1909   BinopElts(BinaryOperator::BinaryOps Opc = (BinaryOperator::BinaryOps)0,
1910             Value *V0 = nullptr, Value *V1 = nullptr) :
1911       Opcode(Opc), Op0(V0), Op1(V1) {}
1912   operator bool() const { return Opcode != 0; }
1913 };
1914 
1915 /// Binops may be transformed into binops with different opcodes and operands.
1916 /// Reverse the usual canonicalization to enable folds with the non-canonical
1917 /// form of the binop. If a transform is possible, return the elements of the
1918 /// new binop. If not, return invalid elements.
1919 static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL) {
1920   Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1);
1921   Type *Ty = BO->getType();
1922   switch (BO->getOpcode()) {
1923     case Instruction::Shl: {
1924       // shl X, C --> mul X, (1 << C)
1925       Constant *C;
1926       if (match(BO1, m_Constant(C))) {
1927         Constant *ShlOne = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C);
1928         return { Instruction::Mul, BO0, ShlOne };
1929       }
1930       break;
1931     }
1932     case Instruction::Or: {
1933       // or X, C --> add X, C (when X and C have no common bits set)
1934       const APInt *C;
1935       if (match(BO1, m_APInt(C)) && MaskedValueIsZero(BO0, *C, DL))
1936         return { Instruction::Add, BO0, BO1 };
1937       break;
1938     }
1939     default:
1940       break;
1941   }
1942   return {};
1943 }
1944 
1945 static Instruction *foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf) {
1946   assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
1947 
1948   // Are we shuffling together some value and that same value after it has been
1949   // modified by a binop with a constant?
1950   Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
1951   Constant *C;
1952   bool Op0IsBinop;
1953   if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C))))
1954     Op0IsBinop = true;
1955   else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C))))
1956     Op0IsBinop = false;
1957   else
1958     return nullptr;
1959 
1960   // The identity constant for a binop leaves a variable operand unchanged. For
1961   // a vector, this is a splat of something like 0, -1, or 1.
1962   // If there's no identity constant for this binop, we're done.
1963   auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1);
1964   BinaryOperator::BinaryOps BOpcode = BO->getOpcode();
1965   Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true);
1966   if (!IdC)
1967     return nullptr;
1968 
1969   // Shuffle identity constants into the lanes that return the original value.
1970   // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4}
1971   // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4}
1972   // The existing binop constant vector remains in the same operand position.
1973   ArrayRef<int> Mask = Shuf.getShuffleMask();
1974   Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) :
1975                                 ConstantExpr::getShuffleVector(IdC, C, Mask);
1976 
1977   bool MightCreatePoisonOrUB =
1978       is_contained(Mask, UndefMaskElem) &&
1979       (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode));
1980   if (MightCreatePoisonOrUB)
1981     NewC = InstCombiner::getSafeVectorConstantForBinop(BOpcode, NewC, true);
1982 
1983   // shuf (bop X, C), X, M --> bop X, C'
1984   // shuf X, (bop X, C), M --> bop X, C'
1985   Value *X = Op0IsBinop ? Op1 : Op0;
1986   Instruction *NewBO = BinaryOperator::Create(BOpcode, X, NewC);
1987   NewBO->copyIRFlags(BO);
1988 
1989   // An undef shuffle mask element may propagate as an undef constant element in
1990   // the new binop. That would produce poison where the original code might not.
1991   // If we already made a safe constant, then there's no danger.
1992   if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB)
1993     NewBO->dropPoisonGeneratingFlags();
1994   return NewBO;
1995 }
1996 
1997 /// If we have an insert of a scalar to a non-zero element of an undefined
1998 /// vector and then shuffle that value, that's the same as inserting to the zero
1999 /// element and shuffling. Splatting from the zero element is recognized as the
2000 /// canonical form of splat.
2001 static Instruction *canonicalizeInsertSplat(ShuffleVectorInst &Shuf,
2002                                             InstCombiner::BuilderTy &Builder) {
2003   Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2004   ArrayRef<int> Mask = Shuf.getShuffleMask();
2005   Value *X;
2006   uint64_t IndexC;
2007 
2008   // Match a shuffle that is a splat to a non-zero element.
2009   if (!match(Op0, m_OneUse(m_InsertElt(m_Undef(), m_Value(X),
2010                                        m_ConstantInt(IndexC)))) ||
2011       !match(Op1, m_Undef()) || match(Mask, m_ZeroMask()) || IndexC == 0)
2012     return nullptr;
2013 
2014   // Insert into element 0 of an undef vector.
2015   UndefValue *UndefVec = UndefValue::get(Shuf.getType());
2016   Constant *Zero = Builder.getInt32(0);
2017   Value *NewIns = Builder.CreateInsertElement(UndefVec, X, Zero);
2018 
2019   // Splat from element 0. Any mask element that is undefined remains undefined.
2020   // For example:
2021   // shuf (inselt undef, X, 2), _, <2,2,undef>
2022   //   --> shuf (inselt undef, X, 0), poison, <0,0,undef>
2023   unsigned NumMaskElts =
2024       cast<FixedVectorType>(Shuf.getType())->getNumElements();
2025   SmallVector<int, 16> NewMask(NumMaskElts, 0);
2026   for (unsigned i = 0; i != NumMaskElts; ++i)
2027     if (Mask[i] == UndefMaskElem)
2028       NewMask[i] = Mask[i];
2029 
2030   return new ShuffleVectorInst(NewIns, NewMask);
2031 }
2032 
2033 /// Try to fold shuffles that are the equivalent of a vector select.
2034 Instruction *InstCombinerImpl::foldSelectShuffle(ShuffleVectorInst &Shuf) {
2035   if (!Shuf.isSelect())
2036     return nullptr;
2037 
2038   // Canonicalize to choose from operand 0 first unless operand 1 is undefined.
2039   // Commuting undef to operand 0 conflicts with another canonicalization.
2040   unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
2041   if (!match(Shuf.getOperand(1), m_Undef()) &&
2042       Shuf.getMaskValue(0) >= (int)NumElts) {
2043     // TODO: Can we assert that both operands of a shuffle-select are not undef
2044     // (otherwise, it would have been folded by instsimplify?
2045     Shuf.commute();
2046     return &Shuf;
2047   }
2048 
2049   if (Instruction *I = foldSelectShuffleWith1Binop(Shuf))
2050     return I;
2051 
2052   BinaryOperator *B0, *B1;
2053   if (!match(Shuf.getOperand(0), m_BinOp(B0)) ||
2054       !match(Shuf.getOperand(1), m_BinOp(B1)))
2055     return nullptr;
2056 
2057   Value *X, *Y;
2058   Constant *C0, *C1;
2059   bool ConstantsAreOp1;
2060   if (match(B0, m_BinOp(m_Value(X), m_Constant(C0))) &&
2061       match(B1, m_BinOp(m_Value(Y), m_Constant(C1))))
2062     ConstantsAreOp1 = true;
2063   else if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) &&
2064            match(B1, m_BinOp(m_Constant(C1), m_Value(Y))))
2065     ConstantsAreOp1 = false;
2066   else
2067     return nullptr;
2068 
2069   // We need matching binops to fold the lanes together.
2070   BinaryOperator::BinaryOps Opc0 = B0->getOpcode();
2071   BinaryOperator::BinaryOps Opc1 = B1->getOpcode();
2072   bool DropNSW = false;
2073   if (ConstantsAreOp1 && Opc0 != Opc1) {
2074     // TODO: We drop "nsw" if shift is converted into multiply because it may
2075     // not be correct when the shift amount is BitWidth - 1. We could examine
2076     // each vector element to determine if it is safe to keep that flag.
2077     if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl)
2078       DropNSW = true;
2079     if (BinopElts AltB0 = getAlternateBinop(B0, DL)) {
2080       assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop");
2081       Opc0 = AltB0.Opcode;
2082       C0 = cast<Constant>(AltB0.Op1);
2083     } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) {
2084       assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop");
2085       Opc1 = AltB1.Opcode;
2086       C1 = cast<Constant>(AltB1.Op1);
2087     }
2088   }
2089 
2090   if (Opc0 != Opc1)
2091     return nullptr;
2092 
2093   // The opcodes must be the same. Use a new name to make that clear.
2094   BinaryOperator::BinaryOps BOpc = Opc0;
2095 
2096   // Select the constant elements needed for the single binop.
2097   ArrayRef<int> Mask = Shuf.getShuffleMask();
2098   Constant *NewC = ConstantExpr::getShuffleVector(C0, C1, Mask);
2099 
2100   // We are moving a binop after a shuffle. When a shuffle has an undefined
2101   // mask element, the result is undefined, but it is not poison or undefined
2102   // behavior. That is not necessarily true for div/rem/shift.
2103   bool MightCreatePoisonOrUB =
2104       is_contained(Mask, UndefMaskElem) &&
2105       (Instruction::isIntDivRem(BOpc) || Instruction::isShift(BOpc));
2106   if (MightCreatePoisonOrUB)
2107     NewC = InstCombiner::getSafeVectorConstantForBinop(BOpc, NewC,
2108                                                        ConstantsAreOp1);
2109 
2110   Value *V;
2111   if (X == Y) {
2112     // Remove a binop and the shuffle by rearranging the constant:
2113     // shuffle (op V, C0), (op V, C1), M --> op V, C'
2114     // shuffle (op C0, V), (op C1, V), M --> op C', V
2115     V = X;
2116   } else {
2117     // If there are 2 different variable operands, we must create a new shuffle
2118     // (select) first, so check uses to ensure that we don't end up with more
2119     // instructions than we started with.
2120     if (!B0->hasOneUse() && !B1->hasOneUse())
2121       return nullptr;
2122 
2123     // If we use the original shuffle mask and op1 is *variable*, we would be
2124     // putting an undef into operand 1 of div/rem/shift. This is either UB or
2125     // poison. We do not have to guard against UB when *constants* are op1
2126     // because safe constants guarantee that we do not overflow sdiv/srem (and
2127     // there's no danger for other opcodes).
2128     // TODO: To allow this case, create a new shuffle mask with no undefs.
2129     if (MightCreatePoisonOrUB && !ConstantsAreOp1)
2130       return nullptr;
2131 
2132     // Note: In general, we do not create new shuffles in InstCombine because we
2133     // do not know if a target can lower an arbitrary shuffle optimally. In this
2134     // case, the shuffle uses the existing mask, so there is no additional risk.
2135 
2136     // Select the variable vectors first, then perform the binop:
2137     // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C'
2138     // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M)
2139     V = Builder.CreateShuffleVector(X, Y, Mask);
2140   }
2141 
2142   Value *NewBO = ConstantsAreOp1 ? Builder.CreateBinOp(BOpc, V, NewC) :
2143                                    Builder.CreateBinOp(BOpc, NewC, V);
2144 
2145   // Flags are intersected from the 2 source binops. But there are 2 exceptions:
2146   // 1. If we changed an opcode, poison conditions might have changed.
2147   // 2. If the shuffle had undef mask elements, the new binop might have undefs
2148   //    where the original code did not. But if we already made a safe constant,
2149   //    then there's no danger.
2150   if (auto *NewI = dyn_cast<Instruction>(NewBO)) {
2151     NewI->copyIRFlags(B0);
2152     NewI->andIRFlags(B1);
2153     if (DropNSW)
2154       NewI->setHasNoSignedWrap(false);
2155     if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB)
2156       NewI->dropPoisonGeneratingFlags();
2157   }
2158   return replaceInstUsesWith(Shuf, NewBO);
2159 }
2160 
2161 /// Convert a narrowing shuffle of a bitcasted vector into a vector truncate.
2162 /// Example (little endian):
2163 /// shuf (bitcast <4 x i16> X to <8 x i8>), <0, 2, 4, 6> --> trunc X to <4 x i8>
2164 static Instruction *foldTruncShuffle(ShuffleVectorInst &Shuf,
2165                                      bool IsBigEndian) {
2166   // This must be a bitcasted shuffle of 1 vector integer operand.
2167   Type *DestType = Shuf.getType();
2168   Value *X;
2169   if (!match(Shuf.getOperand(0), m_BitCast(m_Value(X))) ||
2170       !match(Shuf.getOperand(1), m_Undef()) || !DestType->isIntOrIntVectorTy())
2171     return nullptr;
2172 
2173   // The source type must have the same number of elements as the shuffle,
2174   // and the source element type must be larger than the shuffle element type.
2175   Type *SrcType = X->getType();
2176   if (!SrcType->isVectorTy() || !SrcType->isIntOrIntVectorTy() ||
2177       cast<FixedVectorType>(SrcType)->getNumElements() !=
2178           cast<FixedVectorType>(DestType)->getNumElements() ||
2179       SrcType->getScalarSizeInBits() % DestType->getScalarSizeInBits() != 0)
2180     return nullptr;
2181 
2182   assert(Shuf.changesLength() && !Shuf.increasesLength() &&
2183          "Expected a shuffle that decreases length");
2184 
2185   // Last, check that the mask chooses the correct low bits for each narrow
2186   // element in the result.
2187   uint64_t TruncRatio =
2188       SrcType->getScalarSizeInBits() / DestType->getScalarSizeInBits();
2189   ArrayRef<int> Mask = Shuf.getShuffleMask();
2190   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
2191     if (Mask[i] == UndefMaskElem)
2192       continue;
2193     uint64_t LSBIndex = IsBigEndian ? (i + 1) * TruncRatio - 1 : i * TruncRatio;
2194     assert(LSBIndex <= INT32_MAX && "Overflowed 32-bits");
2195     if (Mask[i] != (int)LSBIndex)
2196       return nullptr;
2197   }
2198 
2199   return new TruncInst(X, DestType);
2200 }
2201 
2202 /// Match a shuffle-select-shuffle pattern where the shuffles are widening and
2203 /// narrowing (concatenating with undef and extracting back to the original
2204 /// length). This allows replacing the wide select with a narrow select.
2205 static Instruction *narrowVectorSelect(ShuffleVectorInst &Shuf,
2206                                        InstCombiner::BuilderTy &Builder) {
2207   // This must be a narrowing identity shuffle. It extracts the 1st N elements
2208   // of the 1st vector operand of a shuffle.
2209   if (!match(Shuf.getOperand(1), m_Undef()) || !Shuf.isIdentityWithExtract())
2210     return nullptr;
2211 
2212   // The vector being shuffled must be a vector select that we can eliminate.
2213   // TODO: The one-use requirement could be eased if X and/or Y are constants.
2214   Value *Cond, *X, *Y;
2215   if (!match(Shuf.getOperand(0),
2216              m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))))
2217     return nullptr;
2218 
2219   // We need a narrow condition value. It must be extended with undef elements
2220   // and have the same number of elements as this shuffle.
2221   unsigned NarrowNumElts =
2222       cast<FixedVectorType>(Shuf.getType())->getNumElements();
2223   Value *NarrowCond;
2224   if (!match(Cond, m_OneUse(m_Shuffle(m_Value(NarrowCond), m_Undef()))) ||
2225       cast<FixedVectorType>(NarrowCond->getType())->getNumElements() !=
2226           NarrowNumElts ||
2227       !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding())
2228     return nullptr;
2229 
2230   // shuf (sel (shuf NarrowCond, undef, WideMask), X, Y), undef, NarrowMask) -->
2231   // sel NarrowCond, (shuf X, undef, NarrowMask), (shuf Y, undef, NarrowMask)
2232   Value *NarrowX = Builder.CreateShuffleVector(X, Shuf.getShuffleMask());
2233   Value *NarrowY = Builder.CreateShuffleVector(Y, Shuf.getShuffleMask());
2234   return SelectInst::Create(NarrowCond, NarrowX, NarrowY);
2235 }
2236 
2237 /// Try to fold an extract subvector operation.
2238 static Instruction *foldIdentityExtractShuffle(ShuffleVectorInst &Shuf) {
2239   Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2240   if (!Shuf.isIdentityWithExtract() || !match(Op1, m_Undef()))
2241     return nullptr;
2242 
2243   // Check if we are extracting all bits of an inserted scalar:
2244   // extract-subvec (bitcast (inselt ?, X, 0) --> bitcast X to subvec type
2245   Value *X;
2246   if (match(Op0, m_BitCast(m_InsertElt(m_Value(), m_Value(X), m_Zero()))) &&
2247       X->getType()->getPrimitiveSizeInBits() ==
2248           Shuf.getType()->getPrimitiveSizeInBits())
2249     return new BitCastInst(X, Shuf.getType());
2250 
2251   // Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask.
2252   Value *Y;
2253   ArrayRef<int> Mask;
2254   if (!match(Op0, m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask))))
2255     return nullptr;
2256 
2257   // Be conservative with shuffle transforms. If we can't kill the 1st shuffle,
2258   // then combining may result in worse codegen.
2259   if (!Op0->hasOneUse())
2260     return nullptr;
2261 
2262   // We are extracting a subvector from a shuffle. Remove excess elements from
2263   // the 1st shuffle mask to eliminate the extract.
2264   //
2265   // This transform is conservatively limited to identity extracts because we do
2266   // not allow arbitrary shuffle mask creation as a target-independent transform
2267   // (because we can't guarantee that will lower efficiently).
2268   //
2269   // If the extracting shuffle has an undef mask element, it transfers to the
2270   // new shuffle mask. Otherwise, copy the original mask element. Example:
2271   //   shuf (shuf X, Y, <C0, C1, C2, undef, C4>), undef, <0, undef, 2, 3> -->
2272   //   shuf X, Y, <C0, undef, C2, undef>
2273   unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
2274   SmallVector<int, 16> NewMask(NumElts);
2275   assert(NumElts < Mask.size() &&
2276          "Identity with extract must have less elements than its inputs");
2277 
2278   for (unsigned i = 0; i != NumElts; ++i) {
2279     int ExtractMaskElt = Shuf.getMaskValue(i);
2280     int MaskElt = Mask[i];
2281     NewMask[i] = ExtractMaskElt == UndefMaskElem ? ExtractMaskElt : MaskElt;
2282   }
2283   return new ShuffleVectorInst(X, Y, NewMask);
2284 }
2285 
2286 /// Try to replace a shuffle with an insertelement or try to replace a shuffle
2287 /// operand with the operand of an insertelement.
2288 static Instruction *foldShuffleWithInsert(ShuffleVectorInst &Shuf,
2289                                           InstCombinerImpl &IC) {
2290   Value *V0 = Shuf.getOperand(0), *V1 = Shuf.getOperand(1);
2291   SmallVector<int, 16> Mask;
2292   Shuf.getShuffleMask(Mask);
2293 
2294   int NumElts = Mask.size();
2295   int InpNumElts = cast<FixedVectorType>(V0->getType())->getNumElements();
2296 
2297   // This is a specialization of a fold in SimplifyDemandedVectorElts. We may
2298   // not be able to handle it there if the insertelement has >1 use.
2299   // If the shuffle has an insertelement operand but does not choose the
2300   // inserted scalar element from that value, then we can replace that shuffle
2301   // operand with the source vector of the insertelement.
2302   Value *X;
2303   uint64_t IdxC;
2304   if (match(V0, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
2305     // shuf (inselt X, ?, IdxC), ?, Mask --> shuf X, ?, Mask
2306     if (!is_contained(Mask, (int)IdxC))
2307       return IC.replaceOperand(Shuf, 0, X);
2308   }
2309   if (match(V1, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
2310     // Offset the index constant by the vector width because we are checking for
2311     // accesses to the 2nd vector input of the shuffle.
2312     IdxC += InpNumElts;
2313     // shuf ?, (inselt X, ?, IdxC), Mask --> shuf ?, X, Mask
2314     if (!is_contained(Mask, (int)IdxC))
2315       return IC.replaceOperand(Shuf, 1, X);
2316   }
2317   // For the rest of the transform, the shuffle must not change vector sizes.
2318   // TODO: This restriction could be removed if the insert has only one use
2319   //       (because the transform would require a new length-changing shuffle).
2320   if (NumElts != InpNumElts)
2321     return nullptr;
2322 
2323   // shuffle (insert ?, Scalar, IndexC), V1, Mask --> insert V1, Scalar, IndexC'
2324   auto isShufflingScalarIntoOp1 = [&](Value *&Scalar, ConstantInt *&IndexC) {
2325     // We need an insertelement with a constant index.
2326     if (!match(V0, m_InsertElt(m_Value(), m_Value(Scalar),
2327                                m_ConstantInt(IndexC))))
2328       return false;
2329 
2330     // Test the shuffle mask to see if it splices the inserted scalar into the
2331     // operand 1 vector of the shuffle.
2332     int NewInsIndex = -1;
2333     for (int i = 0; i != NumElts; ++i) {
2334       // Ignore undef mask elements.
2335       if (Mask[i] == -1)
2336         continue;
2337 
2338       // The shuffle takes elements of operand 1 without lane changes.
2339       if (Mask[i] == NumElts + i)
2340         continue;
2341 
2342       // The shuffle must choose the inserted scalar exactly once.
2343       if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue())
2344         return false;
2345 
2346       // The shuffle is placing the inserted scalar into element i.
2347       NewInsIndex = i;
2348     }
2349 
2350     assert(NewInsIndex != -1 && "Did not fold shuffle with unused operand?");
2351 
2352     // Index is updated to the potentially translated insertion lane.
2353     IndexC = ConstantInt::get(IndexC->getType(), NewInsIndex);
2354     return true;
2355   };
2356 
2357   // If the shuffle is unnecessary, insert the scalar operand directly into
2358   // operand 1 of the shuffle. Example:
2359   // shuffle (insert ?, S, 1), V1, <1, 5, 6, 7> --> insert V1, S, 0
2360   Value *Scalar;
2361   ConstantInt *IndexC;
2362   if (isShufflingScalarIntoOp1(Scalar, IndexC))
2363     return InsertElementInst::Create(V1, Scalar, IndexC);
2364 
2365   // Try again after commuting shuffle. Example:
2366   // shuffle V0, (insert ?, S, 0), <0, 1, 2, 4> -->
2367   // shuffle (insert ?, S, 0), V0, <4, 5, 6, 0> --> insert V0, S, 3
2368   std::swap(V0, V1);
2369   ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
2370   if (isShufflingScalarIntoOp1(Scalar, IndexC))
2371     return InsertElementInst::Create(V1, Scalar, IndexC);
2372 
2373   return nullptr;
2374 }
2375 
2376 static Instruction *foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf) {
2377   // Match the operands as identity with padding (also known as concatenation
2378   // with undef) shuffles of the same source type. The backend is expected to
2379   // recreate these concatenations from a shuffle of narrow operands.
2380   auto *Shuffle0 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(0));
2381   auto *Shuffle1 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(1));
2382   if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() ||
2383       !Shuffle1 || !Shuffle1->isIdentityWithPadding())
2384     return nullptr;
2385 
2386   // We limit this transform to power-of-2 types because we expect that the
2387   // backend can convert the simplified IR patterns to identical nodes as the
2388   // original IR.
2389   // TODO: If we can verify the same behavior for arbitrary types, the
2390   //       power-of-2 checks can be removed.
2391   Value *X = Shuffle0->getOperand(0);
2392   Value *Y = Shuffle1->getOperand(0);
2393   if (X->getType() != Y->getType() ||
2394       !isPowerOf2_32(cast<FixedVectorType>(Shuf.getType())->getNumElements()) ||
2395       !isPowerOf2_32(
2396           cast<FixedVectorType>(Shuffle0->getType())->getNumElements()) ||
2397       !isPowerOf2_32(cast<FixedVectorType>(X->getType())->getNumElements()) ||
2398       match(X, m_Undef()) || match(Y, m_Undef()))
2399     return nullptr;
2400   assert(match(Shuffle0->getOperand(1), m_Undef()) &&
2401          match(Shuffle1->getOperand(1), m_Undef()) &&
2402          "Unexpected operand for identity shuffle");
2403 
2404   // This is a shuffle of 2 widening shuffles. We can shuffle the narrow source
2405   // operands directly by adjusting the shuffle mask to account for the narrower
2406   // types:
2407   // shuf (widen X), (widen Y), Mask --> shuf X, Y, Mask'
2408   int NarrowElts = cast<FixedVectorType>(X->getType())->getNumElements();
2409   int WideElts = cast<FixedVectorType>(Shuffle0->getType())->getNumElements();
2410   assert(WideElts > NarrowElts && "Unexpected types for identity with padding");
2411 
2412   ArrayRef<int> Mask = Shuf.getShuffleMask();
2413   SmallVector<int, 16> NewMask(Mask.size(), -1);
2414   for (int i = 0, e = Mask.size(); i != e; ++i) {
2415     if (Mask[i] == -1)
2416       continue;
2417 
2418     // If this shuffle is choosing an undef element from 1 of the sources, that
2419     // element is undef.
2420     if (Mask[i] < WideElts) {
2421       if (Shuffle0->getMaskValue(Mask[i]) == -1)
2422         continue;
2423     } else {
2424       if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1)
2425         continue;
2426     }
2427 
2428     // If this shuffle is choosing from the 1st narrow op, the mask element is
2429     // the same. If this shuffle is choosing from the 2nd narrow op, the mask
2430     // element is offset down to adjust for the narrow vector widths.
2431     if (Mask[i] < WideElts) {
2432       assert(Mask[i] < NarrowElts && "Unexpected shuffle mask");
2433       NewMask[i] = Mask[i];
2434     } else {
2435       assert(Mask[i] < (WideElts + NarrowElts) && "Unexpected shuffle mask");
2436       NewMask[i] = Mask[i] - (WideElts - NarrowElts);
2437     }
2438   }
2439   return new ShuffleVectorInst(X, Y, NewMask);
2440 }
2441 
2442 Instruction *InstCombinerImpl::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
2443   Value *LHS = SVI.getOperand(0);
2444   Value *RHS = SVI.getOperand(1);
2445   SimplifyQuery ShufQuery = SQ.getWithInstruction(&SVI);
2446   if (auto *V = SimplifyShuffleVectorInst(LHS, RHS, SVI.getShuffleMask(),
2447                                           SVI.getType(), ShufQuery))
2448     return replaceInstUsesWith(SVI, V);
2449 
2450   // Bail out for scalable vectors
2451   if (isa<ScalableVectorType>(LHS->getType()))
2452     return nullptr;
2453 
2454   unsigned VWidth = cast<FixedVectorType>(SVI.getType())->getNumElements();
2455   unsigned LHSWidth = cast<FixedVectorType>(LHS->getType())->getNumElements();
2456 
2457   // shuffle (bitcast X), (bitcast Y), Mask --> bitcast (shuffle X, Y, Mask)
2458   //
2459   // if X and Y are of the same (vector) type, and the element size is not
2460   // changed by the bitcasts, we can distribute the bitcasts through the
2461   // shuffle, hopefully reducing the number of instructions. We make sure that
2462   // at least one bitcast only has one use, so we don't *increase* the number of
2463   // instructions here.
2464   Value *X, *Y;
2465   if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_BitCast(m_Value(Y))) &&
2466       X->getType()->isVectorTy() && X->getType() == Y->getType() &&
2467       X->getType()->getScalarSizeInBits() ==
2468           SVI.getType()->getScalarSizeInBits() &&
2469       (LHS->hasOneUse() || RHS->hasOneUse())) {
2470     Value *V = Builder.CreateShuffleVector(X, Y, SVI.getShuffleMask(),
2471                                            SVI.getName() + ".uncasted");
2472     return new BitCastInst(V, SVI.getType());
2473   }
2474 
2475   ArrayRef<int> Mask = SVI.getShuffleMask();
2476   Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
2477 
2478   // Peek through a bitcasted shuffle operand by scaling the mask. If the
2479   // simulated shuffle can simplify, then this shuffle is unnecessary:
2480   // shuf (bitcast X), undef, Mask --> bitcast X'
2481   // TODO: This could be extended to allow length-changing shuffles.
2482   //       The transform might also be obsoleted if we allowed canonicalization
2483   //       of bitcasted shuffles.
2484   if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_Undef()) &&
2485       X->getType()->isVectorTy() && VWidth == LHSWidth) {
2486     // Try to create a scaled mask constant.
2487     auto *XType = cast<FixedVectorType>(X->getType());
2488     unsigned XNumElts = XType->getNumElements();
2489     SmallVector<int, 16> ScaledMask;
2490     if (XNumElts >= VWidth) {
2491       assert(XNumElts % VWidth == 0 && "Unexpected vector bitcast");
2492       narrowShuffleMaskElts(XNumElts / VWidth, Mask, ScaledMask);
2493     } else {
2494       assert(VWidth % XNumElts == 0 && "Unexpected vector bitcast");
2495       if (!widenShuffleMaskElts(VWidth / XNumElts, Mask, ScaledMask))
2496         ScaledMask.clear();
2497     }
2498     if (!ScaledMask.empty()) {
2499       // If the shuffled source vector simplifies, cast that value to this
2500       // shuffle's type.
2501       if (auto *V = SimplifyShuffleVectorInst(X, UndefValue::get(XType),
2502                                               ScaledMask, XType, ShufQuery))
2503         return BitCastInst::Create(Instruction::BitCast, V, SVI.getType());
2504     }
2505   }
2506 
2507   // shuffle x, x, mask --> shuffle x, undef, mask'
2508   if (LHS == RHS) {
2509     assert(!match(RHS, m_Undef()) &&
2510            "Shuffle with 2 undef ops not simplified?");
2511     return new ShuffleVectorInst(LHS, createUnaryMask(Mask, LHSWidth));
2512   }
2513 
2514   // shuffle undef, x, mask --> shuffle x, undef, mask'
2515   if (match(LHS, m_Undef())) {
2516     SVI.commute();
2517     return &SVI;
2518   }
2519 
2520   if (Instruction *I = canonicalizeInsertSplat(SVI, Builder))
2521     return I;
2522 
2523   if (Instruction *I = foldSelectShuffle(SVI))
2524     return I;
2525 
2526   if (Instruction *I = foldTruncShuffle(SVI, DL.isBigEndian()))
2527     return I;
2528 
2529   if (Instruction *I = narrowVectorSelect(SVI, Builder))
2530     return I;
2531 
2532   APInt UndefElts(VWidth, 0);
2533   APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
2534   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
2535     if (V != &SVI)
2536       return replaceInstUsesWith(SVI, V);
2537     return &SVI;
2538   }
2539 
2540   if (Instruction *I = foldIdentityExtractShuffle(SVI))
2541     return I;
2542 
2543   // These transforms have the potential to lose undef knowledge, so they are
2544   // intentionally placed after SimplifyDemandedVectorElts().
2545   if (Instruction *I = foldShuffleWithInsert(SVI, *this))
2546     return I;
2547   if (Instruction *I = foldIdentityPaddedShuffles(SVI))
2548     return I;
2549 
2550   if (match(RHS, m_Undef()) && canEvaluateShuffled(LHS, Mask)) {
2551     Value *V = evaluateInDifferentElementOrder(LHS, Mask);
2552     return replaceInstUsesWith(SVI, V);
2553   }
2554 
2555   // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
2556   // a non-vector type. We can instead bitcast the original vector followed by
2557   // an extract of the desired element:
2558   //
2559   //   %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
2560   //                         <4 x i32> <i32 0, i32 1, i32 2, i32 3>
2561   //   %1 = bitcast <4 x i8> %sroa to i32
2562   // Becomes:
2563   //   %bc = bitcast <16 x i8> %in to <4 x i32>
2564   //   %ext = extractelement <4 x i32> %bc, i32 0
2565   //
2566   // If the shuffle is extracting a contiguous range of values from the input
2567   // vector then each use which is a bitcast of the extracted size can be
2568   // replaced. This will work if the vector types are compatible, and the begin
2569   // index is aligned to a value in the casted vector type. If the begin index
2570   // isn't aligned then we can shuffle the original vector (keeping the same
2571   // vector type) before extracting.
2572   //
2573   // This code will bail out if the target type is fundamentally incompatible
2574   // with vectors of the source type.
2575   //
2576   // Example of <16 x i8>, target type i32:
2577   // Index range [4,8):         v-----------v Will work.
2578   //                +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
2579   //     <16 x i8>: |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
2580   //     <4 x i32>: |           |           |           |           |
2581   //                +-----------+-----------+-----------+-----------+
2582   // Index range [6,10):              ^-----------^ Needs an extra shuffle.
2583   // Target type i40:           ^--------------^ Won't work, bail.
2584   bool MadeChange = false;
2585   if (isShuffleExtractingFromLHS(SVI, Mask)) {
2586     Value *V = LHS;
2587     unsigned MaskElems = Mask.size();
2588     auto *SrcTy = cast<FixedVectorType>(V->getType());
2589     unsigned VecBitWidth = SrcTy->getPrimitiveSizeInBits().getFixedSize();
2590     unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
2591     assert(SrcElemBitWidth && "vector elements must have a bitwidth");
2592     unsigned SrcNumElems = SrcTy->getNumElements();
2593     SmallVector<BitCastInst *, 8> BCs;
2594     DenseMap<Type *, Value *> NewBCs;
2595     for (User *U : SVI.users())
2596       if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
2597         if (!BC->use_empty())
2598           // Only visit bitcasts that weren't previously handled.
2599           BCs.push_back(BC);
2600     for (BitCastInst *BC : BCs) {
2601       unsigned BegIdx = Mask.front();
2602       Type *TgtTy = BC->getDestTy();
2603       unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
2604       if (!TgtElemBitWidth)
2605         continue;
2606       unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
2607       bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
2608       bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
2609       if (!VecBitWidthsEqual)
2610         continue;
2611       if (!VectorType::isValidElementType(TgtTy))
2612         continue;
2613       auto *CastSrcTy = FixedVectorType::get(TgtTy, TgtNumElems);
2614       if (!BegIsAligned) {
2615         // Shuffle the input so [0,NumElements) contains the output, and
2616         // [NumElems,SrcNumElems) is undef.
2617         SmallVector<int, 16> ShuffleMask(SrcNumElems, -1);
2618         for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
2619           ShuffleMask[I] = Idx;
2620         V = Builder.CreateShuffleVector(V, ShuffleMask,
2621                                         SVI.getName() + ".extract");
2622         BegIdx = 0;
2623       }
2624       unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
2625       assert(SrcElemsPerTgtElem);
2626       BegIdx /= SrcElemsPerTgtElem;
2627       bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
2628       auto *NewBC =
2629           BCAlreadyExists
2630               ? NewBCs[CastSrcTy]
2631               : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
2632       if (!BCAlreadyExists)
2633         NewBCs[CastSrcTy] = NewBC;
2634       auto *Ext = Builder.CreateExtractElement(
2635           NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
2636       // The shufflevector isn't being replaced: the bitcast that used it
2637       // is. InstCombine will visit the newly-created instructions.
2638       replaceInstUsesWith(*BC, Ext);
2639       MadeChange = true;
2640     }
2641   }
2642 
2643   // If the LHS is a shufflevector itself, see if we can combine it with this
2644   // one without producing an unusual shuffle.
2645   // Cases that might be simplified:
2646   // 1.
2647   // x1=shuffle(v1,v2,mask1)
2648   //  x=shuffle(x1,undef,mask)
2649   //        ==>
2650   //  x=shuffle(v1,undef,newMask)
2651   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
2652   // 2.
2653   // x1=shuffle(v1,undef,mask1)
2654   //  x=shuffle(x1,x2,mask)
2655   // where v1.size() == mask1.size()
2656   //        ==>
2657   //  x=shuffle(v1,x2,newMask)
2658   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
2659   // 3.
2660   // x2=shuffle(v2,undef,mask2)
2661   //  x=shuffle(x1,x2,mask)
2662   // where v2.size() == mask2.size()
2663   //        ==>
2664   //  x=shuffle(x1,v2,newMask)
2665   // newMask[i] = (mask[i] < x1.size())
2666   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
2667   // 4.
2668   // x1=shuffle(v1,undef,mask1)
2669   // x2=shuffle(v2,undef,mask2)
2670   //  x=shuffle(x1,x2,mask)
2671   // where v1.size() == v2.size()
2672   //        ==>
2673   //  x=shuffle(v1,v2,newMask)
2674   // newMask[i] = (mask[i] < x1.size())
2675   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
2676   //
2677   // Here we are really conservative:
2678   // we are absolutely afraid of producing a shuffle mask not in the input
2679   // program, because the code gen may not be smart enough to turn a merged
2680   // shuffle into two specific shuffles: it may produce worse code.  As such,
2681   // we only merge two shuffles if the result is either a splat or one of the
2682   // input shuffle masks.  In this case, merging the shuffles just removes
2683   // one instruction, which we know is safe.  This is good for things like
2684   // turning: (splat(splat)) -> splat, or
2685   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
2686   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
2687   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
2688   if (LHSShuffle)
2689     if (!match(LHSShuffle->getOperand(1), m_Undef()) && !match(RHS, m_Undef()))
2690       LHSShuffle = nullptr;
2691   if (RHSShuffle)
2692     if (!match(RHSShuffle->getOperand(1), m_Undef()))
2693       RHSShuffle = nullptr;
2694   if (!LHSShuffle && !RHSShuffle)
2695     return MadeChange ? &SVI : nullptr;
2696 
2697   Value* LHSOp0 = nullptr;
2698   Value* LHSOp1 = nullptr;
2699   Value* RHSOp0 = nullptr;
2700   unsigned LHSOp0Width = 0;
2701   unsigned RHSOp0Width = 0;
2702   if (LHSShuffle) {
2703     LHSOp0 = LHSShuffle->getOperand(0);
2704     LHSOp1 = LHSShuffle->getOperand(1);
2705     LHSOp0Width = cast<FixedVectorType>(LHSOp0->getType())->getNumElements();
2706   }
2707   if (RHSShuffle) {
2708     RHSOp0 = RHSShuffle->getOperand(0);
2709     RHSOp0Width = cast<FixedVectorType>(RHSOp0->getType())->getNumElements();
2710   }
2711   Value* newLHS = LHS;
2712   Value* newRHS = RHS;
2713   if (LHSShuffle) {
2714     // case 1
2715     if (match(RHS, m_Undef())) {
2716       newLHS = LHSOp0;
2717       newRHS = LHSOp1;
2718     }
2719     // case 2 or 4
2720     else if (LHSOp0Width == LHSWidth) {
2721       newLHS = LHSOp0;
2722     }
2723   }
2724   // case 3 or 4
2725   if (RHSShuffle && RHSOp0Width == LHSWidth) {
2726     newRHS = RHSOp0;
2727   }
2728   // case 4
2729   if (LHSOp0 == RHSOp0) {
2730     newLHS = LHSOp0;
2731     newRHS = nullptr;
2732   }
2733 
2734   if (newLHS == LHS && newRHS == RHS)
2735     return MadeChange ? &SVI : nullptr;
2736 
2737   ArrayRef<int> LHSMask;
2738   ArrayRef<int> RHSMask;
2739   if (newLHS != LHS)
2740     LHSMask = LHSShuffle->getShuffleMask();
2741   if (RHSShuffle && newRHS != RHS)
2742     RHSMask = RHSShuffle->getShuffleMask();
2743 
2744   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
2745   SmallVector<int, 16> newMask;
2746   bool isSplat = true;
2747   int SplatElt = -1;
2748   // Create a new mask for the new ShuffleVectorInst so that the new
2749   // ShuffleVectorInst is equivalent to the original one.
2750   for (unsigned i = 0; i < VWidth; ++i) {
2751     int eltMask;
2752     if (Mask[i] < 0) {
2753       // This element is an undef value.
2754       eltMask = -1;
2755     } else if (Mask[i] < (int)LHSWidth) {
2756       // This element is from left hand side vector operand.
2757       //
2758       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
2759       // new mask value for the element.
2760       if (newLHS != LHS) {
2761         eltMask = LHSMask[Mask[i]];
2762         // If the value selected is an undef value, explicitly specify it
2763         // with a -1 mask value.
2764         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
2765           eltMask = -1;
2766       } else
2767         eltMask = Mask[i];
2768     } else {
2769       // This element is from right hand side vector operand
2770       //
2771       // If the value selected is an undef value, explicitly specify it
2772       // with a -1 mask value. (case 1)
2773       if (match(RHS, m_Undef()))
2774         eltMask = -1;
2775       // If RHS is going to be replaced (case 3 or 4), calculate the
2776       // new mask value for the element.
2777       else if (newRHS != RHS) {
2778         eltMask = RHSMask[Mask[i]-LHSWidth];
2779         // If the value selected is an undef value, explicitly specify it
2780         // with a -1 mask value.
2781         if (eltMask >= (int)RHSOp0Width) {
2782           assert(match(RHSShuffle->getOperand(1), m_Undef()) &&
2783                  "should have been check above");
2784           eltMask = -1;
2785         }
2786       } else
2787         eltMask = Mask[i]-LHSWidth;
2788 
2789       // If LHS's width is changed, shift the mask value accordingly.
2790       // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any
2791       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
2792       // If newRHS == newLHS, we want to remap any references from newRHS to
2793       // newLHS so that we can properly identify splats that may occur due to
2794       // obfuscation across the two vectors.
2795       if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
2796         eltMask += newLHSWidth;
2797     }
2798 
2799     // Check if this could still be a splat.
2800     if (eltMask >= 0) {
2801       if (SplatElt >= 0 && SplatElt != eltMask)
2802         isSplat = false;
2803       SplatElt = eltMask;
2804     }
2805 
2806     newMask.push_back(eltMask);
2807   }
2808 
2809   // If the result mask is equal to one of the original shuffle masks,
2810   // or is a splat, do the replacement.
2811   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
2812     if (!newRHS)
2813       newRHS = UndefValue::get(newLHS->getType());
2814     return new ShuffleVectorInst(newLHS, newRHS, newMask);
2815   }
2816 
2817   return MadeChange ? &SVI : nullptr;
2818 }
2819