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