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