1 //===- InstCombineVectorOps.cpp -------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements instcombine for ExtractElement, InsertElement and
11 // ShuffleVector.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "InstCombineInternal.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/Analysis/InstructionSimplify.h"
18 #include "llvm/Analysis/VectorUtils.h"
19 #include "llvm/IR/PatternMatch.h"
20 using namespace llvm;
21 using namespace PatternMatch;
22 
23 #define DEBUG_TYPE "instcombine"
24 
25 /// Return true if the value is cheaper to scalarize than it is to leave as a
26 /// vector operation. isConstant indicates whether we're extracting one known
27 /// element. If false we're extracting a variable index.
28 static bool cheapToScalarize(Value *V, bool isConstant) {
29   if (Constant *C = dyn_cast<Constant>(V)) {
30     if (isConstant) return true;
31 
32     // If all elts are the same, we can extract it and use any of the values.
33     if (Constant *Op0 = C->getAggregateElement(0U)) {
34       for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
35            ++i)
36         if (C->getAggregateElement(i) != Op0)
37           return false;
38       return true;
39     }
40   }
41   Instruction *I = dyn_cast<Instruction>(V);
42   if (!I) return false;
43 
44   // Insert element gets simplified to the inserted element or is deleted if
45   // this is constant idx extract element and its a constant idx insertelt.
46   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
47       isa<ConstantInt>(I->getOperand(2)))
48     return true;
49   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
50     return true;
51   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
52     if (BO->hasOneUse() &&
53         (cheapToScalarize(BO->getOperand(0), isConstant) ||
54          cheapToScalarize(BO->getOperand(1), isConstant)))
55       return true;
56   if (CmpInst *CI = dyn_cast<CmpInst>(I))
57     if (CI->hasOneUse() &&
58         (cheapToScalarize(CI->getOperand(0), isConstant) ||
59          cheapToScalarize(CI->getOperand(1), isConstant)))
60       return true;
61 
62   return false;
63 }
64 
65 // If we have a PHI node with a vector type that has only 2 uses: feed
66 // itself and be an operand of extractelement at a constant location,
67 // try to replace the PHI of the vector type with a PHI of a scalar type.
68 Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
69   // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
70   if (!PN->hasNUses(2))
71     return nullptr;
72 
73   // If so, it's known at this point that one operand is PHI and the other is
74   // an extractelement node. Find the PHI user that is not the extractelement
75   // node.
76   auto iu = PN->user_begin();
77   Instruction *PHIUser = dyn_cast<Instruction>(*iu);
78   if (PHIUser == cast<Instruction>(&EI))
79     PHIUser = cast<Instruction>(*(++iu));
80 
81   // Verify that this PHI user has one use, which is the PHI itself,
82   // and that it is a binary operation which is cheap to scalarize.
83   // otherwise return NULL.
84   if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
85       !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true))
86     return nullptr;
87 
88   // Create a scalar PHI node that will replace the vector PHI node
89   // just before the current PHI node.
90   PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
91       PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
92   // Scalarize each PHI operand.
93   for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
94     Value *PHIInVal = PN->getIncomingValue(i);
95     BasicBlock *inBB = PN->getIncomingBlock(i);
96     Value *Elt = EI.getIndexOperand();
97     // If the operand is the PHI induction variable:
98     if (PHIInVal == PHIUser) {
99       // Scalarize the binary operation. Its first operand is the
100       // scalar PHI, and the second operand is extracted from the other
101       // vector operand.
102       BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
103       unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
104       Value *Op = InsertNewInstWith(
105           ExtractElementInst::Create(B0->getOperand(opId), Elt,
106                                      B0->getOperand(opId)->getName() + ".Elt"),
107           *B0);
108       Value *newPHIUser = InsertNewInstWith(
109           BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
110                                                 scalarPHI, Op, B0), *B0);
111       scalarPHI->addIncoming(newPHIUser, inBB);
112     } else {
113       // Scalarize PHI input:
114       Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
115       // Insert the new instruction into the predecessor basic block.
116       Instruction *pos = dyn_cast<Instruction>(PHIInVal);
117       BasicBlock::iterator InsertPos;
118       if (pos && !isa<PHINode>(pos)) {
119         InsertPos = ++pos->getIterator();
120       } else {
121         InsertPos = inBB->getFirstInsertionPt();
122       }
123 
124       InsertNewInstWith(newEI, *InsertPos);
125 
126       scalarPHI->addIncoming(newEI, inBB);
127     }
128   }
129   return replaceInstUsesWith(EI, scalarPHI);
130 }
131 
132 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
133   if (Value *V = SimplifyExtractElementInst(
134           EI.getVectorOperand(), EI.getIndexOperand(), DL, TLI, DT, AC))
135     return replaceInstUsesWith(EI, V);
136 
137   // If vector val is constant with all elements the same, replace EI with
138   // that element.  We handle a known element # below.
139   if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
140     if (cheapToScalarize(C, false))
141       return replaceInstUsesWith(EI, C->getAggregateElement(0U));
142 
143   // If extracting a specified index from the vector, see if we can recursively
144   // find a previously computed scalar that was inserted into the vector.
145   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
146     unsigned IndexVal = IdxC->getZExtValue();
147     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
148 
149     // InstSimplify handles cases where the index is invalid.
150     assert(IndexVal < VectorWidth);
151 
152     // This instruction only demands the single element from the input vector.
153     // If the input vector has a single use, simplify it based on this use
154     // property.
155     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
156       APInt UndefElts(VectorWidth, 0);
157       APInt DemandedMask(VectorWidth, 0);
158       DemandedMask.setBit(IndexVal);
159       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
160                                                 UndefElts)) {
161         EI.setOperand(0, V);
162         return &EI;
163       }
164     }
165 
166     // If this extractelement is directly using a bitcast from a vector of
167     // the same number of elements, see if we can find the source element from
168     // it.  In this case, we will end up needing to bitcast the scalars.
169     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
170       if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
171         if (VT->getNumElements() == VectorWidth)
172           if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal))
173             return new BitCastInst(Elt, EI.getType());
174     }
175 
176     // If there's a vector PHI feeding a scalar use through this extractelement
177     // instruction, try to scalarize the PHI.
178     if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
179       Instruction *scalarPHI = scalarizePHI(EI, PN);
180       if (scalarPHI)
181         return scalarPHI;
182     }
183   }
184 
185   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
186     // Push extractelement into predecessor operation if legal and
187     // profitable to do so.
188     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
189       if (I->hasOneUse() &&
190           cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
191         Value *newEI0 =
192           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
193                                         EI.getName()+".lhs");
194         Value *newEI1 =
195           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
196                                         EI.getName()+".rhs");
197         return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(),
198                                                      newEI0, newEI1, BO);
199       }
200     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
201       // Extracting the inserted element?
202       if (IE->getOperand(2) == EI.getOperand(1))
203         return replaceInstUsesWith(EI, IE->getOperand(1));
204       // If the inserted and extracted elements are constants, they must not
205       // be the same value, extract from the pre-inserted value instead.
206       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
207         Worklist.AddValue(EI.getOperand(0));
208         EI.setOperand(0, IE->getOperand(0));
209         return &EI;
210       }
211     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
212       // If this is extracting an element from a shufflevector, figure out where
213       // it came from and extract from the appropriate input element instead.
214       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
215         int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
216         Value *Src;
217         unsigned LHSWidth =
218           SVI->getOperand(0)->getType()->getVectorNumElements();
219 
220         if (SrcIdx < 0)
221           return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
222         if (SrcIdx < (int)LHSWidth)
223           Src = SVI->getOperand(0);
224         else {
225           SrcIdx -= LHSWidth;
226           Src = SVI->getOperand(1);
227         }
228         Type *Int32Ty = Type::getInt32Ty(EI.getContext());
229         return ExtractElementInst::Create(Src,
230                                           ConstantInt::get(Int32Ty,
231                                                            SrcIdx, false));
232       }
233     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
234       // Canonicalize extractelement(cast) -> cast(extractelement).
235       // Bitcasts can change the number of vector elements, and they cost
236       // nothing.
237       if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
238         Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
239                                                   EI.getIndexOperand());
240         Worklist.AddValue(EE);
241         return CastInst::Create(CI->getOpcode(), EE, EI.getType());
242       }
243     } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
244       if (SI->hasOneUse()) {
245         // TODO: For a select on vectors, it might be useful to do this if it
246         // has multiple extractelement uses. For vector select, that seems to
247         // fight the vectorizer.
248 
249         // If we are extracting an element from a vector select or a select on
250         // vectors, create a select on the scalars extracted from the vector
251         // arguments.
252         Value *TrueVal = SI->getTrueValue();
253         Value *FalseVal = SI->getFalseValue();
254 
255         Value *Cond = SI->getCondition();
256         if (Cond->getType()->isVectorTy()) {
257           Cond = Builder->CreateExtractElement(Cond,
258                                                EI.getIndexOperand(),
259                                                Cond->getName() + ".elt");
260         }
261 
262         Value *V1Elem
263           = Builder->CreateExtractElement(TrueVal,
264                                           EI.getIndexOperand(),
265                                           TrueVal->getName() + ".elt");
266 
267         Value *V2Elem
268           = Builder->CreateExtractElement(FalseVal,
269                                           EI.getIndexOperand(),
270                                           FalseVal->getName() + ".elt");
271         return SelectInst::Create(Cond,
272                                   V1Elem,
273                                   V2Elem,
274                                   SI->getName() + ".elt");
275       }
276     }
277   }
278   return nullptr;
279 }
280 
281 /// If V is a shuffle of values that ONLY returns elements from either LHS or
282 /// RHS, return the shuffle mask and true. Otherwise, return false.
283 static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
284                                          SmallVectorImpl<Constant*> &Mask) {
285   assert(LHS->getType() == RHS->getType() &&
286          "Invalid CollectSingleShuffleElements");
287   unsigned NumElts = V->getType()->getVectorNumElements();
288 
289   if (isa<UndefValue>(V)) {
290     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
291     return true;
292   }
293 
294   if (V == LHS) {
295     for (unsigned i = 0; i != NumElts; ++i)
296       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
297     return true;
298   }
299 
300   if (V == RHS) {
301     for (unsigned i = 0; i != NumElts; ++i)
302       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
303                                       i+NumElts));
304     return true;
305   }
306 
307   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
308     // If this is an insert of an extract from some other vector, include it.
309     Value *VecOp    = IEI->getOperand(0);
310     Value *ScalarOp = IEI->getOperand(1);
311     Value *IdxOp    = IEI->getOperand(2);
312 
313     if (!isa<ConstantInt>(IdxOp))
314       return false;
315     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
316 
317     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
318       // We can handle this if the vector we are inserting into is
319       // transitively ok.
320       if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
321         // If so, update the mask to reflect the inserted undef.
322         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
323         return true;
324       }
325     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
326       if (isa<ConstantInt>(EI->getOperand(1))) {
327         unsigned ExtractedIdx =
328         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
329         unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
330 
331         // This must be extracting from either LHS or RHS.
332         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
333           // We can handle this if the vector we are inserting into is
334           // transitively ok.
335           if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
336             // If so, update the mask to reflect the inserted value.
337             if (EI->getOperand(0) == LHS) {
338               Mask[InsertedIdx % NumElts] =
339               ConstantInt::get(Type::getInt32Ty(V->getContext()),
340                                ExtractedIdx);
341             } else {
342               assert(EI->getOperand(0) == RHS);
343               Mask[InsertedIdx % NumElts] =
344               ConstantInt::get(Type::getInt32Ty(V->getContext()),
345                                ExtractedIdx + NumLHSElts);
346             }
347             return true;
348           }
349         }
350       }
351     }
352   }
353 
354   return false;
355 }
356 
357 /// If we have insertion into a vector that is wider than the vector that we
358 /// are extracting from, try to widen the source vector to allow a single
359 /// shufflevector to replace one or more insert/extract pairs.
360 static void replaceExtractElements(InsertElementInst *InsElt,
361                                    ExtractElementInst *ExtElt,
362                                    InstCombiner &IC) {
363   VectorType *InsVecType = InsElt->getType();
364   VectorType *ExtVecType = ExtElt->getVectorOperandType();
365   unsigned NumInsElts = InsVecType->getVectorNumElements();
366   unsigned NumExtElts = ExtVecType->getVectorNumElements();
367 
368   // The inserted-to vector must be wider than the extracted-from vector.
369   if (InsVecType->getElementType() != ExtVecType->getElementType() ||
370       NumExtElts >= NumInsElts)
371     return;
372 
373   // Create a shuffle mask to widen the extended-from vector using undefined
374   // values. The mask selects all of the values of the original vector followed
375   // by as many undefined values as needed to create a vector of the same length
376   // as the inserted-to vector.
377   SmallVector<Constant *, 16> ExtendMask;
378   IntegerType *IntType = Type::getInt32Ty(InsElt->getContext());
379   for (unsigned i = 0; i < NumExtElts; ++i)
380     ExtendMask.push_back(ConstantInt::get(IntType, i));
381   for (unsigned i = NumExtElts; i < NumInsElts; ++i)
382     ExtendMask.push_back(UndefValue::get(IntType));
383 
384   Value *ExtVecOp = ExtElt->getVectorOperand();
385   auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
386   BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
387                                    ? ExtVecOpInst->getParent()
388                                    : ExtElt->getParent();
389 
390   // TODO: This restriction matches the basic block check below when creating
391   // new extractelement instructions. If that limitation is removed, this one
392   // could also be removed. But for now, we just bail out to ensure that we
393   // will replace the extractelement instruction that is feeding our
394   // insertelement instruction. This allows the insertelement to then be
395   // replaced by a shufflevector. If the insertelement is not replaced, we can
396   // induce infinite looping because there's an optimization for extractelement
397   // that will delete our widening shuffle. This would trigger another attempt
398   // here to create that shuffle, and we spin forever.
399   if (InsertionBlock != InsElt->getParent())
400     return;
401 
402   auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
403                                         ConstantVector::get(ExtendMask));
404 
405   // Insert the new shuffle after the vector operand of the extract is defined
406   // (as long as it's not a PHI) or at the start of the basic block of the
407   // extract, so any subsequent extracts in the same basic block can use it.
408   // TODO: Insert before the earliest ExtractElementInst that is replaced.
409   if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
410     WideVec->insertAfter(ExtVecOpInst);
411   else
412     IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
413 
414   // Replace extracts from the original narrow vector with extracts from the new
415   // wide vector.
416   for (User *U : ExtVecOp->users()) {
417     ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
418     if (!OldExt || OldExt->getParent() != WideVec->getParent())
419       continue;
420     auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
421     NewExt->insertAfter(WideVec);
422     IC.replaceInstUsesWith(*OldExt, NewExt);
423   }
424 }
425 
426 /// We are building a shuffle to create V, which is a sequence of insertelement,
427 /// extractelement pairs. If PermittedRHS is set, then we must either use it or
428 /// not rely on the second vector source. Return a std::pair containing the
429 /// left and right vectors of the proposed shuffle (or 0), and set the Mask
430 /// parameter as required.
431 ///
432 /// Note: we intentionally don't try to fold earlier shuffles since they have
433 /// often been chosen carefully to be efficiently implementable on the target.
434 typedef std::pair<Value *, Value *> ShuffleOps;
435 
436 static ShuffleOps collectShuffleElements(Value *V,
437                                          SmallVectorImpl<Constant *> &Mask,
438                                          Value *PermittedRHS,
439                                          InstCombiner &IC) {
440   assert(V->getType()->isVectorTy() && "Invalid shuffle!");
441   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
442 
443   if (isa<UndefValue>(V)) {
444     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
445     return std::make_pair(
446         PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
447   }
448 
449   if (isa<ConstantAggregateZero>(V)) {
450     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
451     return std::make_pair(V, nullptr);
452   }
453 
454   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
455     // If this is an insert of an extract from some other vector, include it.
456     Value *VecOp    = IEI->getOperand(0);
457     Value *ScalarOp = IEI->getOperand(1);
458     Value *IdxOp    = IEI->getOperand(2);
459 
460     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
461       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
462         unsigned ExtractedIdx =
463           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
464         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
465 
466         // Either the extracted from or inserted into vector must be RHSVec,
467         // otherwise we'd end up with a shuffle of three inputs.
468         if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
469           Value *RHS = EI->getOperand(0);
470           ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
471           assert(LR.second == nullptr || LR.second == RHS);
472 
473           if (LR.first->getType() != RHS->getType()) {
474             // Although we are giving up for now, see if we can create extracts
475             // that match the inserts for another round of combining.
476             replaceExtractElements(IEI, EI, IC);
477 
478             // We tried our best, but we can't find anything compatible with RHS
479             // further up the chain. Return a trivial shuffle.
480             for (unsigned i = 0; i < NumElts; ++i)
481               Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
482             return std::make_pair(V, nullptr);
483           }
484 
485           unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
486           Mask[InsertedIdx % NumElts] =
487             ConstantInt::get(Type::getInt32Ty(V->getContext()),
488                              NumLHSElts+ExtractedIdx);
489           return std::make_pair(LR.first, RHS);
490         }
491 
492         if (VecOp == PermittedRHS) {
493           // We've gone as far as we can: anything on the other side of the
494           // extractelement will already have been converted into a shuffle.
495           unsigned NumLHSElts =
496               EI->getOperand(0)->getType()->getVectorNumElements();
497           for (unsigned i = 0; i != NumElts; ++i)
498             Mask.push_back(ConstantInt::get(
499                 Type::getInt32Ty(V->getContext()),
500                 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
501           return std::make_pair(EI->getOperand(0), PermittedRHS);
502         }
503 
504         // If this insertelement is a chain that comes from exactly these two
505         // vectors, return the vector and the effective shuffle.
506         if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
507             collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
508                                          Mask))
509           return std::make_pair(EI->getOperand(0), PermittedRHS);
510       }
511     }
512   }
513 
514   // Otherwise, we can't do anything fancy. Return an identity vector.
515   for (unsigned i = 0; i != NumElts; ++i)
516     Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
517   return std::make_pair(V, nullptr);
518 }
519 
520 /// Try to find redundant insertvalue instructions, like the following ones:
521 ///  %0 = insertvalue { i8, i32 } undef, i8 %x, 0
522 ///  %1 = insertvalue { i8, i32 } %0,    i8 %y, 0
523 /// Here the second instruction inserts values at the same indices, as the
524 /// first one, making the first one redundant.
525 /// It should be transformed to:
526 ///  %0 = insertvalue { i8, i32 } undef, i8 %y, 0
527 Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
528   bool IsRedundant = false;
529   ArrayRef<unsigned int> FirstIndices = I.getIndices();
530 
531   // If there is a chain of insertvalue instructions (each of them except the
532   // last one has only one use and it's another insertvalue insn from this
533   // chain), check if any of the 'children' uses the same indices as the first
534   // instruction. In this case, the first one is redundant.
535   Value *V = &I;
536   unsigned Depth = 0;
537   while (V->hasOneUse() && Depth < 10) {
538     User *U = V->user_back();
539     auto UserInsInst = dyn_cast<InsertValueInst>(U);
540     if (!UserInsInst || U->getOperand(0) != V)
541       break;
542     if (UserInsInst->getIndices() == FirstIndices) {
543       IsRedundant = true;
544       break;
545     }
546     V = UserInsInst;
547     Depth++;
548   }
549 
550   if (IsRedundant)
551     return replaceInstUsesWith(I, I.getOperand(0));
552   return nullptr;
553 }
554 
555 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
556   Value *VecOp    = IE.getOperand(0);
557   Value *ScalarOp = IE.getOperand(1);
558   Value *IdxOp    = IE.getOperand(2);
559 
560   // Inserting an undef or into an undefined place, remove this.
561   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
562     replaceInstUsesWith(IE, VecOp);
563 
564   // If the inserted element was extracted from some other vector, and if the
565   // indexes are constant, try to turn this into a shufflevector operation.
566   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
567     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
568       unsigned NumInsertVectorElts = IE.getType()->getNumElements();
569       unsigned NumExtractVectorElts =
570           EI->getOperand(0)->getType()->getVectorNumElements();
571       unsigned ExtractedIdx =
572         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
573       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
574 
575       if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
576         return replaceInstUsesWith(IE, VecOp);
577 
578       if (InsertedIdx >= NumInsertVectorElts)  // Out of range insert.
579         return replaceInstUsesWith(IE, UndefValue::get(IE.getType()));
580 
581       // If we are extracting a value from a vector, then inserting it right
582       // back into the same place, just use the input vector.
583       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
584         return replaceInstUsesWith(IE, VecOp);
585 
586       // If this insertelement isn't used by some other insertelement, turn it
587       // (and any insertelements it points to), into one big shuffle.
588       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
589         SmallVector<Constant*, 16> Mask;
590         ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
591 
592         // The proposed shuffle may be trivial, in which case we shouldn't
593         // perform the combine.
594         if (LR.first != &IE && LR.second != &IE) {
595           // We now have a shuffle of LHS, RHS, Mask.
596           if (LR.second == nullptr)
597             LR.second = UndefValue::get(LR.first->getType());
598           return new ShuffleVectorInst(LR.first, LR.second,
599                                        ConstantVector::get(Mask));
600         }
601       }
602     }
603   }
604 
605   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
606   APInt UndefElts(VWidth, 0);
607   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
608   if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
609     if (V != &IE)
610       return replaceInstUsesWith(IE, V);
611     return &IE;
612   }
613 
614   return nullptr;
615 }
616 
617 /// Return true if we can evaluate the specified expression tree if the vector
618 /// elements were shuffled in a different order.
619 static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
620                                 unsigned Depth = 5) {
621   // We can always reorder the elements of a constant.
622   if (isa<Constant>(V))
623     return true;
624 
625   // We won't reorder vector arguments. No IPO here.
626   Instruction *I = dyn_cast<Instruction>(V);
627   if (!I) return false;
628 
629   // Two users may expect different orders of the elements. Don't try it.
630   if (!I->hasOneUse())
631     return false;
632 
633   if (Depth == 0) return false;
634 
635   switch (I->getOpcode()) {
636     case Instruction::Add:
637     case Instruction::FAdd:
638     case Instruction::Sub:
639     case Instruction::FSub:
640     case Instruction::Mul:
641     case Instruction::FMul:
642     case Instruction::UDiv:
643     case Instruction::SDiv:
644     case Instruction::FDiv:
645     case Instruction::URem:
646     case Instruction::SRem:
647     case Instruction::FRem:
648     case Instruction::Shl:
649     case Instruction::LShr:
650     case Instruction::AShr:
651     case Instruction::And:
652     case Instruction::Or:
653     case Instruction::Xor:
654     case Instruction::ICmp:
655     case Instruction::FCmp:
656     case Instruction::Trunc:
657     case Instruction::ZExt:
658     case Instruction::SExt:
659     case Instruction::FPToUI:
660     case Instruction::FPToSI:
661     case Instruction::UIToFP:
662     case Instruction::SIToFP:
663     case Instruction::FPTrunc:
664     case Instruction::FPExt:
665     case Instruction::GetElementPtr: {
666       for (Value *Operand : I->operands()) {
667         if (!CanEvaluateShuffled(Operand, Mask, Depth-1))
668           return false;
669       }
670       return true;
671     }
672     case Instruction::InsertElement: {
673       ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
674       if (!CI) return false;
675       int ElementNumber = CI->getLimitedValue();
676 
677       // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
678       // can't put an element into multiple indices.
679       bool SeenOnce = false;
680       for (int i = 0, e = Mask.size(); i != e; ++i) {
681         if (Mask[i] == ElementNumber) {
682           if (SeenOnce)
683             return false;
684           SeenOnce = true;
685         }
686       }
687       return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
688     }
689   }
690   return false;
691 }
692 
693 /// Rebuild a new instruction just like 'I' but with the new operands given.
694 /// In the event of type mismatch, the type of the operands is correct.
695 static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
696   // We don't want to use the IRBuilder here because we want the replacement
697   // instructions to appear next to 'I', not the builder's insertion point.
698   switch (I->getOpcode()) {
699     case Instruction::Add:
700     case Instruction::FAdd:
701     case Instruction::Sub:
702     case Instruction::FSub:
703     case Instruction::Mul:
704     case Instruction::FMul:
705     case Instruction::UDiv:
706     case Instruction::SDiv:
707     case Instruction::FDiv:
708     case Instruction::URem:
709     case Instruction::SRem:
710     case Instruction::FRem:
711     case Instruction::Shl:
712     case Instruction::LShr:
713     case Instruction::AShr:
714     case Instruction::And:
715     case Instruction::Or:
716     case Instruction::Xor: {
717       BinaryOperator *BO = cast<BinaryOperator>(I);
718       assert(NewOps.size() == 2 && "binary operator with #ops != 2");
719       BinaryOperator *New =
720           BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
721                                  NewOps[0], NewOps[1], "", BO);
722       if (isa<OverflowingBinaryOperator>(BO)) {
723         New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
724         New->setHasNoSignedWrap(BO->hasNoSignedWrap());
725       }
726       if (isa<PossiblyExactOperator>(BO)) {
727         New->setIsExact(BO->isExact());
728       }
729       if (isa<FPMathOperator>(BO))
730         New->copyFastMathFlags(I);
731       return New;
732     }
733     case Instruction::ICmp:
734       assert(NewOps.size() == 2 && "icmp with #ops != 2");
735       return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
736                           NewOps[0], NewOps[1]);
737     case Instruction::FCmp:
738       assert(NewOps.size() == 2 && "fcmp with #ops != 2");
739       return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
740                           NewOps[0], NewOps[1]);
741     case Instruction::Trunc:
742     case Instruction::ZExt:
743     case Instruction::SExt:
744     case Instruction::FPToUI:
745     case Instruction::FPToSI:
746     case Instruction::UIToFP:
747     case Instruction::SIToFP:
748     case Instruction::FPTrunc:
749     case Instruction::FPExt: {
750       // It's possible that the mask has a different number of elements from
751       // the original cast. We recompute the destination type to match the mask.
752       Type *DestTy =
753           VectorType::get(I->getType()->getScalarType(),
754                           NewOps[0]->getType()->getVectorNumElements());
755       assert(NewOps.size() == 1 && "cast with #ops != 1");
756       return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
757                               "", I);
758     }
759     case Instruction::GetElementPtr: {
760       Value *Ptr = NewOps[0];
761       ArrayRef<Value*> Idx = NewOps.slice(1);
762       GetElementPtrInst *GEP = GetElementPtrInst::Create(
763           cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
764       GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
765       return GEP;
766     }
767   }
768   llvm_unreachable("failed to rebuild vector instructions");
769 }
770 
771 Value *
772 InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
773   // Mask.size() does not need to be equal to the number of vector elements.
774 
775   assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
776   if (isa<UndefValue>(V)) {
777     return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
778                                            Mask.size()));
779   }
780   if (isa<ConstantAggregateZero>(V)) {
781     return ConstantAggregateZero::get(
782                VectorType::get(V->getType()->getScalarType(),
783                                Mask.size()));
784   }
785   if (Constant *C = dyn_cast<Constant>(V)) {
786     SmallVector<Constant *, 16> MaskValues;
787     for (int i = 0, e = Mask.size(); i != e; ++i) {
788       if (Mask[i] == -1)
789         MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
790       else
791         MaskValues.push_back(Builder->getInt32(Mask[i]));
792     }
793     return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
794                                           ConstantVector::get(MaskValues));
795   }
796 
797   Instruction *I = cast<Instruction>(V);
798   switch (I->getOpcode()) {
799     case Instruction::Add:
800     case Instruction::FAdd:
801     case Instruction::Sub:
802     case Instruction::FSub:
803     case Instruction::Mul:
804     case Instruction::FMul:
805     case Instruction::UDiv:
806     case Instruction::SDiv:
807     case Instruction::FDiv:
808     case Instruction::URem:
809     case Instruction::SRem:
810     case Instruction::FRem:
811     case Instruction::Shl:
812     case Instruction::LShr:
813     case Instruction::AShr:
814     case Instruction::And:
815     case Instruction::Or:
816     case Instruction::Xor:
817     case Instruction::ICmp:
818     case Instruction::FCmp:
819     case Instruction::Trunc:
820     case Instruction::ZExt:
821     case Instruction::SExt:
822     case Instruction::FPToUI:
823     case Instruction::FPToSI:
824     case Instruction::UIToFP:
825     case Instruction::SIToFP:
826     case Instruction::FPTrunc:
827     case Instruction::FPExt:
828     case Instruction::Select:
829     case Instruction::GetElementPtr: {
830       SmallVector<Value*, 8> NewOps;
831       bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
832       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
833         Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
834         NewOps.push_back(V);
835         NeedsRebuild |= (V != I->getOperand(i));
836       }
837       if (NeedsRebuild) {
838         return buildNew(I, NewOps);
839       }
840       return I;
841     }
842     case Instruction::InsertElement: {
843       int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
844 
845       // The insertelement was inserting at Element. Figure out which element
846       // that becomes after shuffling. The answer is guaranteed to be unique
847       // by CanEvaluateShuffled.
848       bool Found = false;
849       int Index = 0;
850       for (int e = Mask.size(); Index != e; ++Index) {
851         if (Mask[Index] == Element) {
852           Found = true;
853           break;
854         }
855       }
856 
857       // If element is not in Mask, no need to handle the operand 1 (element to
858       // be inserted). Just evaluate values in operand 0 according to Mask.
859       if (!Found)
860         return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
861 
862       Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
863       return InsertElementInst::Create(V, I->getOperand(1),
864                                        Builder->getInt32(Index), "", I);
865     }
866   }
867   llvm_unreachable("failed to reorder elements of vector instruction!");
868 }
869 
870 static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask,
871                                   bool &isLHSID, bool &isRHSID) {
872   isLHSID = isRHSID = true;
873 
874   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
875     if (Mask[i] < 0) continue;  // Ignore undef values.
876     // Is this an identity shuffle of the LHS value?
877     isLHSID &= (Mask[i] == (int)i);
878 
879     // Is this an identity shuffle of the RHS value?
880     isRHSID &= (Mask[i]-e == i);
881   }
882 }
883 
884 // Returns true if the shuffle is extracting a contiguous range of values from
885 // LHS, for example:
886 //                 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
887 //   Input:        |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
888 //   Shuffles to:  |EE|FF|GG|HH|
889 //                 +--+--+--+--+
890 static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
891                                        SmallVector<int, 16> &Mask) {
892   unsigned LHSElems =
893       cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements();
894   unsigned MaskElems = Mask.size();
895   unsigned BegIdx = Mask.front();
896   unsigned EndIdx = Mask.back();
897   if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
898     return false;
899   for (unsigned I = 0; I != MaskElems; ++I)
900     if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
901       return false;
902   return true;
903 }
904 
905 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
906   Value *LHS = SVI.getOperand(0);
907   Value *RHS = SVI.getOperand(1);
908   SmallVector<int, 16> Mask = SVI.getShuffleMask();
909   Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
910 
911   bool MadeChange = false;
912 
913   // Undefined shuffle mask -> undefined value.
914   if (isa<UndefValue>(SVI.getOperand(2)))
915     return replaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
916 
917   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
918 
919   APInt UndefElts(VWidth, 0);
920   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
921   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
922     if (V != &SVI)
923       return replaceInstUsesWith(SVI, V);
924     LHS = SVI.getOperand(0);
925     RHS = SVI.getOperand(1);
926     MadeChange = true;
927   }
928 
929   unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
930 
931   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
932   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
933   if (LHS == RHS || isa<UndefValue>(LHS)) {
934     if (isa<UndefValue>(LHS) && LHS == RHS) {
935       // shuffle(undef,undef,mask) -> undef.
936       Value *Result = (VWidth == LHSWidth)
937                       ? LHS : UndefValue::get(SVI.getType());
938       return replaceInstUsesWith(SVI, Result);
939     }
940 
941     // Remap any references to RHS to use LHS.
942     SmallVector<Constant*, 16> Elts;
943     for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
944       if (Mask[i] < 0) {
945         Elts.push_back(UndefValue::get(Int32Ty));
946         continue;
947       }
948 
949       if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
950           (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
951         Mask[i] = -1;     // Turn into undef.
952         Elts.push_back(UndefValue::get(Int32Ty));
953       } else {
954         Mask[i] = Mask[i] % e;  // Force to LHS.
955         Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
956       }
957     }
958     SVI.setOperand(0, SVI.getOperand(1));
959     SVI.setOperand(1, UndefValue::get(RHS->getType()));
960     SVI.setOperand(2, ConstantVector::get(Elts));
961     LHS = SVI.getOperand(0);
962     RHS = SVI.getOperand(1);
963     MadeChange = true;
964   }
965 
966   if (VWidth == LHSWidth) {
967     // Analyze the shuffle, are the LHS or RHS and identity shuffles?
968     bool isLHSID, isRHSID;
969     recognizeIdentityMask(Mask, isLHSID, isRHSID);
970 
971     // Eliminate identity shuffles.
972     if (isLHSID) return replaceInstUsesWith(SVI, LHS);
973     if (isRHSID) return replaceInstUsesWith(SVI, RHS);
974   }
975 
976   if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
977     Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
978     return replaceInstUsesWith(SVI, V);
979   }
980 
981   // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
982   // a non-vector type. We can instead bitcast the original vector followed by
983   // an extract of the desired element:
984   //
985   //   %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
986   //                         <4 x i32> <i32 0, i32 1, i32 2, i32 3>
987   //   %1 = bitcast <4 x i8> %sroa to i32
988   // Becomes:
989   //   %bc = bitcast <16 x i8> %in to <4 x i32>
990   //   %ext = extractelement <4 x i32> %bc, i32 0
991   //
992   // If the shuffle is extracting a contiguous range of values from the input
993   // vector then each use which is a bitcast of the extracted size can be
994   // replaced. This will work if the vector types are compatible, and the begin
995   // index is aligned to a value in the casted vector type. If the begin index
996   // isn't aligned then we can shuffle the original vector (keeping the same
997   // vector type) before extracting.
998   //
999   // This code will bail out if the target type is fundamentally incompatible
1000   // with vectors of the source type.
1001   //
1002   // Example of <16 x i8>, target type i32:
1003   // Index range [4,8):         v-----------v Will work.
1004   //                +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1005   //     <16 x i8>: |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
1006   //     <4 x i32>: |           |           |           |           |
1007   //                +-----------+-----------+-----------+-----------+
1008   // Index range [6,10):              ^-----------^ Needs an extra shuffle.
1009   // Target type i40:           ^--------------^ Won't work, bail.
1010   if (isShuffleExtractingFromLHS(SVI, Mask)) {
1011     Value *V = LHS;
1012     unsigned MaskElems = Mask.size();
1013     unsigned BegIdx = Mask.front();
1014     VectorType *SrcTy = cast<VectorType>(V->getType());
1015     unsigned VecBitWidth = SrcTy->getBitWidth();
1016     unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
1017     assert(SrcElemBitWidth && "vector elements must have a bitwidth");
1018     unsigned SrcNumElems = SrcTy->getNumElements();
1019     SmallVector<BitCastInst *, 8> BCs;
1020     DenseMap<Type *, Value *> NewBCs;
1021     for (User *U : SVI.users())
1022       if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
1023         if (!BC->use_empty())
1024           // Only visit bitcasts that weren't previously handled.
1025           BCs.push_back(BC);
1026     for (BitCastInst *BC : BCs) {
1027       Type *TgtTy = BC->getDestTy();
1028       unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
1029       if (!TgtElemBitWidth)
1030         continue;
1031       unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1032       bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1033       bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1034       if (!VecBitWidthsEqual)
1035         continue;
1036       if (!VectorType::isValidElementType(TgtTy))
1037         continue;
1038       VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1039       if (!BegIsAligned) {
1040         // Shuffle the input so [0,NumElements) contains the output, and
1041         // [NumElems,SrcNumElems) is undef.
1042         SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1043                                                 UndefValue::get(Int32Ty));
1044         for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1045           ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
1046         V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()),
1047                                          ConstantVector::get(ShuffleMask),
1048                                          SVI.getName() + ".extract");
1049         BegIdx = 0;
1050       }
1051       unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1052       assert(SrcElemsPerTgtElem);
1053       BegIdx /= SrcElemsPerTgtElem;
1054       bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1055       auto *NewBC =
1056           BCAlreadyExists
1057               ? NewBCs[CastSrcTy]
1058               : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
1059       if (!BCAlreadyExists)
1060         NewBCs[CastSrcTy] = NewBC;
1061       auto *Ext = Builder->CreateExtractElement(
1062           NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1063       // The shufflevector isn't being replaced: the bitcast that used it
1064       // is. InstCombine will visit the newly-created instructions.
1065       replaceInstUsesWith(*BC, Ext);
1066       MadeChange = true;
1067     }
1068   }
1069 
1070   // If the LHS is a shufflevector itself, see if we can combine it with this
1071   // one without producing an unusual shuffle.
1072   // Cases that might be simplified:
1073   // 1.
1074   // x1=shuffle(v1,v2,mask1)
1075   //  x=shuffle(x1,undef,mask)
1076   //        ==>
1077   //  x=shuffle(v1,undef,newMask)
1078   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1079   // 2.
1080   // x1=shuffle(v1,undef,mask1)
1081   //  x=shuffle(x1,x2,mask)
1082   // where v1.size() == mask1.size()
1083   //        ==>
1084   //  x=shuffle(v1,x2,newMask)
1085   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1086   // 3.
1087   // x2=shuffle(v2,undef,mask2)
1088   //  x=shuffle(x1,x2,mask)
1089   // where v2.size() == mask2.size()
1090   //        ==>
1091   //  x=shuffle(x1,v2,newMask)
1092   // newMask[i] = (mask[i] < x1.size())
1093   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1094   // 4.
1095   // x1=shuffle(v1,undef,mask1)
1096   // x2=shuffle(v2,undef,mask2)
1097   //  x=shuffle(x1,x2,mask)
1098   // where v1.size() == v2.size()
1099   //        ==>
1100   //  x=shuffle(v1,v2,newMask)
1101   // newMask[i] = (mask[i] < x1.size())
1102   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1103   //
1104   // Here we are really conservative:
1105   // we are absolutely afraid of producing a shuffle mask not in the input
1106   // program, because the code gen may not be smart enough to turn a merged
1107   // shuffle into two specific shuffles: it may produce worse code.  As such,
1108   // we only merge two shuffles if the result is either a splat or one of the
1109   // input shuffle masks.  In this case, merging the shuffles just removes
1110   // one instruction, which we know is safe.  This is good for things like
1111   // turning: (splat(splat)) -> splat, or
1112   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1113   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1114   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1115   if (LHSShuffle)
1116     if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
1117       LHSShuffle = nullptr;
1118   if (RHSShuffle)
1119     if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
1120       RHSShuffle = nullptr;
1121   if (!LHSShuffle && !RHSShuffle)
1122     return MadeChange ? &SVI : nullptr;
1123 
1124   Value* LHSOp0 = nullptr;
1125   Value* LHSOp1 = nullptr;
1126   Value* RHSOp0 = nullptr;
1127   unsigned LHSOp0Width = 0;
1128   unsigned RHSOp0Width = 0;
1129   if (LHSShuffle) {
1130     LHSOp0 = LHSShuffle->getOperand(0);
1131     LHSOp1 = LHSShuffle->getOperand(1);
1132     LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
1133   }
1134   if (RHSShuffle) {
1135     RHSOp0 = RHSShuffle->getOperand(0);
1136     RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
1137   }
1138   Value* newLHS = LHS;
1139   Value* newRHS = RHS;
1140   if (LHSShuffle) {
1141     // case 1
1142     if (isa<UndefValue>(RHS)) {
1143       newLHS = LHSOp0;
1144       newRHS = LHSOp1;
1145     }
1146     // case 2 or 4
1147     else if (LHSOp0Width == LHSWidth) {
1148       newLHS = LHSOp0;
1149     }
1150   }
1151   // case 3 or 4
1152   if (RHSShuffle && RHSOp0Width == LHSWidth) {
1153     newRHS = RHSOp0;
1154   }
1155   // case 4
1156   if (LHSOp0 == RHSOp0) {
1157     newLHS = LHSOp0;
1158     newRHS = nullptr;
1159   }
1160 
1161   if (newLHS == LHS && newRHS == RHS)
1162     return MadeChange ? &SVI : nullptr;
1163 
1164   SmallVector<int, 16> LHSMask;
1165   SmallVector<int, 16> RHSMask;
1166   if (newLHS != LHS)
1167     LHSMask = LHSShuffle->getShuffleMask();
1168   if (RHSShuffle && newRHS != RHS)
1169     RHSMask = RHSShuffle->getShuffleMask();
1170 
1171   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1172   SmallVector<int, 16> newMask;
1173   bool isSplat = true;
1174   int SplatElt = -1;
1175   // Create a new mask for the new ShuffleVectorInst so that the new
1176   // ShuffleVectorInst is equivalent to the original one.
1177   for (unsigned i = 0; i < VWidth; ++i) {
1178     int eltMask;
1179     if (Mask[i] < 0) {
1180       // This element is an undef value.
1181       eltMask = -1;
1182     } else if (Mask[i] < (int)LHSWidth) {
1183       // This element is from left hand side vector operand.
1184       //
1185       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1186       // new mask value for the element.
1187       if (newLHS != LHS) {
1188         eltMask = LHSMask[Mask[i]];
1189         // If the value selected is an undef value, explicitly specify it
1190         // with a -1 mask value.
1191         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1192           eltMask = -1;
1193       } else
1194         eltMask = Mask[i];
1195     } else {
1196       // This element is from right hand side vector operand
1197       //
1198       // If the value selected is an undef value, explicitly specify it
1199       // with a -1 mask value. (case 1)
1200       if (isa<UndefValue>(RHS))
1201         eltMask = -1;
1202       // If RHS is going to be replaced (case 3 or 4), calculate the
1203       // new mask value for the element.
1204       else if (newRHS != RHS) {
1205         eltMask = RHSMask[Mask[i]-LHSWidth];
1206         // If the value selected is an undef value, explicitly specify it
1207         // with a -1 mask value.
1208         if (eltMask >= (int)RHSOp0Width) {
1209           assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1210                  && "should have been check above");
1211           eltMask = -1;
1212         }
1213       } else
1214         eltMask = Mask[i]-LHSWidth;
1215 
1216       // If LHS's width is changed, shift the mask value accordingly.
1217       // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
1218       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1219       // If newRHS == newLHS, we want to remap any references from newRHS to
1220       // newLHS so that we can properly identify splats that may occur due to
1221       // obfuscation across the two vectors.
1222       if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
1223         eltMask += newLHSWidth;
1224     }
1225 
1226     // Check if this could still be a splat.
1227     if (eltMask >= 0) {
1228       if (SplatElt >= 0 && SplatElt != eltMask)
1229         isSplat = false;
1230       SplatElt = eltMask;
1231     }
1232 
1233     newMask.push_back(eltMask);
1234   }
1235 
1236   // If the result mask is equal to one of the original shuffle masks,
1237   // or is a splat, do the replacement.
1238   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
1239     SmallVector<Constant*, 16> Elts;
1240     for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1241       if (newMask[i] < 0) {
1242         Elts.push_back(UndefValue::get(Int32Ty));
1243       } else {
1244         Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1245       }
1246     }
1247     if (!newRHS)
1248       newRHS = UndefValue::get(newLHS->getType());
1249     return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
1250   }
1251 
1252   // If the result mask is an identity, replace uses of this instruction with
1253   // corresponding argument.
1254   bool isLHSID, isRHSID;
1255   recognizeIdentityMask(newMask, isLHSID, isRHSID);
1256   if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS);
1257   if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS);
1258 
1259   return MadeChange ? &SVI : nullptr;
1260 }
1261