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