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