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