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