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