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