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