1f22ef01cSRoman Divacky //===- InstCombineVectorOps.cpp -------------------------------------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file implements instcombine for ExtractElement, InsertElement and
11f22ef01cSRoman Divacky // ShuffleVector.
12f22ef01cSRoman Divacky //
13f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
14f22ef01cSRoman Divacky 
15ff0cc061SDimitry Andric #include "InstCombineInternal.h"
162cab237bSDimitry Andric #include "llvm/ADT/APInt.h"
172cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
18ff0cc061SDimitry Andric #include "llvm/ADT/DenseMap.h"
192cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
202cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
21875ed548SDimitry Andric #include "llvm/Analysis/InstructionSimplify.h"
22875ed548SDimitry Andric #include "llvm/Analysis/VectorUtils.h"
232cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
242cab237bSDimitry Andric #include "llvm/IR/Constant.h"
252cab237bSDimitry Andric #include "llvm/IR/Constants.h"
262cab237bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
272cab237bSDimitry Andric #include "llvm/IR/InstrTypes.h"
282cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
292cab237bSDimitry Andric #include "llvm/IR/Instructions.h"
302cab237bSDimitry Andric #include "llvm/IR/Operator.h"
3191bc56edSDimitry Andric #include "llvm/IR/PatternMatch.h"
322cab237bSDimitry Andric #include "llvm/IR/Type.h"
332cab237bSDimitry Andric #include "llvm/IR/User.h"
342cab237bSDimitry Andric #include "llvm/IR/Value.h"
352cab237bSDimitry Andric #include "llvm/Support/Casting.h"
362cab237bSDimitry Andric #include "llvm/Support/ErrorHandling.h"
372cab237bSDimitry Andric #include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
382cab237bSDimitry Andric #include <cassert>
392cab237bSDimitry Andric #include <cstdint>
402cab237bSDimitry Andric #include <iterator>
412cab237bSDimitry Andric #include <utility>
422cab237bSDimitry Andric 
43f22ef01cSRoman Divacky using namespace llvm;
44139f7f9bSDimitry Andric using namespace PatternMatch;
45f22ef01cSRoman Divacky 
4691bc56edSDimitry Andric #define DEBUG_TYPE "instcombine"
4791bc56edSDimitry Andric 
487d523365SDimitry Andric /// Return true if the value is cheaper to scalarize than it is to leave as a
497d523365SDimitry Andric /// vector operation. isConstant indicates whether we're extracting one known
507d523365SDimitry Andric /// element. If false we're extracting a variable index.
517d523365SDimitry Andric static bool cheapToScalarize(Value *V, bool isConstant) {
52dff0c46cSDimitry Andric   if (Constant *C = dyn_cast<Constant>(V)) {
53f22ef01cSRoman Divacky     if (isConstant) return true;
54dff0c46cSDimitry Andric 
55dff0c46cSDimitry Andric     // If all elts are the same, we can extract it and use any of the values.
5685d60e68SDimitry Andric     if (Constant *Op0 = C->getAggregateElement(0U)) {
5785d60e68SDimitry Andric       for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
5885d60e68SDimitry Andric            ++i)
59dff0c46cSDimitry Andric         if (C->getAggregateElement(i) != Op0)
60f22ef01cSRoman Divacky           return false;
61f22ef01cSRoman Divacky       return true;
62f22ef01cSRoman Divacky     }
6385d60e68SDimitry Andric   }
64f22ef01cSRoman Divacky   Instruction *I = dyn_cast<Instruction>(V);
65f22ef01cSRoman Divacky   if (!I) return false;
66f22ef01cSRoman Divacky 
67f22ef01cSRoman Divacky   // Insert element gets simplified to the inserted element or is deleted if
68f22ef01cSRoman Divacky   // this is constant idx extract element and its a constant idx insertelt.
69f22ef01cSRoman Divacky   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
70f22ef01cSRoman Divacky       isa<ConstantInt>(I->getOperand(2)))
71f22ef01cSRoman Divacky     return true;
72f22ef01cSRoman Divacky   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
73f22ef01cSRoman Divacky     return true;
74f22ef01cSRoman Divacky   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
75f22ef01cSRoman Divacky     if (BO->hasOneUse() &&
767d523365SDimitry Andric         (cheapToScalarize(BO->getOperand(0), isConstant) ||
777d523365SDimitry Andric          cheapToScalarize(BO->getOperand(1), isConstant)))
78f22ef01cSRoman Divacky       return true;
79f22ef01cSRoman Divacky   if (CmpInst *CI = dyn_cast<CmpInst>(I))
80f22ef01cSRoman Divacky     if (CI->hasOneUse() &&
817d523365SDimitry Andric         (cheapToScalarize(CI->getOperand(0), isConstant) ||
827d523365SDimitry Andric          cheapToScalarize(CI->getOperand(1), isConstant)))
83f22ef01cSRoman Divacky       return true;
84f22ef01cSRoman Divacky 
85f22ef01cSRoman Divacky   return false;
86f22ef01cSRoman Divacky }
87f22ef01cSRoman Divacky 
883ca95b02SDimitry Andric // If we have a PHI node with a vector type that is only used to feed
89f785676fSDimitry Andric // itself and be an operand of extractelement at a constant location,
90f785676fSDimitry Andric // try to replace the PHI of the vector type with a PHI of a scalar type.
91284c1978SDimitry Andric Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
923ca95b02SDimitry Andric   SmallVector<Instruction *, 2> Extracts;
933ca95b02SDimitry Andric   // The users we want the PHI to have are:
943ca95b02SDimitry Andric   // 1) The EI ExtractElement (we already know this)
953ca95b02SDimitry Andric   // 2) Possibly more ExtractElements with the same index.
963ca95b02SDimitry Andric   // 3) Another operand, which will feed back into the PHI.
973ca95b02SDimitry Andric   Instruction *PHIUser = nullptr;
983ca95b02SDimitry Andric   for (auto U : PN->users()) {
993ca95b02SDimitry Andric     if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
1003ca95b02SDimitry Andric       if (EI.getIndexOperand() == EU->getIndexOperand())
1013ca95b02SDimitry Andric         Extracts.push_back(EU);
1023ca95b02SDimitry Andric       else
10391bc56edSDimitry Andric         return nullptr;
1043ca95b02SDimitry Andric     } else if (!PHIUser) {
1053ca95b02SDimitry Andric       PHIUser = cast<Instruction>(U);
1063ca95b02SDimitry Andric     } else {
1073ca95b02SDimitry Andric       return nullptr;
1083ca95b02SDimitry Andric     }
1093ca95b02SDimitry Andric   }
110284c1978SDimitry Andric 
1113ca95b02SDimitry Andric   if (!PHIUser)
1123ca95b02SDimitry Andric     return nullptr;
113284c1978SDimitry Andric 
114284c1978SDimitry Andric   // Verify that this PHI user has one use, which is the PHI itself,
115284c1978SDimitry Andric   // and that it is a binary operation which is cheap to scalarize.
1162cab237bSDimitry Andric   // otherwise return nullptr.
11791bc56edSDimitry Andric   if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
1187d523365SDimitry Andric       !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true))
11991bc56edSDimitry Andric     return nullptr;
120284c1978SDimitry Andric 
121284c1978SDimitry Andric   // Create a scalar PHI node that will replace the vector PHI node
122284c1978SDimitry Andric   // just before the current PHI node.
123f785676fSDimitry Andric   PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
124f785676fSDimitry Andric       PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
125284c1978SDimitry Andric   // Scalarize each PHI operand.
126284c1978SDimitry Andric   for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
127284c1978SDimitry Andric     Value *PHIInVal = PN->getIncomingValue(i);
128284c1978SDimitry Andric     BasicBlock *inBB = PN->getIncomingBlock(i);
129284c1978SDimitry Andric     Value *Elt = EI.getIndexOperand();
130284c1978SDimitry Andric     // If the operand is the PHI induction variable:
131284c1978SDimitry Andric     if (PHIInVal == PHIUser) {
132284c1978SDimitry Andric       // Scalarize the binary operation. Its first operand is the
13391bc56edSDimitry Andric       // scalar PHI, and the second operand is extracted from the other
134284c1978SDimitry Andric       // vector operand.
135284c1978SDimitry Andric       BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
136284c1978SDimitry Andric       unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
137f785676fSDimitry Andric       Value *Op = InsertNewInstWith(
138f785676fSDimitry Andric           ExtractElementInst::Create(B0->getOperand(opId), Elt,
139f785676fSDimitry Andric                                      B0->getOperand(opId)->getName() + ".Elt"),
140284c1978SDimitry Andric           *B0);
141f785676fSDimitry Andric       Value *newPHIUser = InsertNewInstWith(
1423ca95b02SDimitry Andric           BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
1433ca95b02SDimitry Andric                                                 scalarPHI, Op, B0), *B0);
144284c1978SDimitry Andric       scalarPHI->addIncoming(newPHIUser, inBB);
145284c1978SDimitry Andric     } else {
146284c1978SDimitry Andric       // Scalarize PHI input:
147f785676fSDimitry Andric       Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
148284c1978SDimitry Andric       // Insert the new instruction into the predecessor basic block.
149284c1978SDimitry Andric       Instruction *pos = dyn_cast<Instruction>(PHIInVal);
150284c1978SDimitry Andric       BasicBlock::iterator InsertPos;
151284c1978SDimitry Andric       if (pos && !isa<PHINode>(pos)) {
1527d523365SDimitry Andric         InsertPos = ++pos->getIterator();
153284c1978SDimitry Andric       } else {
154284c1978SDimitry Andric         InsertPos = inBB->getFirstInsertionPt();
155284c1978SDimitry Andric       }
156284c1978SDimitry Andric 
157284c1978SDimitry Andric       InsertNewInstWith(newEI, *InsertPos);
158284c1978SDimitry Andric 
159284c1978SDimitry Andric       scalarPHI->addIncoming(newEI, inBB);
160284c1978SDimitry Andric     }
161284c1978SDimitry Andric   }
1623ca95b02SDimitry Andric 
1633ca95b02SDimitry Andric   for (auto E : Extracts)
1643ca95b02SDimitry Andric     replaceInstUsesWith(*E, scalarPHI);
1653ca95b02SDimitry Andric 
1663ca95b02SDimitry Andric   return &EI;
167284c1978SDimitry Andric }
168284c1978SDimitry Andric 
169f22ef01cSRoman Divacky Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
170f37b6182SDimitry Andric   if (Value *V = SimplifyExtractElementInst(EI.getVectorOperand(),
171db17bf38SDimitry Andric                                             EI.getIndexOperand(),
172db17bf38SDimitry Andric                                             SQ.getWithInstruction(&EI)))
1733ca95b02SDimitry Andric     return replaceInstUsesWith(EI, V);
174875ed548SDimitry Andric 
175f22ef01cSRoman Divacky   // If vector val is constant with all elements the same, replace EI with
176dff0c46cSDimitry Andric   // that element.  We handle a known element # below.
177dff0c46cSDimitry Andric   if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
1787d523365SDimitry Andric     if (cheapToScalarize(C, false))
1793ca95b02SDimitry Andric       return replaceInstUsesWith(EI, C->getAggregateElement(0U));
180f22ef01cSRoman Divacky 
181f22ef01cSRoman Divacky   // If extracting a specified index from the vector, see if we can recursively
182f22ef01cSRoman Divacky   // find a previously computed scalar that was inserted into the vector.
183f22ef01cSRoman Divacky   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
184f22ef01cSRoman Divacky     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
185f22ef01cSRoman Divacky 
186fe4fed2eSDimitry Andric     // InstSimplify should handle cases where the index is invalid.
187fe4fed2eSDimitry Andric     if (!IdxC->getValue().ule(VectorWidth))
188fe4fed2eSDimitry Andric       return nullptr;
189fe4fed2eSDimitry Andric 
190fe4fed2eSDimitry Andric     unsigned IndexVal = IdxC->getZExtValue();
191f22ef01cSRoman Divacky 
192f22ef01cSRoman Divacky     // This instruction only demands the single element from the input vector.
193f22ef01cSRoman Divacky     // If the input vector has a single use, simplify it based on this use
194f22ef01cSRoman Divacky     // property.
195f22ef01cSRoman Divacky     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
196f22ef01cSRoman Divacky       APInt UndefElts(VectorWidth, 0);
197f22ef01cSRoman Divacky       APInt DemandedMask(VectorWidth, 0);
1982754fe60SDimitry Andric       DemandedMask.setBit(IndexVal);
199ff0cc061SDimitry Andric       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
200ff0cc061SDimitry Andric                                                 UndefElts)) {
201f22ef01cSRoman Divacky         EI.setOperand(0, V);
202f22ef01cSRoman Divacky         return &EI;
203f22ef01cSRoman Divacky       }
204f22ef01cSRoman Divacky     }
205f22ef01cSRoman Divacky 
2067d523365SDimitry Andric     // If this extractelement is directly using a bitcast from a vector of
207f22ef01cSRoman Divacky     // the same number of elements, see if we can find the source element from
208f22ef01cSRoman Divacky     // it.  In this case, we will end up needing to bitcast the scalars.
209f22ef01cSRoman Divacky     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
210dff0c46cSDimitry Andric       if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
211f22ef01cSRoman Divacky         if (VT->getNumElements() == VectorWidth)
212875ed548SDimitry Andric           if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal))
213f22ef01cSRoman Divacky             return new BitCastInst(Elt, EI.getType());
214f22ef01cSRoman Divacky     }
215284c1978SDimitry Andric 
216284c1978SDimitry Andric     // If there's a vector PHI feeding a scalar use through this extractelement
217284c1978SDimitry Andric     // instruction, try to scalarize the PHI.
218284c1978SDimitry Andric     if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
219284c1978SDimitry Andric       Instruction *scalarPHI = scalarizePHI(EI, PN);
220284c1978SDimitry Andric       if (scalarPHI)
221f785676fSDimitry Andric         return scalarPHI;
222284c1978SDimitry Andric     }
223f22ef01cSRoman Divacky   }
224f22ef01cSRoman Divacky 
225f22ef01cSRoman Divacky   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
226f22ef01cSRoman Divacky     // Push extractelement into predecessor operation if legal and
2277d523365SDimitry Andric     // profitable to do so.
228f22ef01cSRoman Divacky     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
229f22ef01cSRoman Divacky       if (I->hasOneUse() &&
2307d523365SDimitry Andric           cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
231f22ef01cSRoman Divacky         Value *newEI0 =
232c4394386SDimitry Andric           Builder.CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
233f22ef01cSRoman Divacky                                        EI.getName()+".lhs");
234f22ef01cSRoman Divacky         Value *newEI1 =
235c4394386SDimitry Andric           Builder.CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
236f22ef01cSRoman Divacky                                        EI.getName()+".rhs");
2373ca95b02SDimitry Andric         return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(),
2383ca95b02SDimitry Andric                                                      newEI0, newEI1, BO);
239f22ef01cSRoman Divacky       }
240f22ef01cSRoman Divacky     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
241f22ef01cSRoman Divacky       // Extracting the inserted element?
242f22ef01cSRoman Divacky       if (IE->getOperand(2) == EI.getOperand(1))
2433ca95b02SDimitry Andric         return replaceInstUsesWith(EI, IE->getOperand(1));
244f22ef01cSRoman Divacky       // If the inserted and extracted elements are constants, they must not
245f22ef01cSRoman Divacky       // be the same value, extract from the pre-inserted value instead.
246f22ef01cSRoman Divacky       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
247f22ef01cSRoman Divacky         Worklist.AddValue(EI.getOperand(0));
248f22ef01cSRoman Divacky         EI.setOperand(0, IE->getOperand(0));
249f22ef01cSRoman Divacky         return &EI;
250f22ef01cSRoman Divacky       }
251f22ef01cSRoman Divacky     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
252f22ef01cSRoman Divacky       // If this is extracting an element from a shufflevector, figure out where
253f22ef01cSRoman Divacky       // it came from and extract from the appropriate input element instead.
254f22ef01cSRoman Divacky       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
255dff0c46cSDimitry Andric         int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
256f22ef01cSRoman Divacky         Value *Src;
257f22ef01cSRoman Divacky         unsigned LHSWidth =
258dff0c46cSDimitry Andric           SVI->getOperand(0)->getType()->getVectorNumElements();
259f22ef01cSRoman Divacky 
2602754fe60SDimitry Andric         if (SrcIdx < 0)
2613ca95b02SDimitry Andric           return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
2622754fe60SDimitry Andric         if (SrcIdx < (int)LHSWidth)
263f22ef01cSRoman Divacky           Src = SVI->getOperand(0);
2642754fe60SDimitry Andric         else {
265f22ef01cSRoman Divacky           SrcIdx -= LHSWidth;
266f22ef01cSRoman Divacky           Src = SVI->getOperand(1);
267f22ef01cSRoman Divacky         }
2686122f3e6SDimitry Andric         Type *Int32Ty = Type::getInt32Ty(EI.getContext());
269f22ef01cSRoman Divacky         return ExtractElementInst::Create(Src,
2702754fe60SDimitry Andric                                           ConstantInt::get(Int32Ty,
271f22ef01cSRoman Divacky                                                            SrcIdx, false));
272f22ef01cSRoman Divacky       }
2733b0f4066SDimitry Andric     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2747d523365SDimitry Andric       // Canonicalize extractelement(cast) -> cast(extractelement).
2757d523365SDimitry Andric       // Bitcasts can change the number of vector elements, and they cost
2767d523365SDimitry Andric       // nothing.
277284c1978SDimitry Andric       if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
278c4394386SDimitry Andric         Value *EE = Builder.CreateExtractElement(CI->getOperand(0),
2793b0f4066SDimitry Andric                                                  EI.getIndexOperand());
280284c1978SDimitry Andric         Worklist.AddValue(EE);
2813b0f4066SDimitry Andric         return CastInst::Create(CI->getOpcode(), EE, EI.getType());
282f22ef01cSRoman Divacky       }
2833b0f4066SDimitry Andric     }
284f22ef01cSRoman Divacky   }
28591bc56edSDimitry Andric   return nullptr;
286f22ef01cSRoman Divacky }
287f22ef01cSRoman Divacky 
2887d523365SDimitry Andric /// If V is a shuffle of values that ONLY returns elements from either LHS or
2897d523365SDimitry Andric /// RHS, return the shuffle mask and true. Otherwise, return false.
2907d523365SDimitry Andric static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
291dff0c46cSDimitry Andric                                          SmallVectorImpl<Constant*> &Mask) {
29291bc56edSDimitry Andric   assert(LHS->getType() == RHS->getType() &&
293f22ef01cSRoman Divacky          "Invalid CollectSingleShuffleElements");
294f785676fSDimitry Andric   unsigned NumElts = V->getType()->getVectorNumElements();
295f22ef01cSRoman Divacky 
296f22ef01cSRoman Divacky   if (isa<UndefValue>(V)) {
297f22ef01cSRoman Divacky     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
298f22ef01cSRoman Divacky     return true;
299f22ef01cSRoman Divacky   }
300f22ef01cSRoman Divacky 
301f22ef01cSRoman Divacky   if (V == LHS) {
302f22ef01cSRoman Divacky     for (unsigned i = 0; i != NumElts; ++i)
303f22ef01cSRoman Divacky       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
304f22ef01cSRoman Divacky     return true;
305f22ef01cSRoman Divacky   }
306f22ef01cSRoman Divacky 
307f22ef01cSRoman Divacky   if (V == RHS) {
308f22ef01cSRoman Divacky     for (unsigned i = 0; i != NumElts; ++i)
309f22ef01cSRoman Divacky       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
310f22ef01cSRoman Divacky                                       i+NumElts));
311f22ef01cSRoman Divacky     return true;
312f22ef01cSRoman Divacky   }
313f22ef01cSRoman Divacky 
314f22ef01cSRoman Divacky   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
315f22ef01cSRoman Divacky     // If this is an insert of an extract from some other vector, include it.
316f22ef01cSRoman Divacky     Value *VecOp    = IEI->getOperand(0);
317f22ef01cSRoman Divacky     Value *ScalarOp = IEI->getOperand(1);
318f22ef01cSRoman Divacky     Value *IdxOp    = IEI->getOperand(2);
319f22ef01cSRoman Divacky 
320f22ef01cSRoman Divacky     if (!isa<ConstantInt>(IdxOp))
321f22ef01cSRoman Divacky       return false;
322f22ef01cSRoman Divacky     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
323f22ef01cSRoman Divacky 
324f22ef01cSRoman Divacky     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
32591bc56edSDimitry Andric       // We can handle this if the vector we are inserting into is
326f22ef01cSRoman Divacky       // transitively ok.
3277d523365SDimitry Andric       if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
328f22ef01cSRoman Divacky         // If so, update the mask to reflect the inserted undef.
329f22ef01cSRoman Divacky         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
330f22ef01cSRoman Divacky         return true;
331f22ef01cSRoman Divacky       }
332f22ef01cSRoman Divacky     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
33391bc56edSDimitry Andric       if (isa<ConstantInt>(EI->getOperand(1))) {
334f22ef01cSRoman Divacky         unsigned ExtractedIdx =
335f22ef01cSRoman Divacky         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
33691bc56edSDimitry Andric         unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
337f22ef01cSRoman Divacky 
338f22ef01cSRoman Divacky         // This must be extracting from either LHS or RHS.
339f22ef01cSRoman Divacky         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
34091bc56edSDimitry Andric           // We can handle this if the vector we are inserting into is
341f22ef01cSRoman Divacky           // transitively ok.
3427d523365SDimitry Andric           if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
343f22ef01cSRoman Divacky             // If so, update the mask to reflect the inserted value.
344f22ef01cSRoman Divacky             if (EI->getOperand(0) == LHS) {
345f22ef01cSRoman Divacky               Mask[InsertedIdx % NumElts] =
346f22ef01cSRoman Divacky               ConstantInt::get(Type::getInt32Ty(V->getContext()),
347f22ef01cSRoman Divacky                                ExtractedIdx);
348f22ef01cSRoman Divacky             } else {
349f22ef01cSRoman Divacky               assert(EI->getOperand(0) == RHS);
350f22ef01cSRoman Divacky               Mask[InsertedIdx % NumElts] =
351f22ef01cSRoman Divacky               ConstantInt::get(Type::getInt32Ty(V->getContext()),
35291bc56edSDimitry Andric                                ExtractedIdx + NumLHSElts);
353f22ef01cSRoman Divacky             }
354f22ef01cSRoman Divacky             return true;
355f22ef01cSRoman Divacky           }
356f22ef01cSRoman Divacky         }
357f22ef01cSRoman Divacky       }
358f22ef01cSRoman Divacky     }
359f22ef01cSRoman Divacky   }
360f22ef01cSRoman Divacky 
361f22ef01cSRoman Divacky   return false;
362f22ef01cSRoman Divacky }
363f22ef01cSRoman Divacky 
3647d523365SDimitry Andric /// If we have insertion into a vector that is wider than the vector that we
3657d523365SDimitry Andric /// are extracting from, try to widen the source vector to allow a single
3667d523365SDimitry Andric /// shufflevector to replace one or more insert/extract pairs.
3677d523365SDimitry Andric static void replaceExtractElements(InsertElementInst *InsElt,
3687d523365SDimitry Andric                                    ExtractElementInst *ExtElt,
3697d523365SDimitry Andric                                    InstCombiner &IC) {
3707d523365SDimitry Andric   VectorType *InsVecType = InsElt->getType();
3717d523365SDimitry Andric   VectorType *ExtVecType = ExtElt->getVectorOperandType();
3727d523365SDimitry Andric   unsigned NumInsElts = InsVecType->getVectorNumElements();
3737d523365SDimitry Andric   unsigned NumExtElts = ExtVecType->getVectorNumElements();
3747d523365SDimitry Andric 
3757d523365SDimitry Andric   // The inserted-to vector must be wider than the extracted-from vector.
3767d523365SDimitry Andric   if (InsVecType->getElementType() != ExtVecType->getElementType() ||
3777d523365SDimitry Andric       NumExtElts >= NumInsElts)
3787d523365SDimitry Andric     return;
3797d523365SDimitry Andric 
3807d523365SDimitry Andric   // Create a shuffle mask to widen the extended-from vector using undefined
3817d523365SDimitry Andric   // values. The mask selects all of the values of the original vector followed
3827d523365SDimitry Andric   // by as many undefined values as needed to create a vector of the same length
3837d523365SDimitry Andric   // as the inserted-to vector.
3847d523365SDimitry Andric   SmallVector<Constant *, 16> ExtendMask;
3857d523365SDimitry Andric   IntegerType *IntType = Type::getInt32Ty(InsElt->getContext());
3867d523365SDimitry Andric   for (unsigned i = 0; i < NumExtElts; ++i)
3877d523365SDimitry Andric     ExtendMask.push_back(ConstantInt::get(IntType, i));
3887d523365SDimitry Andric   for (unsigned i = NumExtElts; i < NumInsElts; ++i)
3897d523365SDimitry Andric     ExtendMask.push_back(UndefValue::get(IntType));
3907d523365SDimitry Andric 
3917d523365SDimitry Andric   Value *ExtVecOp = ExtElt->getVectorOperand();
392a8bcc4d8SDimitry Andric   auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
393a8bcc4d8SDimitry Andric   BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
394a8bcc4d8SDimitry Andric                                    ? ExtVecOpInst->getParent()
395a8bcc4d8SDimitry Andric                                    : ExtElt->getParent();
396a8bcc4d8SDimitry Andric 
397a8bcc4d8SDimitry Andric   // TODO: This restriction matches the basic block check below when creating
398a8bcc4d8SDimitry Andric   // new extractelement instructions. If that limitation is removed, this one
399a8bcc4d8SDimitry Andric   // could also be removed. But for now, we just bail out to ensure that we
400a8bcc4d8SDimitry Andric   // will replace the extractelement instruction that is feeding our
401a8bcc4d8SDimitry Andric   // insertelement instruction. This allows the insertelement to then be
402a8bcc4d8SDimitry Andric   // replaced by a shufflevector. If the insertelement is not replaced, we can
403a8bcc4d8SDimitry Andric   // induce infinite looping because there's an optimization for extractelement
404a8bcc4d8SDimitry Andric   // that will delete our widening shuffle. This would trigger another attempt
405a8bcc4d8SDimitry Andric   // here to create that shuffle, and we spin forever.
406a8bcc4d8SDimitry Andric   if (InsertionBlock != InsElt->getParent())
407a8bcc4d8SDimitry Andric     return;
408a8bcc4d8SDimitry Andric 
409d88c1a5aSDimitry Andric   // TODO: This restriction matches the check in visitInsertElementInst() and
410d88c1a5aSDimitry Andric   // prevents an infinite loop caused by not turning the extract/insert pair
411d88c1a5aSDimitry Andric   // into a shuffle. We really should not need either check, but we're lacking
412d88c1a5aSDimitry Andric   // folds for shufflevectors because we're afraid to generate shuffle masks
413d88c1a5aSDimitry Andric   // that the backend can't handle.
414d88c1a5aSDimitry Andric   if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
415d88c1a5aSDimitry Andric     return;
416d88c1a5aSDimitry Andric 
4177d523365SDimitry Andric   auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
4187d523365SDimitry Andric                                         ConstantVector::get(ExtendMask));
4197d523365SDimitry Andric 
4204d0b32cdSDimitry Andric   // Insert the new shuffle after the vector operand of the extract is defined
421444ed5c5SDimitry Andric   // (as long as it's not a PHI) or at the start of the basic block of the
422444ed5c5SDimitry Andric   // extract, so any subsequent extracts in the same basic block can use it.
423444ed5c5SDimitry Andric   // TODO: Insert before the earliest ExtractElementInst that is replaced.
424444ed5c5SDimitry Andric   if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
4254d0b32cdSDimitry Andric     WideVec->insertAfter(ExtVecOpInst);
426444ed5c5SDimitry Andric   else
4274d0b32cdSDimitry Andric     IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
4284d0b32cdSDimitry Andric 
4294d0b32cdSDimitry Andric   // Replace extracts from the original narrow vector with extracts from the new
4304d0b32cdSDimitry Andric   // wide vector.
4317d523365SDimitry Andric   for (User *U : ExtVecOp->users()) {
4324d0b32cdSDimitry Andric     ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
433444ed5c5SDimitry Andric     if (!OldExt || OldExt->getParent() != WideVec->getParent())
4344d0b32cdSDimitry Andric       continue;
4357d523365SDimitry Andric     auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
436db17bf38SDimitry Andric     NewExt->insertAfter(OldExt);
4373ca95b02SDimitry Andric     IC.replaceInstUsesWith(*OldExt, NewExt);
4387d523365SDimitry Andric   }
4397d523365SDimitry Andric }
44091bc56edSDimitry Andric 
44191bc56edSDimitry Andric /// We are building a shuffle to create V, which is a sequence of insertelement,
44291bc56edSDimitry Andric /// extractelement pairs. If PermittedRHS is set, then we must either use it or
44391bc56edSDimitry Andric /// not rely on the second vector source. Return a std::pair containing the
44491bc56edSDimitry Andric /// left and right vectors of the proposed shuffle (or 0), and set the Mask
44591bc56edSDimitry Andric /// parameter as required.
44691bc56edSDimitry Andric ///
44791bc56edSDimitry Andric /// Note: we intentionally don't try to fold earlier shuffles since they have
44891bc56edSDimitry Andric /// often been chosen carefully to be efficiently implementable on the target.
4492cab237bSDimitry Andric using ShuffleOps = std::pair<Value *, Value *>;
45091bc56edSDimitry Andric 
4517d523365SDimitry Andric static ShuffleOps collectShuffleElements(Value *V,
45291bc56edSDimitry Andric                                          SmallVectorImpl<Constant *> &Mask,
4537d523365SDimitry Andric                                          Value *PermittedRHS,
4547d523365SDimitry Andric                                          InstCombiner &IC) {
45591bc56edSDimitry Andric   assert(V->getType()->isVectorTy() && "Invalid shuffle!");
456d88c1a5aSDimitry Andric   unsigned NumElts = V->getType()->getVectorNumElements();
457f22ef01cSRoman Divacky 
458f22ef01cSRoman Divacky   if (isa<UndefValue>(V)) {
459f22ef01cSRoman Divacky     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
46091bc56edSDimitry Andric     return std::make_pair(
46191bc56edSDimitry Andric         PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
462dff0c46cSDimitry Andric   }
463dff0c46cSDimitry Andric 
464dff0c46cSDimitry Andric   if (isa<ConstantAggregateZero>(V)) {
465f22ef01cSRoman Divacky     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
46691bc56edSDimitry Andric     return std::make_pair(V, nullptr);
467dff0c46cSDimitry Andric   }
468dff0c46cSDimitry Andric 
469dff0c46cSDimitry Andric   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
470f22ef01cSRoman Divacky     // If this is an insert of an extract from some other vector, include it.
471f22ef01cSRoman Divacky     Value *VecOp    = IEI->getOperand(0);
472f22ef01cSRoman Divacky     Value *ScalarOp = IEI->getOperand(1);
473f22ef01cSRoman Divacky     Value *IdxOp    = IEI->getOperand(2);
474f22ef01cSRoman Divacky 
475f22ef01cSRoman Divacky     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
47691bc56edSDimitry Andric       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
477f22ef01cSRoman Divacky         unsigned ExtractedIdx =
478f22ef01cSRoman Divacky           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
479f22ef01cSRoman Divacky         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
480f22ef01cSRoman Divacky 
481f22ef01cSRoman Divacky         // Either the extracted from or inserted into vector must be RHSVec,
482f22ef01cSRoman Divacky         // otherwise we'd end up with a shuffle of three inputs.
48391bc56edSDimitry Andric         if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
48491bc56edSDimitry Andric           Value *RHS = EI->getOperand(0);
4857d523365SDimitry Andric           ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
48691bc56edSDimitry Andric           assert(LR.second == nullptr || LR.second == RHS);
48791bc56edSDimitry Andric 
48891bc56edSDimitry Andric           if (LR.first->getType() != RHS->getType()) {
4897d523365SDimitry Andric             // Although we are giving up for now, see if we can create extracts
4907d523365SDimitry Andric             // that match the inserts for another round of combining.
4917d523365SDimitry Andric             replaceExtractElements(IEI, EI, IC);
4927d523365SDimitry Andric 
49391bc56edSDimitry Andric             // We tried our best, but we can't find anything compatible with RHS
49491bc56edSDimitry Andric             // further up the chain. Return a trivial shuffle.
49591bc56edSDimitry Andric             for (unsigned i = 0; i < NumElts; ++i)
49691bc56edSDimitry Andric               Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
49791bc56edSDimitry Andric             return std::make_pair(V, nullptr);
49891bc56edSDimitry Andric           }
49991bc56edSDimitry Andric 
50091bc56edSDimitry Andric           unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
501f22ef01cSRoman Divacky           Mask[InsertedIdx % NumElts] =
502f22ef01cSRoman Divacky             ConstantInt::get(Type::getInt32Ty(V->getContext()),
50391bc56edSDimitry Andric                              NumLHSElts+ExtractedIdx);
50491bc56edSDimitry Andric           return std::make_pair(LR.first, RHS);
505f22ef01cSRoman Divacky         }
506f22ef01cSRoman Divacky 
50791bc56edSDimitry Andric         if (VecOp == PermittedRHS) {
50891bc56edSDimitry Andric           // We've gone as far as we can: anything on the other side of the
50991bc56edSDimitry Andric           // extractelement will already have been converted into a shuffle.
51091bc56edSDimitry Andric           unsigned NumLHSElts =
51191bc56edSDimitry Andric               EI->getOperand(0)->getType()->getVectorNumElements();
51291bc56edSDimitry Andric           for (unsigned i = 0; i != NumElts; ++i)
51391bc56edSDimitry Andric             Mask.push_back(ConstantInt::get(
51491bc56edSDimitry Andric                 Type::getInt32Ty(V->getContext()),
51591bc56edSDimitry Andric                 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
51691bc56edSDimitry Andric           return std::make_pair(EI->getOperand(0), PermittedRHS);
517f22ef01cSRoman Divacky         }
518f22ef01cSRoman Divacky 
519f22ef01cSRoman Divacky         // If this insertelement is a chain that comes from exactly these two
520f22ef01cSRoman Divacky         // vectors, return the vector and the effective shuffle.
52191bc56edSDimitry Andric         if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
5227d523365SDimitry Andric             collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
52391bc56edSDimitry Andric                                          Mask))
52491bc56edSDimitry Andric           return std::make_pair(EI->getOperand(0), PermittedRHS);
525f22ef01cSRoman Divacky       }
526f22ef01cSRoman Divacky     }
527f22ef01cSRoman Divacky   }
528f22ef01cSRoman Divacky 
5297d523365SDimitry Andric   // Otherwise, we can't do anything fancy. Return an identity vector.
530f22ef01cSRoman Divacky   for (unsigned i = 0; i != NumElts; ++i)
531f22ef01cSRoman Divacky     Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
53291bc56edSDimitry Andric   return std::make_pair(V, nullptr);
53391bc56edSDimitry Andric }
53491bc56edSDimitry Andric 
53591bc56edSDimitry Andric /// Try to find redundant insertvalue instructions, like the following ones:
53691bc56edSDimitry Andric ///  %0 = insertvalue { i8, i32 } undef, i8 %x, 0
53791bc56edSDimitry Andric ///  %1 = insertvalue { i8, i32 } %0,    i8 %y, 0
53891bc56edSDimitry Andric /// Here the second instruction inserts values at the same indices, as the
53991bc56edSDimitry Andric /// first one, making the first one redundant.
54091bc56edSDimitry Andric /// It should be transformed to:
54191bc56edSDimitry Andric ///  %0 = insertvalue { i8, i32 } undef, i8 %y, 0
54291bc56edSDimitry Andric Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
54391bc56edSDimitry Andric   bool IsRedundant = false;
54491bc56edSDimitry Andric   ArrayRef<unsigned int> FirstIndices = I.getIndices();
54591bc56edSDimitry Andric 
54691bc56edSDimitry Andric   // If there is a chain of insertvalue instructions (each of them except the
54791bc56edSDimitry Andric   // last one has only one use and it's another insertvalue insn from this
54891bc56edSDimitry Andric   // chain), check if any of the 'children' uses the same indices as the first
54991bc56edSDimitry Andric   // instruction. In this case, the first one is redundant.
55091bc56edSDimitry Andric   Value *V = &I;
55191bc56edSDimitry Andric   unsigned Depth = 0;
55291bc56edSDimitry Andric   while (V->hasOneUse() && Depth < 10) {
55391bc56edSDimitry Andric     User *U = V->user_back();
55491bc56edSDimitry Andric     auto UserInsInst = dyn_cast<InsertValueInst>(U);
55591bc56edSDimitry Andric     if (!UserInsInst || U->getOperand(0) != V)
55691bc56edSDimitry Andric       break;
55791bc56edSDimitry Andric     if (UserInsInst->getIndices() == FirstIndices) {
55891bc56edSDimitry Andric       IsRedundant = true;
55991bc56edSDimitry Andric       break;
56091bc56edSDimitry Andric     }
56191bc56edSDimitry Andric     V = UserInsInst;
56291bc56edSDimitry Andric     Depth++;
56391bc56edSDimitry Andric   }
56491bc56edSDimitry Andric 
56591bc56edSDimitry Andric   if (IsRedundant)
5663ca95b02SDimitry Andric     return replaceInstUsesWith(I, I.getOperand(0));
56791bc56edSDimitry Andric   return nullptr;
568f22ef01cSRoman Divacky }
569f22ef01cSRoman Divacky 
570d88c1a5aSDimitry Andric static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) {
571d88c1a5aSDimitry Andric   int MaskSize = Shuf.getMask()->getType()->getVectorNumElements();
572d88c1a5aSDimitry Andric   int VecSize = Shuf.getOperand(0)->getType()->getVectorNumElements();
573d88c1a5aSDimitry Andric 
574d88c1a5aSDimitry Andric   // A vector select does not change the size of the operands.
575d88c1a5aSDimitry Andric   if (MaskSize != VecSize)
576d88c1a5aSDimitry Andric     return false;
577d88c1a5aSDimitry Andric 
578d88c1a5aSDimitry Andric   // Each mask element must be undefined or choose a vector element from one of
579d88c1a5aSDimitry Andric   // the source operands without crossing vector lanes.
580d88c1a5aSDimitry Andric   for (int i = 0; i != MaskSize; ++i) {
581d88c1a5aSDimitry Andric     int Elt = Shuf.getMaskValue(i);
582d88c1a5aSDimitry Andric     if (Elt != -1 && Elt != i && Elt != i + VecSize)
583d88c1a5aSDimitry Andric       return false;
584d88c1a5aSDimitry Andric   }
585d88c1a5aSDimitry Andric 
586d88c1a5aSDimitry Andric   return true;
587d88c1a5aSDimitry Andric }
588d88c1a5aSDimitry Andric 
589d88c1a5aSDimitry Andric // Turn a chain of inserts that splats a value into a canonical insert + shuffle
590d88c1a5aSDimitry Andric // splat. That is:
591d88c1a5aSDimitry Andric // insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
592d88c1a5aSDimitry Andric // shufflevector(insertelt(X, %k, 0), undef, zero)
593d88c1a5aSDimitry Andric static Instruction *foldInsSequenceIntoBroadcast(InsertElementInst &InsElt) {
594d88c1a5aSDimitry Andric   // We are interested in the last insert in a chain. So, if this insert
595d88c1a5aSDimitry Andric   // has a single user, and that user is an insert, bail.
596d88c1a5aSDimitry Andric   if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
597d88c1a5aSDimitry Andric     return nullptr;
598d88c1a5aSDimitry Andric 
599d88c1a5aSDimitry Andric   VectorType *VT = cast<VectorType>(InsElt.getType());
600d88c1a5aSDimitry Andric   int NumElements = VT->getNumElements();
601d88c1a5aSDimitry Andric 
602d88c1a5aSDimitry Andric   // Do not try to do this for a one-element vector, since that's a nop,
603d88c1a5aSDimitry Andric   // and will cause an inf-loop.
604d88c1a5aSDimitry Andric   if (NumElements == 1)
605d88c1a5aSDimitry Andric     return nullptr;
606d88c1a5aSDimitry Andric 
607d88c1a5aSDimitry Andric   Value *SplatVal = InsElt.getOperand(1);
608d88c1a5aSDimitry Andric   InsertElementInst *CurrIE = &InsElt;
609d88c1a5aSDimitry Andric   SmallVector<bool, 16> ElementPresent(NumElements, false);
6102cab237bSDimitry Andric   InsertElementInst *FirstIE = nullptr;
611d88c1a5aSDimitry Andric 
612d88c1a5aSDimitry Andric   // Walk the chain backwards, keeping track of which indices we inserted into,
613d88c1a5aSDimitry Andric   // until we hit something that isn't an insert of the splatted value.
614d88c1a5aSDimitry Andric   while (CurrIE) {
6152cab237bSDimitry Andric     auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
616d88c1a5aSDimitry Andric     if (!Idx || CurrIE->getOperand(1) != SplatVal)
617d88c1a5aSDimitry Andric       return nullptr;
618d88c1a5aSDimitry Andric 
6192cab237bSDimitry Andric     auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
6202cab237bSDimitry Andric     // Check none of the intermediate steps have any additional uses, except
6212cab237bSDimitry Andric     // for the root insertelement instruction, which can be re-used, if it
6222cab237bSDimitry Andric     // inserts at position 0.
6232cab237bSDimitry Andric     if (CurrIE != &InsElt &&
6242cab237bSDimitry Andric         (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero())))
625d88c1a5aSDimitry Andric       return nullptr;
626d88c1a5aSDimitry Andric 
627d88c1a5aSDimitry Andric     ElementPresent[Idx->getZExtValue()] = true;
6282cab237bSDimitry Andric     FirstIE = CurrIE;
6292cab237bSDimitry Andric     CurrIE = NextIE;
630d88c1a5aSDimitry Andric   }
631d88c1a5aSDimitry Andric 
632d88c1a5aSDimitry Andric   // Make sure we've seen an insert into every element.
633d88c1a5aSDimitry Andric   if (llvm::any_of(ElementPresent, [](bool Present) { return !Present; }))
634d88c1a5aSDimitry Andric     return nullptr;
635d88c1a5aSDimitry Andric 
636d88c1a5aSDimitry Andric   // All right, create the insert + shuffle.
6372cab237bSDimitry Andric   Instruction *InsertFirst;
6382cab237bSDimitry Andric   if (cast<ConstantInt>(FirstIE->getOperand(2))->isZero())
6392cab237bSDimitry Andric     InsertFirst = FirstIE;
6402cab237bSDimitry Andric   else
6412cab237bSDimitry Andric     InsertFirst = InsertElementInst::Create(
642d88c1a5aSDimitry Andric         UndefValue::get(VT), SplatVal,
6432cab237bSDimitry Andric         ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 0),
6442cab237bSDimitry Andric         "", &InsElt);
645d88c1a5aSDimitry Andric 
646d88c1a5aSDimitry Andric   Constant *ZeroMask = ConstantAggregateZero::get(
647d88c1a5aSDimitry Andric       VectorType::get(Type::getInt32Ty(InsElt.getContext()), NumElements));
648d88c1a5aSDimitry Andric 
649d88c1a5aSDimitry Andric   return new ShuffleVectorInst(InsertFirst, UndefValue::get(VT), ZeroMask);
650d88c1a5aSDimitry Andric }
651d88c1a5aSDimitry Andric 
6527a7e6055SDimitry Andric /// If we have an insertelement instruction feeding into another insertelement
6537a7e6055SDimitry Andric /// and the 2nd is inserting a constant into the vector, canonicalize that
6547a7e6055SDimitry Andric /// constant insertion before the insertion of a variable:
6557a7e6055SDimitry Andric ///
6567a7e6055SDimitry Andric /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
6577a7e6055SDimitry Andric /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
6587a7e6055SDimitry Andric ///
6597a7e6055SDimitry Andric /// This has the potential of eliminating the 2nd insertelement instruction
6607a7e6055SDimitry Andric /// via constant folding of the scalar constant into a vector constant.
6617a7e6055SDimitry Andric static Instruction *hoistInsEltConst(InsertElementInst &InsElt2,
6627a7e6055SDimitry Andric                                      InstCombiner::BuilderTy &Builder) {
6637a7e6055SDimitry Andric   auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
6647a7e6055SDimitry Andric   if (!InsElt1 || !InsElt1->hasOneUse())
6657a7e6055SDimitry Andric     return nullptr;
6667a7e6055SDimitry Andric 
6677a7e6055SDimitry Andric   Value *X, *Y;
6687a7e6055SDimitry Andric   Constant *ScalarC;
6697a7e6055SDimitry Andric   ConstantInt *IdxC1, *IdxC2;
6707a7e6055SDimitry Andric   if (match(InsElt1->getOperand(0), m_Value(X)) &&
6717a7e6055SDimitry Andric       match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
6727a7e6055SDimitry Andric       match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
6737a7e6055SDimitry Andric       match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
6747a7e6055SDimitry Andric       match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
6757a7e6055SDimitry Andric     Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
6767a7e6055SDimitry Andric     return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
6777a7e6055SDimitry Andric   }
6787a7e6055SDimitry Andric 
6797a7e6055SDimitry Andric   return nullptr;
6807a7e6055SDimitry Andric }
6817a7e6055SDimitry Andric 
682d88c1a5aSDimitry Andric /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
683d88c1a5aSDimitry Andric /// --> shufflevector X, CVec', Mask'
684d88c1a5aSDimitry Andric static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) {
685d88c1a5aSDimitry Andric   auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
686d88c1a5aSDimitry Andric   // Bail out if the parent has more than one use. In that case, we'd be
687d88c1a5aSDimitry Andric   // replacing the insertelt with a shuffle, and that's not a clear win.
688d88c1a5aSDimitry Andric   if (!Inst || !Inst->hasOneUse())
689d88c1a5aSDimitry Andric     return nullptr;
690d88c1a5aSDimitry Andric   if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
691d88c1a5aSDimitry Andric     // The shuffle must have a constant vector operand. The insertelt must have
692d88c1a5aSDimitry Andric     // a constant scalar being inserted at a constant position in the vector.
693d88c1a5aSDimitry Andric     Constant *ShufConstVec, *InsEltScalar;
694d88c1a5aSDimitry Andric     uint64_t InsEltIndex;
695d88c1a5aSDimitry Andric     if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
696d88c1a5aSDimitry Andric         !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
697d88c1a5aSDimitry Andric         !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
698d88c1a5aSDimitry Andric       return nullptr;
699d88c1a5aSDimitry Andric 
700d88c1a5aSDimitry Andric     // Adding an element to an arbitrary shuffle could be expensive, but a
701d88c1a5aSDimitry Andric     // shuffle that selects elements from vectors without crossing lanes is
702d88c1a5aSDimitry Andric     // assumed cheap.
703d88c1a5aSDimitry Andric     // If we're just adding a constant into that shuffle, it will still be
704d88c1a5aSDimitry Andric     // cheap.
705d88c1a5aSDimitry Andric     if (!isShuffleEquivalentToSelect(*Shuf))
706d88c1a5aSDimitry Andric       return nullptr;
707d88c1a5aSDimitry Andric 
708d88c1a5aSDimitry Andric     // From the above 'select' check, we know that the mask has the same number
709d88c1a5aSDimitry Andric     // of elements as the vector input operands. We also know that each constant
710d88c1a5aSDimitry Andric     // input element is used in its lane and can not be used more than once by
711d88c1a5aSDimitry Andric     // the shuffle. Therefore, replace the constant in the shuffle's constant
712d88c1a5aSDimitry Andric     // vector with the insertelt constant. Replace the constant in the shuffle's
713d88c1a5aSDimitry Andric     // mask vector with the insertelt index plus the length of the vector
714d88c1a5aSDimitry Andric     // (because the constant vector operand of a shuffle is always the 2nd
715d88c1a5aSDimitry Andric     // operand).
716d88c1a5aSDimitry Andric     Constant *Mask = Shuf->getMask();
717d88c1a5aSDimitry Andric     unsigned NumElts = Mask->getType()->getVectorNumElements();
718d88c1a5aSDimitry Andric     SmallVector<Constant *, 16> NewShufElts(NumElts);
719d88c1a5aSDimitry Andric     SmallVector<Constant *, 16> NewMaskElts(NumElts);
720d88c1a5aSDimitry Andric     for (unsigned I = 0; I != NumElts; ++I) {
721d88c1a5aSDimitry Andric       if (I == InsEltIndex) {
722d88c1a5aSDimitry Andric         NewShufElts[I] = InsEltScalar;
723d88c1a5aSDimitry Andric         Type *Int32Ty = Type::getInt32Ty(Shuf->getContext());
724d88c1a5aSDimitry Andric         NewMaskElts[I] = ConstantInt::get(Int32Ty, InsEltIndex + NumElts);
725d88c1a5aSDimitry Andric       } else {
726d88c1a5aSDimitry Andric         // Copy over the existing values.
727d88c1a5aSDimitry Andric         NewShufElts[I] = ShufConstVec->getAggregateElement(I);
728d88c1a5aSDimitry Andric         NewMaskElts[I] = Mask->getAggregateElement(I);
729d88c1a5aSDimitry Andric       }
730d88c1a5aSDimitry Andric     }
731d88c1a5aSDimitry Andric 
732d88c1a5aSDimitry Andric     // Create new operands for a shuffle that includes the constant of the
733d88c1a5aSDimitry Andric     // original insertelt. The old shuffle will be dead now.
734d88c1a5aSDimitry Andric     return new ShuffleVectorInst(Shuf->getOperand(0),
735d88c1a5aSDimitry Andric                                  ConstantVector::get(NewShufElts),
736d88c1a5aSDimitry Andric                                  ConstantVector::get(NewMaskElts));
737d88c1a5aSDimitry Andric   } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
738d88c1a5aSDimitry Andric     // Transform sequences of insertelements ops with constant data/indexes into
739d88c1a5aSDimitry Andric     // a single shuffle op.
740d88c1a5aSDimitry Andric     unsigned NumElts = InsElt.getType()->getNumElements();
741d88c1a5aSDimitry Andric 
742d88c1a5aSDimitry Andric     uint64_t InsertIdx[2];
743d88c1a5aSDimitry Andric     Constant *Val[2];
744d88c1a5aSDimitry Andric     if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
745d88c1a5aSDimitry Andric         !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
746d88c1a5aSDimitry Andric         !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
747d88c1a5aSDimitry Andric         !match(IEI->getOperand(1), m_Constant(Val[1])))
748d88c1a5aSDimitry Andric       return nullptr;
749d88c1a5aSDimitry Andric     SmallVector<Constant *, 16> Values(NumElts);
750d88c1a5aSDimitry Andric     SmallVector<Constant *, 16> Mask(NumElts);
751d88c1a5aSDimitry Andric     auto ValI = std::begin(Val);
752d88c1a5aSDimitry Andric     // Generate new constant vector and mask.
753d88c1a5aSDimitry Andric     // We have 2 values/masks from the insertelements instructions. Insert them
754d88c1a5aSDimitry Andric     // into new value/mask vectors.
755d88c1a5aSDimitry Andric     for (uint64_t I : InsertIdx) {
756d88c1a5aSDimitry Andric       if (!Values[I]) {
757d88c1a5aSDimitry Andric         assert(!Mask[I]);
758d88c1a5aSDimitry Andric         Values[I] = *ValI;
759d88c1a5aSDimitry Andric         Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()),
760d88c1a5aSDimitry Andric                                    NumElts + I);
761d88c1a5aSDimitry Andric       }
762d88c1a5aSDimitry Andric       ++ValI;
763d88c1a5aSDimitry Andric     }
764d88c1a5aSDimitry Andric     // Remaining values are filled with 'undef' values.
765d88c1a5aSDimitry Andric     for (unsigned I = 0; I < NumElts; ++I) {
766d88c1a5aSDimitry Andric       if (!Values[I]) {
767d88c1a5aSDimitry Andric         assert(!Mask[I]);
768d88c1a5aSDimitry Andric         Values[I] = UndefValue::get(InsElt.getType()->getElementType());
769d88c1a5aSDimitry Andric         Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), I);
770d88c1a5aSDimitry Andric       }
771d88c1a5aSDimitry Andric     }
772d88c1a5aSDimitry Andric     // Create new operands for a shuffle that includes the constant of the
773d88c1a5aSDimitry Andric     // original insertelt.
774d88c1a5aSDimitry Andric     return new ShuffleVectorInst(IEI->getOperand(0),
775d88c1a5aSDimitry Andric                                  ConstantVector::get(Values),
776d88c1a5aSDimitry Andric                                  ConstantVector::get(Mask));
777d88c1a5aSDimitry Andric   }
778d88c1a5aSDimitry Andric   return nullptr;
779d88c1a5aSDimitry Andric }
780d88c1a5aSDimitry Andric 
781f22ef01cSRoman Divacky Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
782f22ef01cSRoman Divacky   Value *VecOp    = IE.getOperand(0);
783f22ef01cSRoman Divacky   Value *ScalarOp = IE.getOperand(1);
784f22ef01cSRoman Divacky   Value *IdxOp    = IE.getOperand(2);
785f22ef01cSRoman Divacky 
7862cab237bSDimitry Andric   if (auto *V = SimplifyInsertElementInst(
7872cab237bSDimitry Andric           VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE)))
7882cab237bSDimitry Andric     return replaceInstUsesWith(IE, V);
7892cab237bSDimitry Andric 
790f22ef01cSRoman Divacky   // Inserting an undef or into an undefined place, remove this.
791f22ef01cSRoman Divacky   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
7923ca95b02SDimitry Andric     replaceInstUsesWith(IE, VecOp);
793f22ef01cSRoman Divacky 
794f22ef01cSRoman Divacky   // If the inserted element was extracted from some other vector, and if the
795f22ef01cSRoman Divacky   // indexes are constant, try to turn this into a shufflevector operation.
796f22ef01cSRoman Divacky   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
79791bc56edSDimitry Andric     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
79891bc56edSDimitry Andric       unsigned NumInsertVectorElts = IE.getType()->getNumElements();
79991bc56edSDimitry Andric       unsigned NumExtractVectorElts =
80091bc56edSDimitry Andric           EI->getOperand(0)->getType()->getVectorNumElements();
801f22ef01cSRoman Divacky       unsigned ExtractedIdx =
802f22ef01cSRoman Divacky         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
803f22ef01cSRoman Divacky       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
804f22ef01cSRoman Divacky 
80591bc56edSDimitry Andric       if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
8063ca95b02SDimitry Andric         return replaceInstUsesWith(IE, VecOp);
807f22ef01cSRoman Divacky 
80891bc56edSDimitry Andric       if (InsertedIdx >= NumInsertVectorElts)  // Out of range insert.
8093ca95b02SDimitry Andric         return replaceInstUsesWith(IE, UndefValue::get(IE.getType()));
810f22ef01cSRoman Divacky 
811f22ef01cSRoman Divacky       // If we are extracting a value from a vector, then inserting it right
812f22ef01cSRoman Divacky       // back into the same place, just use the input vector.
813f22ef01cSRoman Divacky       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8143ca95b02SDimitry Andric         return replaceInstUsesWith(IE, VecOp);
815f22ef01cSRoman Divacky 
816f22ef01cSRoman Divacky       // If this insertelement isn't used by some other insertelement, turn it
817f22ef01cSRoman Divacky       // (and any insertelements it points to), into one big shuffle.
81891bc56edSDimitry Andric       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
819dff0c46cSDimitry Andric         SmallVector<Constant*, 16> Mask;
8207d523365SDimitry Andric         ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
82191bc56edSDimitry Andric 
82291bc56edSDimitry Andric         // The proposed shuffle may be trivial, in which case we shouldn't
82391bc56edSDimitry Andric         // perform the combine.
82491bc56edSDimitry Andric         if (LR.first != &IE && LR.second != &IE) {
825f22ef01cSRoman Divacky           // We now have a shuffle of LHS, RHS, Mask.
82691bc56edSDimitry Andric           if (LR.second == nullptr)
82791bc56edSDimitry Andric             LR.second = UndefValue::get(LR.first->getType());
82891bc56edSDimitry Andric           return new ShuffleVectorInst(LR.first, LR.second,
82991bc56edSDimitry Andric                                        ConstantVector::get(Mask));
83091bc56edSDimitry Andric         }
831f22ef01cSRoman Divacky       }
832f22ef01cSRoman Divacky     }
833f22ef01cSRoman Divacky   }
834f22ef01cSRoman Divacky 
835d88c1a5aSDimitry Andric   unsigned VWidth = VecOp->getType()->getVectorNumElements();
836f22ef01cSRoman Divacky   APInt UndefElts(VWidth, 0);
837f22ef01cSRoman Divacky   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
8382754fe60SDimitry Andric   if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
8392754fe60SDimitry Andric     if (V != &IE)
8403ca95b02SDimitry Andric       return replaceInstUsesWith(IE, V);
841f22ef01cSRoman Divacky     return &IE;
8422754fe60SDimitry Andric   }
843f22ef01cSRoman Divacky 
844d88c1a5aSDimitry Andric   if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE))
845d88c1a5aSDimitry Andric     return Shuf;
846d88c1a5aSDimitry Andric 
847c4394386SDimitry Andric   if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder))
8487a7e6055SDimitry Andric     return NewInsElt;
8497a7e6055SDimitry Andric 
850d88c1a5aSDimitry Andric   // Turn a sequence of inserts that broadcasts a scalar into a single
851d88c1a5aSDimitry Andric   // insert + shufflevector.
852d88c1a5aSDimitry Andric   if (Instruction *Broadcast = foldInsSequenceIntoBroadcast(IE))
853d88c1a5aSDimitry Andric     return Broadcast;
854d88c1a5aSDimitry Andric 
85591bc56edSDimitry Andric   return nullptr;
856f22ef01cSRoman Divacky }
857f22ef01cSRoman Divacky 
858f785676fSDimitry Andric /// Return true if we can evaluate the specified expression tree if the vector
859f785676fSDimitry Andric /// elements were shuffled in a different order.
860f785676fSDimitry Andric static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
861f785676fSDimitry Andric                                 unsigned Depth = 5) {
862f785676fSDimitry Andric   // We can always reorder the elements of a constant.
863f785676fSDimitry Andric   if (isa<Constant>(V))
864f785676fSDimitry Andric     return true;
865f785676fSDimitry Andric 
866f785676fSDimitry Andric   // We won't reorder vector arguments. No IPO here.
867f785676fSDimitry Andric   Instruction *I = dyn_cast<Instruction>(V);
868f785676fSDimitry Andric   if (!I) return false;
869f785676fSDimitry Andric 
870f785676fSDimitry Andric   // Two users may expect different orders of the elements. Don't try it.
871f785676fSDimitry Andric   if (!I->hasOneUse())
872f785676fSDimitry Andric     return false;
873f785676fSDimitry Andric 
874f785676fSDimitry Andric   if (Depth == 0) return false;
875f785676fSDimitry Andric 
876f785676fSDimitry Andric   switch (I->getOpcode()) {
877f785676fSDimitry Andric     case Instruction::Add:
878f785676fSDimitry Andric     case Instruction::FAdd:
879f785676fSDimitry Andric     case Instruction::Sub:
880f785676fSDimitry Andric     case Instruction::FSub:
881f785676fSDimitry Andric     case Instruction::Mul:
882f785676fSDimitry Andric     case Instruction::FMul:
883f785676fSDimitry Andric     case Instruction::UDiv:
884f785676fSDimitry Andric     case Instruction::SDiv:
885f785676fSDimitry Andric     case Instruction::FDiv:
886f785676fSDimitry Andric     case Instruction::URem:
887f785676fSDimitry Andric     case Instruction::SRem:
888f785676fSDimitry Andric     case Instruction::FRem:
889f785676fSDimitry Andric     case Instruction::Shl:
890f785676fSDimitry Andric     case Instruction::LShr:
891f785676fSDimitry Andric     case Instruction::AShr:
892f785676fSDimitry Andric     case Instruction::And:
893f785676fSDimitry Andric     case Instruction::Or:
894f785676fSDimitry Andric     case Instruction::Xor:
895f785676fSDimitry Andric     case Instruction::ICmp:
896f785676fSDimitry Andric     case Instruction::FCmp:
897f785676fSDimitry Andric     case Instruction::Trunc:
898f785676fSDimitry Andric     case Instruction::ZExt:
899f785676fSDimitry Andric     case Instruction::SExt:
900f785676fSDimitry Andric     case Instruction::FPToUI:
901f785676fSDimitry Andric     case Instruction::FPToSI:
902f785676fSDimitry Andric     case Instruction::UIToFP:
903f785676fSDimitry Andric     case Instruction::SIToFP:
904f785676fSDimitry Andric     case Instruction::FPTrunc:
905f785676fSDimitry Andric     case Instruction::FPExt:
906f785676fSDimitry Andric     case Instruction::GetElementPtr: {
9077d523365SDimitry Andric       for (Value *Operand : I->operands()) {
9087d523365SDimitry Andric         if (!CanEvaluateShuffled(Operand, Mask, Depth-1))
909f785676fSDimitry Andric           return false;
910f785676fSDimitry Andric       }
911f785676fSDimitry Andric       return true;
912f785676fSDimitry Andric     }
913f785676fSDimitry Andric     case Instruction::InsertElement: {
914f785676fSDimitry Andric       ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
915f785676fSDimitry Andric       if (!CI) return false;
916f785676fSDimitry Andric       int ElementNumber = CI->getLimitedValue();
917f785676fSDimitry Andric 
918f785676fSDimitry Andric       // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
919f785676fSDimitry Andric       // can't put an element into multiple indices.
920f785676fSDimitry Andric       bool SeenOnce = false;
921f785676fSDimitry Andric       for (int i = 0, e = Mask.size(); i != e; ++i) {
922f785676fSDimitry Andric         if (Mask[i] == ElementNumber) {
923f785676fSDimitry Andric           if (SeenOnce)
924f785676fSDimitry Andric             return false;
925f785676fSDimitry Andric           SeenOnce = true;
926f785676fSDimitry Andric         }
927f785676fSDimitry Andric       }
928f785676fSDimitry Andric       return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
929f785676fSDimitry Andric     }
930f785676fSDimitry Andric   }
931f785676fSDimitry Andric   return false;
932f785676fSDimitry Andric }
933f785676fSDimitry Andric 
934f785676fSDimitry Andric /// Rebuild a new instruction just like 'I' but with the new operands given.
935f785676fSDimitry Andric /// In the event of type mismatch, the type of the operands is correct.
9367d523365SDimitry Andric static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
937f785676fSDimitry Andric   // We don't want to use the IRBuilder here because we want the replacement
938f785676fSDimitry Andric   // instructions to appear next to 'I', not the builder's insertion point.
939f785676fSDimitry Andric   switch (I->getOpcode()) {
940f785676fSDimitry Andric     case Instruction::Add:
941f785676fSDimitry Andric     case Instruction::FAdd:
942f785676fSDimitry Andric     case Instruction::Sub:
943f785676fSDimitry Andric     case Instruction::FSub:
944f785676fSDimitry Andric     case Instruction::Mul:
945f785676fSDimitry Andric     case Instruction::FMul:
946f785676fSDimitry Andric     case Instruction::UDiv:
947f785676fSDimitry Andric     case Instruction::SDiv:
948f785676fSDimitry Andric     case Instruction::FDiv:
949f785676fSDimitry Andric     case Instruction::URem:
950f785676fSDimitry Andric     case Instruction::SRem:
951f785676fSDimitry Andric     case Instruction::FRem:
952f785676fSDimitry Andric     case Instruction::Shl:
953f785676fSDimitry Andric     case Instruction::LShr:
954f785676fSDimitry Andric     case Instruction::AShr:
955f785676fSDimitry Andric     case Instruction::And:
956f785676fSDimitry Andric     case Instruction::Or:
957f785676fSDimitry Andric     case Instruction::Xor: {
958f785676fSDimitry Andric       BinaryOperator *BO = cast<BinaryOperator>(I);
959f785676fSDimitry Andric       assert(NewOps.size() == 2 && "binary operator with #ops != 2");
960f785676fSDimitry Andric       BinaryOperator *New =
961f785676fSDimitry Andric           BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
962f785676fSDimitry Andric                                  NewOps[0], NewOps[1], "", BO);
963f785676fSDimitry Andric       if (isa<OverflowingBinaryOperator>(BO)) {
964f785676fSDimitry Andric         New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
965f785676fSDimitry Andric         New->setHasNoSignedWrap(BO->hasNoSignedWrap());
966f785676fSDimitry Andric       }
967f785676fSDimitry Andric       if (isa<PossiblyExactOperator>(BO)) {
968f785676fSDimitry Andric         New->setIsExact(BO->isExact());
969f785676fSDimitry Andric       }
97091bc56edSDimitry Andric       if (isa<FPMathOperator>(BO))
97191bc56edSDimitry Andric         New->copyFastMathFlags(I);
972f785676fSDimitry Andric       return New;
973f785676fSDimitry Andric     }
974f785676fSDimitry Andric     case Instruction::ICmp:
975f785676fSDimitry Andric       assert(NewOps.size() == 2 && "icmp with #ops != 2");
976f785676fSDimitry Andric       return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
977f785676fSDimitry Andric                           NewOps[0], NewOps[1]);
978f785676fSDimitry Andric     case Instruction::FCmp:
979f785676fSDimitry Andric       assert(NewOps.size() == 2 && "fcmp with #ops != 2");
980f785676fSDimitry Andric       return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
981f785676fSDimitry Andric                           NewOps[0], NewOps[1]);
982f785676fSDimitry Andric     case Instruction::Trunc:
983f785676fSDimitry Andric     case Instruction::ZExt:
984f785676fSDimitry Andric     case Instruction::SExt:
985f785676fSDimitry Andric     case Instruction::FPToUI:
986f785676fSDimitry Andric     case Instruction::FPToSI:
987f785676fSDimitry Andric     case Instruction::UIToFP:
988f785676fSDimitry Andric     case Instruction::SIToFP:
989f785676fSDimitry Andric     case Instruction::FPTrunc:
990f785676fSDimitry Andric     case Instruction::FPExt: {
991f785676fSDimitry Andric       // It's possible that the mask has a different number of elements from
992f785676fSDimitry Andric       // the original cast. We recompute the destination type to match the mask.
993f785676fSDimitry Andric       Type *DestTy =
994f785676fSDimitry Andric           VectorType::get(I->getType()->getScalarType(),
995f785676fSDimitry Andric                           NewOps[0]->getType()->getVectorNumElements());
996f785676fSDimitry Andric       assert(NewOps.size() == 1 && "cast with #ops != 1");
997f785676fSDimitry Andric       return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
998f785676fSDimitry Andric                               "", I);
999f785676fSDimitry Andric     }
1000f785676fSDimitry Andric     case Instruction::GetElementPtr: {
1001f785676fSDimitry Andric       Value *Ptr = NewOps[0];
1002f785676fSDimitry Andric       ArrayRef<Value*> Idx = NewOps.slice(1);
1003ff0cc061SDimitry Andric       GetElementPtrInst *GEP = GetElementPtrInst::Create(
1004ff0cc061SDimitry Andric           cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
1005f785676fSDimitry Andric       GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
1006f785676fSDimitry Andric       return GEP;
1007f785676fSDimitry Andric     }
1008f785676fSDimitry Andric   }
1009f785676fSDimitry Andric   llvm_unreachable("failed to rebuild vector instructions");
1010f785676fSDimitry Andric }
1011f785676fSDimitry Andric 
1012f785676fSDimitry Andric Value *
1013f785676fSDimitry Andric InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
1014f785676fSDimitry Andric   // Mask.size() does not need to be equal to the number of vector elements.
1015f785676fSDimitry Andric 
1016f785676fSDimitry Andric   assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
10172cab237bSDimitry Andric   Type *EltTy = V->getType()->getScalarType();
10182cab237bSDimitry Andric   if (isa<UndefValue>(V))
10192cab237bSDimitry Andric     return UndefValue::get(VectorType::get(EltTy, Mask.size()));
10202cab237bSDimitry Andric 
10212cab237bSDimitry Andric   if (isa<ConstantAggregateZero>(V))
10222cab237bSDimitry Andric     return ConstantAggregateZero::get(VectorType::get(EltTy, Mask.size()));
10232cab237bSDimitry Andric 
1024f785676fSDimitry Andric   if (Constant *C = dyn_cast<Constant>(V)) {
1025f785676fSDimitry Andric     SmallVector<Constant *, 16> MaskValues;
1026f785676fSDimitry Andric     for (int i = 0, e = Mask.size(); i != e; ++i) {
1027f785676fSDimitry Andric       if (Mask[i] == -1)
1028c4394386SDimitry Andric         MaskValues.push_back(UndefValue::get(Builder.getInt32Ty()));
1029f785676fSDimitry Andric       else
1030c4394386SDimitry Andric         MaskValues.push_back(Builder.getInt32(Mask[i]));
1031f785676fSDimitry Andric     }
1032f785676fSDimitry Andric     return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
1033f785676fSDimitry Andric                                           ConstantVector::get(MaskValues));
1034f785676fSDimitry Andric   }
1035f785676fSDimitry Andric 
1036f785676fSDimitry Andric   Instruction *I = cast<Instruction>(V);
1037f785676fSDimitry Andric   switch (I->getOpcode()) {
1038f785676fSDimitry Andric     case Instruction::Add:
1039f785676fSDimitry Andric     case Instruction::FAdd:
1040f785676fSDimitry Andric     case Instruction::Sub:
1041f785676fSDimitry Andric     case Instruction::FSub:
1042f785676fSDimitry Andric     case Instruction::Mul:
1043f785676fSDimitry Andric     case Instruction::FMul:
1044f785676fSDimitry Andric     case Instruction::UDiv:
1045f785676fSDimitry Andric     case Instruction::SDiv:
1046f785676fSDimitry Andric     case Instruction::FDiv:
1047f785676fSDimitry Andric     case Instruction::URem:
1048f785676fSDimitry Andric     case Instruction::SRem:
1049f785676fSDimitry Andric     case Instruction::FRem:
1050f785676fSDimitry Andric     case Instruction::Shl:
1051f785676fSDimitry Andric     case Instruction::LShr:
1052f785676fSDimitry Andric     case Instruction::AShr:
1053f785676fSDimitry Andric     case Instruction::And:
1054f785676fSDimitry Andric     case Instruction::Or:
1055f785676fSDimitry Andric     case Instruction::Xor:
1056f785676fSDimitry Andric     case Instruction::ICmp:
1057f785676fSDimitry Andric     case Instruction::FCmp:
1058f785676fSDimitry Andric     case Instruction::Trunc:
1059f785676fSDimitry Andric     case Instruction::ZExt:
1060f785676fSDimitry Andric     case Instruction::SExt:
1061f785676fSDimitry Andric     case Instruction::FPToUI:
1062f785676fSDimitry Andric     case Instruction::FPToSI:
1063f785676fSDimitry Andric     case Instruction::UIToFP:
1064f785676fSDimitry Andric     case Instruction::SIToFP:
1065f785676fSDimitry Andric     case Instruction::FPTrunc:
1066f785676fSDimitry Andric     case Instruction::FPExt:
1067f785676fSDimitry Andric     case Instruction::Select:
1068f785676fSDimitry Andric     case Instruction::GetElementPtr: {
1069f785676fSDimitry Andric       SmallVector<Value*, 8> NewOps;
1070f785676fSDimitry Andric       bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
1071f785676fSDimitry Andric       for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
1072f785676fSDimitry Andric         Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
1073f785676fSDimitry Andric         NewOps.push_back(V);
1074f785676fSDimitry Andric         NeedsRebuild |= (V != I->getOperand(i));
1075f785676fSDimitry Andric       }
1076f785676fSDimitry Andric       if (NeedsRebuild) {
10777d523365SDimitry Andric         return buildNew(I, NewOps);
1078f785676fSDimitry Andric       }
1079f785676fSDimitry Andric       return I;
1080f785676fSDimitry Andric     }
1081f785676fSDimitry Andric     case Instruction::InsertElement: {
1082f785676fSDimitry Andric       int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
1083f785676fSDimitry Andric 
1084f785676fSDimitry Andric       // The insertelement was inserting at Element. Figure out which element
1085f785676fSDimitry Andric       // that becomes after shuffling. The answer is guaranteed to be unique
1086f785676fSDimitry Andric       // by CanEvaluateShuffled.
1087f785676fSDimitry Andric       bool Found = false;
1088f785676fSDimitry Andric       int Index = 0;
1089f785676fSDimitry Andric       for (int e = Mask.size(); Index != e; ++Index) {
1090f785676fSDimitry Andric         if (Mask[Index] == Element) {
1091f785676fSDimitry Andric           Found = true;
1092f785676fSDimitry Andric           break;
1093f785676fSDimitry Andric         }
1094f785676fSDimitry Andric       }
1095f785676fSDimitry Andric 
109691bc56edSDimitry Andric       // If element is not in Mask, no need to handle the operand 1 (element to
109791bc56edSDimitry Andric       // be inserted). Just evaluate values in operand 0 according to Mask.
1098f785676fSDimitry Andric       if (!Found)
109991bc56edSDimitry Andric         return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
1100f785676fSDimitry Andric 
1101f785676fSDimitry Andric       Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
1102f785676fSDimitry Andric       return InsertElementInst::Create(V, I->getOperand(1),
1103c4394386SDimitry Andric                                        Builder.getInt32(Index), "", I);
1104f785676fSDimitry Andric     }
1105f785676fSDimitry Andric   }
1106f785676fSDimitry Andric   llvm_unreachable("failed to reorder elements of vector instruction!");
1107f785676fSDimitry Andric }
1108f22ef01cSRoman Divacky 
11097d523365SDimitry Andric static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask,
111091bc56edSDimitry Andric                                   bool &isLHSID, bool &isRHSID) {
111191bc56edSDimitry Andric   isLHSID = isRHSID = true;
111291bc56edSDimitry Andric 
111391bc56edSDimitry Andric   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
111491bc56edSDimitry Andric     if (Mask[i] < 0) continue;  // Ignore undef values.
111591bc56edSDimitry Andric     // Is this an identity shuffle of the LHS value?
111691bc56edSDimitry Andric     isLHSID &= (Mask[i] == (int)i);
111791bc56edSDimitry Andric 
111891bc56edSDimitry Andric     // Is this an identity shuffle of the RHS value?
111991bc56edSDimitry Andric     isRHSID &= (Mask[i]-e == i);
112091bc56edSDimitry Andric   }
112191bc56edSDimitry Andric }
112291bc56edSDimitry Andric 
1123ff0cc061SDimitry Andric // Returns true if the shuffle is extracting a contiguous range of values from
1124ff0cc061SDimitry Andric // LHS, for example:
1125ff0cc061SDimitry Andric //                 +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1126ff0cc061SDimitry Andric //   Input:        |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
1127ff0cc061SDimitry Andric //   Shuffles to:  |EE|FF|GG|HH|
1128ff0cc061SDimitry Andric //                 +--+--+--+--+
1129ff0cc061SDimitry Andric static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
1130ff0cc061SDimitry Andric                                        SmallVector<int, 16> &Mask) {
1131d88c1a5aSDimitry Andric   unsigned LHSElems = SVI.getOperand(0)->getType()->getVectorNumElements();
1132ff0cc061SDimitry Andric   unsigned MaskElems = Mask.size();
1133ff0cc061SDimitry Andric   unsigned BegIdx = Mask.front();
1134ff0cc061SDimitry Andric   unsigned EndIdx = Mask.back();
1135ff0cc061SDimitry Andric   if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
1136ff0cc061SDimitry Andric     return false;
1137ff0cc061SDimitry Andric   for (unsigned I = 0; I != MaskElems; ++I)
1138ff0cc061SDimitry Andric     if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
1139ff0cc061SDimitry Andric       return false;
1140ff0cc061SDimitry Andric   return true;
1141ff0cc061SDimitry Andric }
1142ff0cc061SDimitry Andric 
1143f22ef01cSRoman Divacky Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
1144f22ef01cSRoman Divacky   Value *LHS = SVI.getOperand(0);
1145f22ef01cSRoman Divacky   Value *RHS = SVI.getOperand(1);
1146dff0c46cSDimitry Andric   SmallVector<int, 16> Mask = SVI.getShuffleMask();
1147ff0cc061SDimitry Andric   Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
1148f22ef01cSRoman Divacky 
1149db17bf38SDimitry Andric   if (auto *V = SimplifyShuffleVectorInst(
1150db17bf38SDimitry Andric           LHS, RHS, SVI.getMask(), SVI.getType(), SQ.getWithInstruction(&SVI)))
11517a7e6055SDimitry Andric     return replaceInstUsesWith(SVI, V);
11527a7e6055SDimitry Andric 
1153f22ef01cSRoman Divacky   bool MadeChange = false;
1154d88c1a5aSDimitry Andric   unsigned VWidth = SVI.getType()->getVectorNumElements();
1155f22ef01cSRoman Divacky 
1156f22ef01cSRoman Divacky   APInt UndefElts(VWidth, 0);
1157f22ef01cSRoman Divacky   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
11582754fe60SDimitry Andric   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11592754fe60SDimitry Andric     if (V != &SVI)
11603ca95b02SDimitry Andric       return replaceInstUsesWith(SVI, V);
11612cab237bSDimitry Andric     return &SVI;
1162f22ef01cSRoman Divacky   }
1163f22ef01cSRoman Divacky 
1164d88c1a5aSDimitry Andric   unsigned LHSWidth = LHS->getType()->getVectorNumElements();
1165dff0c46cSDimitry Andric 
1166f22ef01cSRoman Divacky   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
1167f22ef01cSRoman Divacky   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
1168f22ef01cSRoman Divacky   if (LHS == RHS || isa<UndefValue>(LHS)) {
1169f22ef01cSRoman Divacky     if (isa<UndefValue>(LHS) && LHS == RHS) {
1170f22ef01cSRoman Divacky       // shuffle(undef,undef,mask) -> undef.
1171f785676fSDimitry Andric       Value *Result = (VWidth == LHSWidth)
1172dff0c46cSDimitry Andric                       ? LHS : UndefValue::get(SVI.getType());
11733ca95b02SDimitry Andric       return replaceInstUsesWith(SVI, Result);
1174f22ef01cSRoman Divacky     }
1175f22ef01cSRoman Divacky 
1176f22ef01cSRoman Divacky     // Remap any references to RHS to use LHS.
1177dff0c46cSDimitry Andric     SmallVector<Constant*, 16> Elts;
1178dff0c46cSDimitry Andric     for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
1179dff0c46cSDimitry Andric       if (Mask[i] < 0) {
1180ff0cc061SDimitry Andric         Elts.push_back(UndefValue::get(Int32Ty));
1181dff0c46cSDimitry Andric         continue;
1182dff0c46cSDimitry Andric       }
1183dff0c46cSDimitry Andric 
11842754fe60SDimitry Andric       if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
11852754fe60SDimitry Andric           (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
11862754fe60SDimitry Andric         Mask[i] = -1;     // Turn into undef.
1187ff0cc061SDimitry Andric         Elts.push_back(UndefValue::get(Int32Ty));
1188f22ef01cSRoman Divacky       } else {
1189f22ef01cSRoman Divacky         Mask[i] = Mask[i] % e;  // Force to LHS.
1190ff0cc061SDimitry Andric         Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
1191f22ef01cSRoman Divacky       }
1192f22ef01cSRoman Divacky     }
1193f22ef01cSRoman Divacky     SVI.setOperand(0, SVI.getOperand(1));
1194f22ef01cSRoman Divacky     SVI.setOperand(1, UndefValue::get(RHS->getType()));
1195f22ef01cSRoman Divacky     SVI.setOperand(2, ConstantVector::get(Elts));
1196f22ef01cSRoman Divacky     LHS = SVI.getOperand(0);
1197f22ef01cSRoman Divacky     RHS = SVI.getOperand(1);
1198f22ef01cSRoman Divacky     MadeChange = true;
1199f22ef01cSRoman Divacky   }
1200f22ef01cSRoman Divacky 
1201dff0c46cSDimitry Andric   if (VWidth == LHSWidth) {
1202f22ef01cSRoman Divacky     // Analyze the shuffle, are the LHS or RHS and identity shuffles?
120391bc56edSDimitry Andric     bool isLHSID, isRHSID;
12047d523365SDimitry Andric     recognizeIdentityMask(Mask, isLHSID, isRHSID);
1205f22ef01cSRoman Divacky 
1206f22ef01cSRoman Divacky     // Eliminate identity shuffles.
12073ca95b02SDimitry Andric     if (isLHSID) return replaceInstUsesWith(SVI, LHS);
12083ca95b02SDimitry Andric     if (isRHSID) return replaceInstUsesWith(SVI, RHS);
1209dff0c46cSDimitry Andric   }
1210f22ef01cSRoman Divacky 
1211f785676fSDimitry Andric   if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
1212f785676fSDimitry Andric     Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
12133ca95b02SDimitry Andric     return replaceInstUsesWith(SVI, V);
1214f785676fSDimitry Andric   }
1215f785676fSDimitry Andric 
1216ff0cc061SDimitry Andric   // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
1217ff0cc061SDimitry Andric   // a non-vector type. We can instead bitcast the original vector followed by
1218ff0cc061SDimitry Andric   // an extract of the desired element:
1219ff0cc061SDimitry Andric   //
1220ff0cc061SDimitry Andric   //   %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
1221ff0cc061SDimitry Andric   //                         <4 x i32> <i32 0, i32 1, i32 2, i32 3>
1222ff0cc061SDimitry Andric   //   %1 = bitcast <4 x i8> %sroa to i32
1223ff0cc061SDimitry Andric   // Becomes:
1224ff0cc061SDimitry Andric   //   %bc = bitcast <16 x i8> %in to <4 x i32>
1225ff0cc061SDimitry Andric   //   %ext = extractelement <4 x i32> %bc, i32 0
1226ff0cc061SDimitry Andric   //
1227ff0cc061SDimitry Andric   // If the shuffle is extracting a contiguous range of values from the input
1228ff0cc061SDimitry Andric   // vector then each use which is a bitcast of the extracted size can be
1229ff0cc061SDimitry Andric   // replaced. This will work if the vector types are compatible, and the begin
1230ff0cc061SDimitry Andric   // index is aligned to a value in the casted vector type. If the begin index
1231ff0cc061SDimitry Andric   // isn't aligned then we can shuffle the original vector (keeping the same
1232ff0cc061SDimitry Andric   // vector type) before extracting.
1233ff0cc061SDimitry Andric   //
1234ff0cc061SDimitry Andric   // This code will bail out if the target type is fundamentally incompatible
1235ff0cc061SDimitry Andric   // with vectors of the source type.
1236ff0cc061SDimitry Andric   //
1237ff0cc061SDimitry Andric   // Example of <16 x i8>, target type i32:
1238ff0cc061SDimitry Andric   // Index range [4,8):         v-----------v Will work.
1239ff0cc061SDimitry Andric   //                +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1240ff0cc061SDimitry Andric   //     <16 x i8>: |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |  |
1241ff0cc061SDimitry Andric   //     <4 x i32>: |           |           |           |           |
1242ff0cc061SDimitry Andric   //                +-----------+-----------+-----------+-----------+
1243ff0cc061SDimitry Andric   // Index range [6,10):              ^-----------^ Needs an extra shuffle.
1244ff0cc061SDimitry Andric   // Target type i40:           ^--------------^ Won't work, bail.
1245ff0cc061SDimitry Andric   if (isShuffleExtractingFromLHS(SVI, Mask)) {
1246ff0cc061SDimitry Andric     Value *V = LHS;
1247ff0cc061SDimitry Andric     unsigned MaskElems = Mask.size();
1248ff0cc061SDimitry Andric     VectorType *SrcTy = cast<VectorType>(V->getType());
1249ff0cc061SDimitry Andric     unsigned VecBitWidth = SrcTy->getBitWidth();
1250ff0cc061SDimitry Andric     unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
1251ff0cc061SDimitry Andric     assert(SrcElemBitWidth && "vector elements must have a bitwidth");
1252ff0cc061SDimitry Andric     unsigned SrcNumElems = SrcTy->getNumElements();
1253ff0cc061SDimitry Andric     SmallVector<BitCastInst *, 8> BCs;
1254ff0cc061SDimitry Andric     DenseMap<Type *, Value *> NewBCs;
1255ff0cc061SDimitry Andric     for (User *U : SVI.users())
1256ff0cc061SDimitry Andric       if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
1257ff0cc061SDimitry Andric         if (!BC->use_empty())
1258ff0cc061SDimitry Andric           // Only visit bitcasts that weren't previously handled.
1259ff0cc061SDimitry Andric           BCs.push_back(BC);
1260ff0cc061SDimitry Andric     for (BitCastInst *BC : BCs) {
12617a7e6055SDimitry Andric       unsigned BegIdx = Mask.front();
1262ff0cc061SDimitry Andric       Type *TgtTy = BC->getDestTy();
1263ff0cc061SDimitry Andric       unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
1264ff0cc061SDimitry Andric       if (!TgtElemBitWidth)
1265ff0cc061SDimitry Andric         continue;
1266ff0cc061SDimitry Andric       unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1267ff0cc061SDimitry Andric       bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1268ff0cc061SDimitry Andric       bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1269ff0cc061SDimitry Andric       if (!VecBitWidthsEqual)
1270ff0cc061SDimitry Andric         continue;
1271ff0cc061SDimitry Andric       if (!VectorType::isValidElementType(TgtTy))
1272ff0cc061SDimitry Andric         continue;
1273ff0cc061SDimitry Andric       VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1274ff0cc061SDimitry Andric       if (!BegIsAligned) {
1275ff0cc061SDimitry Andric         // Shuffle the input so [0,NumElements) contains the output, and
1276ff0cc061SDimitry Andric         // [NumElems,SrcNumElems) is undef.
1277ff0cc061SDimitry Andric         SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1278ff0cc061SDimitry Andric                                                 UndefValue::get(Int32Ty));
1279ff0cc061SDimitry Andric         for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1280ff0cc061SDimitry Andric           ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
1281c4394386SDimitry Andric         V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
1282ff0cc061SDimitry Andric                                         ConstantVector::get(ShuffleMask),
1283ff0cc061SDimitry Andric                                         SVI.getName() + ".extract");
1284ff0cc061SDimitry Andric         BegIdx = 0;
1285ff0cc061SDimitry Andric       }
1286ff0cc061SDimitry Andric       unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1287ff0cc061SDimitry Andric       assert(SrcElemsPerTgtElem);
1288ff0cc061SDimitry Andric       BegIdx /= SrcElemsPerTgtElem;
1289ff0cc061SDimitry Andric       bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1290ff0cc061SDimitry Andric       auto *NewBC =
1291ff0cc061SDimitry Andric           BCAlreadyExists
1292ff0cc061SDimitry Andric               ? NewBCs[CastSrcTy]
1293c4394386SDimitry Andric               : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
1294ff0cc061SDimitry Andric       if (!BCAlreadyExists)
1295ff0cc061SDimitry Andric         NewBCs[CastSrcTy] = NewBC;
1296c4394386SDimitry Andric       auto *Ext = Builder.CreateExtractElement(
1297ff0cc061SDimitry Andric           NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1298ff0cc061SDimitry Andric       // The shufflevector isn't being replaced: the bitcast that used it
1299ff0cc061SDimitry Andric       // is. InstCombine will visit the newly-created instructions.
13003ca95b02SDimitry Andric       replaceInstUsesWith(*BC, Ext);
1301ff0cc061SDimitry Andric       MadeChange = true;
1302ff0cc061SDimitry Andric     }
1303ff0cc061SDimitry Andric   }
1304ff0cc061SDimitry Andric 
1305f22ef01cSRoman Divacky   // If the LHS is a shufflevector itself, see if we can combine it with this
1306dff0c46cSDimitry Andric   // one without producing an unusual shuffle.
1307dff0c46cSDimitry Andric   // Cases that might be simplified:
1308dff0c46cSDimitry Andric   // 1.
1309dff0c46cSDimitry Andric   // x1=shuffle(v1,v2,mask1)
1310dff0c46cSDimitry Andric   //  x=shuffle(x1,undef,mask)
1311dff0c46cSDimitry Andric   //        ==>
1312dff0c46cSDimitry Andric   //  x=shuffle(v1,undef,newMask)
1313dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1314dff0c46cSDimitry Andric   // 2.
1315dff0c46cSDimitry Andric   // x1=shuffle(v1,undef,mask1)
1316dff0c46cSDimitry Andric   //  x=shuffle(x1,x2,mask)
1317dff0c46cSDimitry Andric   // where v1.size() == mask1.size()
1318dff0c46cSDimitry Andric   //        ==>
1319dff0c46cSDimitry Andric   //  x=shuffle(v1,x2,newMask)
1320dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1321dff0c46cSDimitry Andric   // 3.
1322dff0c46cSDimitry Andric   // x2=shuffle(v2,undef,mask2)
1323dff0c46cSDimitry Andric   //  x=shuffle(x1,x2,mask)
1324dff0c46cSDimitry Andric   // where v2.size() == mask2.size()
1325dff0c46cSDimitry Andric   //        ==>
1326dff0c46cSDimitry Andric   //  x=shuffle(x1,v2,newMask)
1327dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size())
1328dff0c46cSDimitry Andric   //              ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1329dff0c46cSDimitry Andric   // 4.
1330dff0c46cSDimitry Andric   // x1=shuffle(v1,undef,mask1)
1331dff0c46cSDimitry Andric   // x2=shuffle(v2,undef,mask2)
1332dff0c46cSDimitry Andric   //  x=shuffle(x1,x2,mask)
1333dff0c46cSDimitry Andric   // where v1.size() == v2.size()
1334dff0c46cSDimitry Andric   //        ==>
1335dff0c46cSDimitry Andric   //  x=shuffle(v1,v2,newMask)
1336dff0c46cSDimitry Andric   // newMask[i] = (mask[i] < x1.size())
1337dff0c46cSDimitry Andric   //              ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1338dff0c46cSDimitry Andric   //
1339dff0c46cSDimitry Andric   // Here we are really conservative:
1340f22ef01cSRoman Divacky   // we are absolutely afraid of producing a shuffle mask not in the input
1341f22ef01cSRoman Divacky   // program, because the code gen may not be smart enough to turn a merged
1342f22ef01cSRoman Divacky   // shuffle into two specific shuffles: it may produce worse code.  As such,
13432754fe60SDimitry Andric   // we only merge two shuffles if the result is either a splat or one of the
1344dff0c46cSDimitry Andric   // input shuffle masks.  In this case, merging the shuffles just removes
13452754fe60SDimitry Andric   // one instruction, which we know is safe.  This is good for things like
1346dff0c46cSDimitry Andric   // turning: (splat(splat)) -> splat, or
1347dff0c46cSDimitry Andric   // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1348dff0c46cSDimitry Andric   ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1349dff0c46cSDimitry Andric   ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1350dff0c46cSDimitry Andric   if (LHSShuffle)
1351dff0c46cSDimitry Andric     if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
135291bc56edSDimitry Andric       LHSShuffle = nullptr;
1353dff0c46cSDimitry Andric   if (RHSShuffle)
1354dff0c46cSDimitry Andric     if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
135591bc56edSDimitry Andric       RHSShuffle = nullptr;
1356dff0c46cSDimitry Andric   if (!LHSShuffle && !RHSShuffle)
135791bc56edSDimitry Andric     return MadeChange ? &SVI : nullptr;
1358dff0c46cSDimitry Andric 
135991bc56edSDimitry Andric   Value* LHSOp0 = nullptr;
136091bc56edSDimitry Andric   Value* LHSOp1 = nullptr;
136191bc56edSDimitry Andric   Value* RHSOp0 = nullptr;
1362dff0c46cSDimitry Andric   unsigned LHSOp0Width = 0;
1363dff0c46cSDimitry Andric   unsigned RHSOp0Width = 0;
1364dff0c46cSDimitry Andric   if (LHSShuffle) {
1365dff0c46cSDimitry Andric     LHSOp0 = LHSShuffle->getOperand(0);
1366dff0c46cSDimitry Andric     LHSOp1 = LHSShuffle->getOperand(1);
1367d88c1a5aSDimitry Andric     LHSOp0Width = LHSOp0->getType()->getVectorNumElements();
1368dff0c46cSDimitry Andric   }
1369dff0c46cSDimitry Andric   if (RHSShuffle) {
1370dff0c46cSDimitry Andric     RHSOp0 = RHSShuffle->getOperand(0);
1371d88c1a5aSDimitry Andric     RHSOp0Width = RHSOp0->getType()->getVectorNumElements();
1372dff0c46cSDimitry Andric   }
1373dff0c46cSDimitry Andric   Value* newLHS = LHS;
1374dff0c46cSDimitry Andric   Value* newRHS = RHS;
1375dff0c46cSDimitry Andric   if (LHSShuffle) {
1376dff0c46cSDimitry Andric     // case 1
1377f22ef01cSRoman Divacky     if (isa<UndefValue>(RHS)) {
1378dff0c46cSDimitry Andric       newLHS = LHSOp0;
1379dff0c46cSDimitry Andric       newRHS = LHSOp1;
1380dff0c46cSDimitry Andric     }
1381dff0c46cSDimitry Andric     // case 2 or 4
1382dff0c46cSDimitry Andric     else if (LHSOp0Width == LHSWidth) {
1383dff0c46cSDimitry Andric       newLHS = LHSOp0;
1384dff0c46cSDimitry Andric     }
1385dff0c46cSDimitry Andric   }
1386dff0c46cSDimitry Andric   // case 3 or 4
1387dff0c46cSDimitry Andric   if (RHSShuffle && RHSOp0Width == LHSWidth) {
1388dff0c46cSDimitry Andric     newRHS = RHSOp0;
1389dff0c46cSDimitry Andric   }
1390dff0c46cSDimitry Andric   // case 4
1391dff0c46cSDimitry Andric   if (LHSOp0 == RHSOp0) {
1392dff0c46cSDimitry Andric     newLHS = LHSOp0;
139391bc56edSDimitry Andric     newRHS = nullptr;
1394dff0c46cSDimitry Andric   }
1395f22ef01cSRoman Divacky 
1396dff0c46cSDimitry Andric   if (newLHS == LHS && newRHS == RHS)
139791bc56edSDimitry Andric     return MadeChange ? &SVI : nullptr;
1398dff0c46cSDimitry Andric 
1399dff0c46cSDimitry Andric   SmallVector<int, 16> LHSMask;
1400dff0c46cSDimitry Andric   SmallVector<int, 16> RHSMask;
1401dff0c46cSDimitry Andric   if (newLHS != LHS)
1402dff0c46cSDimitry Andric     LHSMask = LHSShuffle->getShuffleMask();
1403dff0c46cSDimitry Andric   if (RHSShuffle && newRHS != RHS)
1404dff0c46cSDimitry Andric     RHSMask = RHSShuffle->getShuffleMask();
1405dff0c46cSDimitry Andric 
1406dff0c46cSDimitry Andric   unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1407dff0c46cSDimitry Andric   SmallVector<int, 16> newMask;
14082754fe60SDimitry Andric   bool isSplat = true;
1409dff0c46cSDimitry Andric   int SplatElt = -1;
1410dff0c46cSDimitry Andric   // Create a new mask for the new ShuffleVectorInst so that the new
1411dff0c46cSDimitry Andric   // ShuffleVectorInst is equivalent to the original one.
1412dff0c46cSDimitry Andric   for (unsigned i = 0; i < VWidth; ++i) {
1413dff0c46cSDimitry Andric     int eltMask;
1414139f7f9bSDimitry Andric     if (Mask[i] < 0) {
1415dff0c46cSDimitry Andric       // This element is an undef value.
1416dff0c46cSDimitry Andric       eltMask = -1;
1417dff0c46cSDimitry Andric     } else if (Mask[i] < (int)LHSWidth) {
1418dff0c46cSDimitry Andric       // This element is from left hand side vector operand.
1419dff0c46cSDimitry Andric       //
1420dff0c46cSDimitry Andric       // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1421dff0c46cSDimitry Andric       // new mask value for the element.
1422dff0c46cSDimitry Andric       if (newLHS != LHS) {
1423dff0c46cSDimitry Andric         eltMask = LHSMask[Mask[i]];
1424dff0c46cSDimitry Andric         // If the value selected is an undef value, explicitly specify it
1425dff0c46cSDimitry Andric         // with a -1 mask value.
1426dff0c46cSDimitry Andric         if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1427dff0c46cSDimitry Andric           eltMask = -1;
1428139f7f9bSDimitry Andric       } else
1429dff0c46cSDimitry Andric         eltMask = Mask[i];
1430dff0c46cSDimitry Andric     } else {
1431dff0c46cSDimitry Andric       // This element is from right hand side vector operand
1432dff0c46cSDimitry Andric       //
1433dff0c46cSDimitry Andric       // If the value selected is an undef value, explicitly specify it
1434dff0c46cSDimitry Andric       // with a -1 mask value. (case 1)
1435dff0c46cSDimitry Andric       if (isa<UndefValue>(RHS))
1436dff0c46cSDimitry Andric         eltMask = -1;
1437dff0c46cSDimitry Andric       // If RHS is going to be replaced (case 3 or 4), calculate the
1438dff0c46cSDimitry Andric       // new mask value for the element.
1439dff0c46cSDimitry Andric       else if (newRHS != RHS) {
1440dff0c46cSDimitry Andric         eltMask = RHSMask[Mask[i]-LHSWidth];
1441dff0c46cSDimitry Andric         // If the value selected is an undef value, explicitly specify it
1442dff0c46cSDimitry Andric         // with a -1 mask value.
1443dff0c46cSDimitry Andric         if (eltMask >= (int)RHSOp0Width) {
1444dff0c46cSDimitry Andric           assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1445dff0c46cSDimitry Andric                  && "should have been check above");
1446dff0c46cSDimitry Andric           eltMask = -1;
1447dff0c46cSDimitry Andric         }
1448139f7f9bSDimitry Andric       } else
1449dff0c46cSDimitry Andric         eltMask = Mask[i]-LHSWidth;
1450dff0c46cSDimitry Andric 
1451dff0c46cSDimitry Andric       // If LHS's width is changed, shift the mask value accordingly.
14522cab237bSDimitry Andric       // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any
14533861d79fSDimitry Andric       // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
14543861d79fSDimitry Andric       // If newRHS == newLHS, we want to remap any references from newRHS to
14553861d79fSDimitry Andric       // newLHS so that we can properly identify splats that may occur due to
145691bc56edSDimitry Andric       // obfuscation across the two vectors.
145791bc56edSDimitry Andric       if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
1458dff0c46cSDimitry Andric         eltMask += newLHSWidth;
14592754fe60SDimitry Andric     }
1460f22ef01cSRoman Divacky 
1461dff0c46cSDimitry Andric     // Check if this could still be a splat.
1462dff0c46cSDimitry Andric     if (eltMask >= 0) {
1463dff0c46cSDimitry Andric       if (SplatElt >= 0 && SplatElt != eltMask)
1464dff0c46cSDimitry Andric         isSplat = false;
1465dff0c46cSDimitry Andric       SplatElt = eltMask;
1466dff0c46cSDimitry Andric     }
1467dff0c46cSDimitry Andric 
1468dff0c46cSDimitry Andric     newMask.push_back(eltMask);
1469dff0c46cSDimitry Andric   }
1470dff0c46cSDimitry Andric 
1471dff0c46cSDimitry Andric   // If the result mask is equal to one of the original shuffle masks,
1472dff0c46cSDimitry Andric   // or is a splat, do the replacement.
1473dff0c46cSDimitry Andric   if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
1474dff0c46cSDimitry Andric     SmallVector<Constant*, 16> Elts;
1475dff0c46cSDimitry Andric     for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1476dff0c46cSDimitry Andric       if (newMask[i] < 0) {
14772754fe60SDimitry Andric         Elts.push_back(UndefValue::get(Int32Ty));
1478f22ef01cSRoman Divacky       } else {
1479dff0c46cSDimitry Andric         Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1480f22ef01cSRoman Divacky       }
1481f22ef01cSRoman Divacky     }
148291bc56edSDimitry Andric     if (!newRHS)
1483dff0c46cSDimitry Andric       newRHS = UndefValue::get(newLHS->getType());
1484dff0c46cSDimitry Andric     return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
1485f22ef01cSRoman Divacky   }
1486f22ef01cSRoman Divacky 
148791bc56edSDimitry Andric   // If the result mask is an identity, replace uses of this instruction with
148891bc56edSDimitry Andric   // corresponding argument.
148991bc56edSDimitry Andric   bool isLHSID, isRHSID;
14907d523365SDimitry Andric   recognizeIdentityMask(newMask, isLHSID, isRHSID);
14913ca95b02SDimitry Andric   if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS);
14923ca95b02SDimitry Andric   if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS);
149391bc56edSDimitry Andric 
149491bc56edSDimitry Andric   return MadeChange ? &SVI : nullptr;
1495f22ef01cSRoman Divacky }
1496