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