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