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