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