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 
15f22ef01cSRoman Divacky #include "InstCombine.h"
16f22ef01cSRoman Divacky using namespace llvm;
17f22ef01cSRoman Divacky 
18f22ef01cSRoman Divacky /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
19f22ef01cSRoman Divacky /// is to leave as a vector operation.
20f22ef01cSRoman Divacky static bool CheapToScalarize(Value *V, bool isConstant) {
21f22ef01cSRoman Divacky   if (isa<ConstantAggregateZero>(V))
22f22ef01cSRoman Divacky     return true;
23f22ef01cSRoman Divacky   if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
24f22ef01cSRoman Divacky     if (isConstant) return true;
25f22ef01cSRoman Divacky     // If all elts are the same, we can extract.
26f22ef01cSRoman Divacky     Constant *Op0 = C->getOperand(0);
27f22ef01cSRoman Divacky     for (unsigned i = 1; i < C->getNumOperands(); ++i)
28f22ef01cSRoman Divacky       if (C->getOperand(i) != Op0)
29f22ef01cSRoman Divacky         return false;
30f22ef01cSRoman Divacky     return true;
31f22ef01cSRoman Divacky   }
32f22ef01cSRoman Divacky   Instruction *I = dyn_cast<Instruction>(V);
33f22ef01cSRoman Divacky   if (!I) return false;
34f22ef01cSRoman Divacky 
35f22ef01cSRoman Divacky   // Insert element gets simplified to the inserted element or is deleted if
36f22ef01cSRoman Divacky   // this is constant idx extract element and its a constant idx insertelt.
37f22ef01cSRoman Divacky   if (I->getOpcode() == Instruction::InsertElement && isConstant &&
38f22ef01cSRoman Divacky       isa<ConstantInt>(I->getOperand(2)))
39f22ef01cSRoman Divacky     return true;
40f22ef01cSRoman Divacky   if (I->getOpcode() == Instruction::Load && I->hasOneUse())
41f22ef01cSRoman Divacky     return true;
42f22ef01cSRoman Divacky   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
43f22ef01cSRoman Divacky     if (BO->hasOneUse() &&
44f22ef01cSRoman Divacky         (CheapToScalarize(BO->getOperand(0), isConstant) ||
45f22ef01cSRoman Divacky          CheapToScalarize(BO->getOperand(1), isConstant)))
46f22ef01cSRoman Divacky       return true;
47f22ef01cSRoman Divacky   if (CmpInst *CI = dyn_cast<CmpInst>(I))
48f22ef01cSRoman Divacky     if (CI->hasOneUse() &&
49f22ef01cSRoman Divacky         (CheapToScalarize(CI->getOperand(0), isConstant) ||
50f22ef01cSRoman Divacky          CheapToScalarize(CI->getOperand(1), isConstant)))
51f22ef01cSRoman Divacky       return true;
52f22ef01cSRoman Divacky 
53f22ef01cSRoman Divacky   return false;
54f22ef01cSRoman Divacky }
55f22ef01cSRoman Divacky 
562754fe60SDimitry Andric /// getShuffleMask - Read and decode a shufflevector mask.
572754fe60SDimitry Andric /// Turn undef elements into negative values.
582754fe60SDimitry Andric static std::vector<int> getShuffleMask(const ShuffleVectorInst *SVI) {
59f22ef01cSRoman Divacky   unsigned NElts = SVI->getType()->getNumElements();
60f22ef01cSRoman Divacky   if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
612754fe60SDimitry Andric     return std::vector<int>(NElts, 0);
62f22ef01cSRoman Divacky   if (isa<UndefValue>(SVI->getOperand(2)))
632754fe60SDimitry Andric     return std::vector<int>(NElts, -1);
64f22ef01cSRoman Divacky 
652754fe60SDimitry Andric   std::vector<int> Result;
66f22ef01cSRoman Divacky   const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
67f22ef01cSRoman Divacky   for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
68f22ef01cSRoman Divacky     if (isa<UndefValue>(*i))
692754fe60SDimitry Andric       Result.push_back(-1);  // undef
70f22ef01cSRoman Divacky     else
71f22ef01cSRoman Divacky       Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
72f22ef01cSRoman Divacky   return Result;
73f22ef01cSRoman Divacky }
74f22ef01cSRoman Divacky 
75f22ef01cSRoman Divacky /// FindScalarElement - Given a vector and an element number, see if the scalar
76f22ef01cSRoman Divacky /// value is already around as a register, for example if it were inserted then
77f22ef01cSRoman Divacky /// extracted from the vector.
78f22ef01cSRoman Divacky static Value *FindScalarElement(Value *V, unsigned EltNo) {
79f22ef01cSRoman Divacky   assert(V->getType()->isVectorTy() && "Not looking at a vector?");
80f22ef01cSRoman Divacky   const VectorType *PTy = cast<VectorType>(V->getType());
81f22ef01cSRoman Divacky   unsigned Width = PTy->getNumElements();
82f22ef01cSRoman Divacky   if (EltNo >= Width)  // Out of range access.
83f22ef01cSRoman Divacky     return UndefValue::get(PTy->getElementType());
84f22ef01cSRoman Divacky 
85f22ef01cSRoman Divacky   if (isa<UndefValue>(V))
86f22ef01cSRoman Divacky     return UndefValue::get(PTy->getElementType());
87f22ef01cSRoman Divacky   if (isa<ConstantAggregateZero>(V))
88f22ef01cSRoman Divacky     return Constant::getNullValue(PTy->getElementType());
89f22ef01cSRoman Divacky   if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
90f22ef01cSRoman Divacky     return CP->getOperand(EltNo);
91f22ef01cSRoman Divacky 
92f22ef01cSRoman Divacky   if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
93f22ef01cSRoman Divacky     // If this is an insert to a variable element, we don't know what it is.
94f22ef01cSRoman Divacky     if (!isa<ConstantInt>(III->getOperand(2)))
95f22ef01cSRoman Divacky       return 0;
96f22ef01cSRoman Divacky     unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
97f22ef01cSRoman Divacky 
98f22ef01cSRoman Divacky     // If this is an insert to the element we are looking for, return the
99f22ef01cSRoman Divacky     // inserted value.
100f22ef01cSRoman Divacky     if (EltNo == IIElt)
101f22ef01cSRoman Divacky       return III->getOperand(1);
102f22ef01cSRoman Divacky 
103f22ef01cSRoman Divacky     // Otherwise, the insertelement doesn't modify the value, recurse on its
104f22ef01cSRoman Divacky     // vector input.
105f22ef01cSRoman Divacky     return FindScalarElement(III->getOperand(0), EltNo);
106f22ef01cSRoman Divacky   }
107f22ef01cSRoman Divacky 
108f22ef01cSRoman Divacky   if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
109f22ef01cSRoman Divacky     unsigned LHSWidth =
110f22ef01cSRoman Divacky       cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
1112754fe60SDimitry Andric     int InEl = getShuffleMask(SVI)[EltNo];
1122754fe60SDimitry Andric     if (InEl < 0)
113f22ef01cSRoman Divacky       return UndefValue::get(PTy->getElementType());
1142754fe60SDimitry Andric     if (InEl < (int)LHSWidth)
1152754fe60SDimitry Andric       return FindScalarElement(SVI->getOperand(0), InEl);
1162754fe60SDimitry Andric     return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
117f22ef01cSRoman Divacky   }
118f22ef01cSRoman Divacky 
119f22ef01cSRoman Divacky   // Otherwise, we don't know.
120f22ef01cSRoman Divacky   return 0;
121f22ef01cSRoman Divacky }
122f22ef01cSRoman Divacky 
123f22ef01cSRoman Divacky Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
124f22ef01cSRoman Divacky   // If vector val is undef, replace extract with scalar undef.
125f22ef01cSRoman Divacky   if (isa<UndefValue>(EI.getOperand(0)))
126f22ef01cSRoman Divacky     return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
127f22ef01cSRoman Divacky 
128f22ef01cSRoman Divacky   // If vector val is constant 0, replace extract with scalar 0.
129f22ef01cSRoman Divacky   if (isa<ConstantAggregateZero>(EI.getOperand(0)))
130f22ef01cSRoman Divacky     return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
131f22ef01cSRoman Divacky 
132f22ef01cSRoman Divacky   if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
133f22ef01cSRoman Divacky     // If vector val is constant with all elements the same, replace EI with
134f22ef01cSRoman Divacky     // that element. When the elements are not identical, we cannot replace yet
135f22ef01cSRoman Divacky     // (we do that below, but only when the index is constant).
136f22ef01cSRoman Divacky     Constant *op0 = C->getOperand(0);
137f22ef01cSRoman Divacky     for (unsigned i = 1; i != C->getNumOperands(); ++i)
138f22ef01cSRoman Divacky       if (C->getOperand(i) != op0) {
139f22ef01cSRoman Divacky         op0 = 0;
140f22ef01cSRoman Divacky         break;
141f22ef01cSRoman Divacky       }
142f22ef01cSRoman Divacky     if (op0)
143f22ef01cSRoman Divacky       return ReplaceInstUsesWith(EI, op0);
144f22ef01cSRoman Divacky   }
145f22ef01cSRoman Divacky 
146f22ef01cSRoman Divacky   // If extracting a specified index from the vector, see if we can recursively
147f22ef01cSRoman Divacky   // find a previously computed scalar that was inserted into the vector.
148f22ef01cSRoman Divacky   if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
149f22ef01cSRoman Divacky     unsigned IndexVal = IdxC->getZExtValue();
150f22ef01cSRoman Divacky     unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
151f22ef01cSRoman Divacky 
152f22ef01cSRoman Divacky     // If this is extracting an invalid index, turn this into undef, to avoid
153f22ef01cSRoman Divacky     // crashing the code below.
154f22ef01cSRoman Divacky     if (IndexVal >= VectorWidth)
155f22ef01cSRoman Divacky       return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
156f22ef01cSRoman Divacky 
157f22ef01cSRoman Divacky     // This instruction only demands the single element from the input vector.
158f22ef01cSRoman Divacky     // If the input vector has a single use, simplify it based on this use
159f22ef01cSRoman Divacky     // property.
160f22ef01cSRoman Divacky     if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
161f22ef01cSRoman Divacky       APInt UndefElts(VectorWidth, 0);
162f22ef01cSRoman Divacky       APInt DemandedMask(VectorWidth, 0);
1632754fe60SDimitry Andric       DemandedMask.setBit(IndexVal);
164f22ef01cSRoman Divacky       if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
165f22ef01cSRoman Divacky                                                 DemandedMask, UndefElts)) {
166f22ef01cSRoman Divacky         EI.setOperand(0, V);
167f22ef01cSRoman Divacky         return &EI;
168f22ef01cSRoman Divacky       }
169f22ef01cSRoman Divacky     }
170f22ef01cSRoman Divacky 
171f22ef01cSRoman Divacky     if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
172f22ef01cSRoman Divacky       return ReplaceInstUsesWith(EI, Elt);
173f22ef01cSRoman Divacky 
174f22ef01cSRoman Divacky     // If the this extractelement is directly using a bitcast from a vector of
175f22ef01cSRoman Divacky     // the same number of elements, see if we can find the source element from
176f22ef01cSRoman Divacky     // it.  In this case, we will end up needing to bitcast the scalars.
177f22ef01cSRoman Divacky     if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
178f22ef01cSRoman Divacky       if (const VectorType *VT =
179f22ef01cSRoman Divacky           dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
180f22ef01cSRoman Divacky         if (VT->getNumElements() == VectorWidth)
181f22ef01cSRoman Divacky           if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
182f22ef01cSRoman Divacky             return new BitCastInst(Elt, EI.getType());
183f22ef01cSRoman Divacky     }
184f22ef01cSRoman Divacky   }
185f22ef01cSRoman Divacky 
186f22ef01cSRoman Divacky   if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
187f22ef01cSRoman Divacky     // Push extractelement into predecessor operation if legal and
188f22ef01cSRoman Divacky     // profitable to do so
189f22ef01cSRoman Divacky     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
190f22ef01cSRoman Divacky       if (I->hasOneUse() &&
191f22ef01cSRoman Divacky           CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
192f22ef01cSRoman Divacky         Value *newEI0 =
193f22ef01cSRoman Divacky           Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
194f22ef01cSRoman Divacky                                         EI.getName()+".lhs");
195f22ef01cSRoman Divacky         Value *newEI1 =
196f22ef01cSRoman Divacky           Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
197f22ef01cSRoman Divacky                                         EI.getName()+".rhs");
198f22ef01cSRoman Divacky         return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
199f22ef01cSRoman Divacky       }
200f22ef01cSRoman Divacky     } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
201f22ef01cSRoman Divacky       // Extracting the inserted element?
202f22ef01cSRoman Divacky       if (IE->getOperand(2) == EI.getOperand(1))
203f22ef01cSRoman Divacky         return ReplaceInstUsesWith(EI, IE->getOperand(1));
204f22ef01cSRoman Divacky       // If the inserted and extracted elements are constants, they must not
205f22ef01cSRoman Divacky       // be the same value, extract from the pre-inserted value instead.
206f22ef01cSRoman Divacky       if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
207f22ef01cSRoman Divacky         Worklist.AddValue(EI.getOperand(0));
208f22ef01cSRoman Divacky         EI.setOperand(0, IE->getOperand(0));
209f22ef01cSRoman Divacky         return &EI;
210f22ef01cSRoman Divacky       }
211f22ef01cSRoman Divacky     } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
212f22ef01cSRoman Divacky       // If this is extracting an element from a shufflevector, figure out where
213f22ef01cSRoman Divacky       // it came from and extract from the appropriate input element instead.
214f22ef01cSRoman Divacky       if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
2152754fe60SDimitry Andric         int SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
216f22ef01cSRoman Divacky         Value *Src;
217f22ef01cSRoman Divacky         unsigned LHSWidth =
218f22ef01cSRoman Divacky           cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
219f22ef01cSRoman Divacky 
2202754fe60SDimitry Andric         if (SrcIdx < 0)
2212754fe60SDimitry Andric           return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
2222754fe60SDimitry Andric         if (SrcIdx < (int)LHSWidth)
223f22ef01cSRoman Divacky           Src = SVI->getOperand(0);
2242754fe60SDimitry Andric         else {
225f22ef01cSRoman Divacky           SrcIdx -= LHSWidth;
226f22ef01cSRoman Divacky           Src = SVI->getOperand(1);
227f22ef01cSRoman Divacky         }
2282754fe60SDimitry Andric         const Type *Int32Ty = Type::getInt32Ty(EI.getContext());
229f22ef01cSRoman Divacky         return ExtractElementInst::Create(Src,
2302754fe60SDimitry Andric                                           ConstantInt::get(Int32Ty,
231f22ef01cSRoman Divacky                                                            SrcIdx, false));
232f22ef01cSRoman Divacky       }
2333b0f4066SDimitry Andric     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2343b0f4066SDimitry Andric       // Canonicalize extractelement(cast) -> cast(extractelement)
2353b0f4066SDimitry Andric       // bitcasts can change the number of vector elements and they cost nothing
2363b0f4066SDimitry Andric       if (CI->hasOneUse() && EI.hasOneUse() &&
2373b0f4066SDimitry Andric           (CI->getOpcode() != Instruction::BitCast)) {
2383b0f4066SDimitry Andric         Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
2393b0f4066SDimitry Andric                                                   EI.getIndexOperand());
2403b0f4066SDimitry Andric         return CastInst::Create(CI->getOpcode(), EE, EI.getType());
241f22ef01cSRoman Divacky       }
2423b0f4066SDimitry Andric     }
243f22ef01cSRoman Divacky   }
244f22ef01cSRoman Divacky   return 0;
245f22ef01cSRoman Divacky }
246f22ef01cSRoman Divacky 
247f22ef01cSRoman Divacky /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
248f22ef01cSRoman Divacky /// elements from either LHS or RHS, return the shuffle mask and true.
249f22ef01cSRoman Divacky /// Otherwise, return false.
250f22ef01cSRoman Divacky static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
251f22ef01cSRoman Divacky                                          std::vector<Constant*> &Mask) {
252f22ef01cSRoman Divacky   assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
253f22ef01cSRoman Divacky          "Invalid CollectSingleShuffleElements");
254f22ef01cSRoman Divacky   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
255f22ef01cSRoman Divacky 
256f22ef01cSRoman Divacky   if (isa<UndefValue>(V)) {
257f22ef01cSRoman Divacky     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
258f22ef01cSRoman Divacky     return true;
259f22ef01cSRoman Divacky   }
260f22ef01cSRoman Divacky 
261f22ef01cSRoman Divacky   if (V == LHS) {
262f22ef01cSRoman Divacky     for (unsigned i = 0; i != NumElts; ++i)
263f22ef01cSRoman Divacky       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
264f22ef01cSRoman Divacky     return true;
265f22ef01cSRoman Divacky   }
266f22ef01cSRoman Divacky 
267f22ef01cSRoman Divacky   if (V == RHS) {
268f22ef01cSRoman Divacky     for (unsigned i = 0; i != NumElts; ++i)
269f22ef01cSRoman Divacky       Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
270f22ef01cSRoman Divacky                                       i+NumElts));
271f22ef01cSRoman Divacky     return true;
272f22ef01cSRoman Divacky   }
273f22ef01cSRoman Divacky 
274f22ef01cSRoman Divacky   if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
275f22ef01cSRoman Divacky     // If this is an insert of an extract from some other vector, include it.
276f22ef01cSRoman Divacky     Value *VecOp    = IEI->getOperand(0);
277f22ef01cSRoman Divacky     Value *ScalarOp = IEI->getOperand(1);
278f22ef01cSRoman Divacky     Value *IdxOp    = IEI->getOperand(2);
279f22ef01cSRoman Divacky 
280f22ef01cSRoman Divacky     if (!isa<ConstantInt>(IdxOp))
281f22ef01cSRoman Divacky       return false;
282f22ef01cSRoman Divacky     unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
283f22ef01cSRoman Divacky 
284f22ef01cSRoman Divacky     if (isa<UndefValue>(ScalarOp)) {  // inserting undef into vector.
285f22ef01cSRoman Divacky       // Okay, we can handle this if the vector we are insertinting into is
286f22ef01cSRoman Divacky       // transitively ok.
287f22ef01cSRoman Divacky       if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
288f22ef01cSRoman Divacky         // If so, update the mask to reflect the inserted undef.
289f22ef01cSRoman Divacky         Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
290f22ef01cSRoman Divacky         return true;
291f22ef01cSRoman Divacky       }
292f22ef01cSRoman Divacky     } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
293f22ef01cSRoman Divacky       if (isa<ConstantInt>(EI->getOperand(1)) &&
294f22ef01cSRoman Divacky           EI->getOperand(0)->getType() == V->getType()) {
295f22ef01cSRoman Divacky         unsigned ExtractedIdx =
296f22ef01cSRoman Divacky         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
297f22ef01cSRoman Divacky 
298f22ef01cSRoman Divacky         // This must be extracting from either LHS or RHS.
299f22ef01cSRoman Divacky         if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
300f22ef01cSRoman Divacky           // Okay, we can handle this if the vector we are insertinting into is
301f22ef01cSRoman Divacky           // transitively ok.
302f22ef01cSRoman Divacky           if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
303f22ef01cSRoman Divacky             // If so, update the mask to reflect the inserted value.
304f22ef01cSRoman Divacky             if (EI->getOperand(0) == LHS) {
305f22ef01cSRoman Divacky               Mask[InsertedIdx % NumElts] =
306f22ef01cSRoman Divacky               ConstantInt::get(Type::getInt32Ty(V->getContext()),
307f22ef01cSRoman Divacky                                ExtractedIdx);
308f22ef01cSRoman Divacky             } else {
309f22ef01cSRoman Divacky               assert(EI->getOperand(0) == RHS);
310f22ef01cSRoman Divacky               Mask[InsertedIdx % NumElts] =
311f22ef01cSRoman Divacky               ConstantInt::get(Type::getInt32Ty(V->getContext()),
312f22ef01cSRoman Divacky                                ExtractedIdx+NumElts);
313f22ef01cSRoman Divacky             }
314f22ef01cSRoman Divacky             return true;
315f22ef01cSRoman Divacky           }
316f22ef01cSRoman Divacky         }
317f22ef01cSRoman Divacky       }
318f22ef01cSRoman Divacky     }
319f22ef01cSRoman Divacky   }
320f22ef01cSRoman Divacky   // TODO: Handle shufflevector here!
321f22ef01cSRoman Divacky 
322f22ef01cSRoman Divacky   return false;
323f22ef01cSRoman Divacky }
324f22ef01cSRoman Divacky 
325f22ef01cSRoman Divacky /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
326f22ef01cSRoman Divacky /// RHS of the shuffle instruction, if it is not null.  Return a shuffle mask
327f22ef01cSRoman Divacky /// that computes V and the LHS value of the shuffle.
328f22ef01cSRoman Divacky static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
329f22ef01cSRoman Divacky                                      Value *&RHS) {
330f22ef01cSRoman Divacky   assert(V->getType()->isVectorTy() &&
331f22ef01cSRoman Divacky          (RHS == 0 || V->getType() == RHS->getType()) &&
332f22ef01cSRoman Divacky          "Invalid shuffle!");
333f22ef01cSRoman Divacky   unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
334f22ef01cSRoman Divacky 
335f22ef01cSRoman Divacky   if (isa<UndefValue>(V)) {
336f22ef01cSRoman Divacky     Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
337f22ef01cSRoman Divacky     return V;
338f22ef01cSRoman Divacky   } else if (isa<ConstantAggregateZero>(V)) {
339f22ef01cSRoman Divacky     Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
340f22ef01cSRoman Divacky     return V;
341f22ef01cSRoman Divacky   } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
342f22ef01cSRoman Divacky     // If this is an insert of an extract from some other vector, include it.
343f22ef01cSRoman Divacky     Value *VecOp    = IEI->getOperand(0);
344f22ef01cSRoman Divacky     Value *ScalarOp = IEI->getOperand(1);
345f22ef01cSRoman Divacky     Value *IdxOp    = IEI->getOperand(2);
346f22ef01cSRoman Divacky 
347f22ef01cSRoman Divacky     if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
348f22ef01cSRoman Divacky       if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
349f22ef01cSRoman Divacky           EI->getOperand(0)->getType() == V->getType()) {
350f22ef01cSRoman Divacky         unsigned ExtractedIdx =
351f22ef01cSRoman Divacky           cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
352f22ef01cSRoman Divacky         unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
353f22ef01cSRoman Divacky 
354f22ef01cSRoman Divacky         // Either the extracted from or inserted into vector must be RHSVec,
355f22ef01cSRoman Divacky         // otherwise we'd end up with a shuffle of three inputs.
356f22ef01cSRoman Divacky         if (EI->getOperand(0) == RHS || RHS == 0) {
357f22ef01cSRoman Divacky           RHS = EI->getOperand(0);
358f22ef01cSRoman Divacky           Value *V = CollectShuffleElements(VecOp, Mask, RHS);
359f22ef01cSRoman Divacky           Mask[InsertedIdx % NumElts] =
360f22ef01cSRoman Divacky             ConstantInt::get(Type::getInt32Ty(V->getContext()),
361f22ef01cSRoman Divacky                              NumElts+ExtractedIdx);
362f22ef01cSRoman Divacky           return V;
363f22ef01cSRoman Divacky         }
364f22ef01cSRoman Divacky 
365f22ef01cSRoman Divacky         if (VecOp == RHS) {
366f22ef01cSRoman Divacky           Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
367f22ef01cSRoman Divacky           // Everything but the extracted element is replaced with the RHS.
368f22ef01cSRoman Divacky           for (unsigned i = 0; i != NumElts; ++i) {
369f22ef01cSRoman Divacky             if (i != InsertedIdx)
370f22ef01cSRoman Divacky               Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()),
371f22ef01cSRoman Divacky                                          NumElts+i);
372f22ef01cSRoman Divacky           }
373f22ef01cSRoman Divacky           return V;
374f22ef01cSRoman Divacky         }
375f22ef01cSRoman Divacky 
376f22ef01cSRoman Divacky         // If this insertelement is a chain that comes from exactly these two
377f22ef01cSRoman Divacky         // vectors, return the vector and the effective shuffle.
378f22ef01cSRoman Divacky         if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
379f22ef01cSRoman Divacky           return EI->getOperand(0);
380f22ef01cSRoman Divacky       }
381f22ef01cSRoman Divacky     }
382f22ef01cSRoman Divacky   }
383f22ef01cSRoman Divacky   // TODO: Handle shufflevector here!
384f22ef01cSRoman Divacky 
385f22ef01cSRoman Divacky   // Otherwise, can't do anything fancy.  Return an identity vector.
386f22ef01cSRoman Divacky   for (unsigned i = 0; i != NumElts; ++i)
387f22ef01cSRoman Divacky     Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
388f22ef01cSRoman Divacky   return V;
389f22ef01cSRoman Divacky }
390f22ef01cSRoman Divacky 
391f22ef01cSRoman Divacky Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
392f22ef01cSRoman Divacky   Value *VecOp    = IE.getOperand(0);
393f22ef01cSRoman Divacky   Value *ScalarOp = IE.getOperand(1);
394f22ef01cSRoman Divacky   Value *IdxOp    = IE.getOperand(2);
395f22ef01cSRoman Divacky 
396f22ef01cSRoman Divacky   // Inserting an undef or into an undefined place, remove this.
397f22ef01cSRoman Divacky   if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
398f22ef01cSRoman Divacky     ReplaceInstUsesWith(IE, VecOp);
399f22ef01cSRoman Divacky 
400f22ef01cSRoman Divacky   // If the inserted element was extracted from some other vector, and if the
401f22ef01cSRoman Divacky   // indexes are constant, try to turn this into a shufflevector operation.
402f22ef01cSRoman Divacky   if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
403f22ef01cSRoman Divacky     if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
404f22ef01cSRoman Divacky         EI->getOperand(0)->getType() == IE.getType()) {
405f22ef01cSRoman Divacky       unsigned NumVectorElts = IE.getType()->getNumElements();
406f22ef01cSRoman Divacky       unsigned ExtractedIdx =
407f22ef01cSRoman Divacky         cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
408f22ef01cSRoman Divacky       unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
409f22ef01cSRoman Divacky 
410f22ef01cSRoman Divacky       if (ExtractedIdx >= NumVectorElts) // Out of range extract.
411f22ef01cSRoman Divacky         return ReplaceInstUsesWith(IE, VecOp);
412f22ef01cSRoman Divacky 
413f22ef01cSRoman Divacky       if (InsertedIdx >= NumVectorElts)  // Out of range insert.
414f22ef01cSRoman Divacky         return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
415f22ef01cSRoman Divacky 
416f22ef01cSRoman Divacky       // If we are extracting a value from a vector, then inserting it right
417f22ef01cSRoman Divacky       // back into the same place, just use the input vector.
418f22ef01cSRoman Divacky       if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
419f22ef01cSRoman Divacky         return ReplaceInstUsesWith(IE, VecOp);
420f22ef01cSRoman Divacky 
421f22ef01cSRoman Divacky       // If this insertelement isn't used by some other insertelement, turn it
422f22ef01cSRoman Divacky       // (and any insertelements it points to), into one big shuffle.
423f22ef01cSRoman Divacky       if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
424f22ef01cSRoman Divacky         std::vector<Constant*> Mask;
425f22ef01cSRoman Divacky         Value *RHS = 0;
426f22ef01cSRoman Divacky         Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
427f22ef01cSRoman Divacky         if (RHS == 0) RHS = UndefValue::get(LHS->getType());
428f22ef01cSRoman Divacky         // We now have a shuffle of LHS, RHS, Mask.
4292754fe60SDimitry Andric         return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
430f22ef01cSRoman Divacky       }
431f22ef01cSRoman Divacky     }
432f22ef01cSRoman Divacky   }
433f22ef01cSRoman Divacky 
434f22ef01cSRoman Divacky   unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
435f22ef01cSRoman Divacky   APInt UndefElts(VWidth, 0);
436f22ef01cSRoman Divacky   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
4372754fe60SDimitry Andric   if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
4382754fe60SDimitry Andric     if (V != &IE)
4392754fe60SDimitry Andric       return ReplaceInstUsesWith(IE, V);
440f22ef01cSRoman Divacky     return &IE;
4412754fe60SDimitry Andric   }
442f22ef01cSRoman Divacky 
443f22ef01cSRoman Divacky   return 0;
444f22ef01cSRoman Divacky }
445f22ef01cSRoman Divacky 
446f22ef01cSRoman Divacky 
447f22ef01cSRoman Divacky Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
448f22ef01cSRoman Divacky   Value *LHS = SVI.getOperand(0);
449f22ef01cSRoman Divacky   Value *RHS = SVI.getOperand(1);
4502754fe60SDimitry Andric   std::vector<int> Mask = getShuffleMask(&SVI);
451f22ef01cSRoman Divacky 
452f22ef01cSRoman Divacky   bool MadeChange = false;
453f22ef01cSRoman Divacky 
454f22ef01cSRoman Divacky   // Undefined shuffle mask -> undefined value.
455f22ef01cSRoman Divacky   if (isa<UndefValue>(SVI.getOperand(2)))
456f22ef01cSRoman Divacky     return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
457f22ef01cSRoman Divacky 
458f22ef01cSRoman Divacky   unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
459f22ef01cSRoman Divacky 
460f22ef01cSRoman Divacky   if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
461f22ef01cSRoman Divacky     return 0;
462f22ef01cSRoman Divacky 
463f22ef01cSRoman Divacky   APInt UndefElts(VWidth, 0);
464f22ef01cSRoman Divacky   APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
4652754fe60SDimitry Andric   if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
4662754fe60SDimitry Andric     if (V != &SVI)
4672754fe60SDimitry Andric       return ReplaceInstUsesWith(SVI, V);
468f22ef01cSRoman Divacky     LHS = SVI.getOperand(0);
469f22ef01cSRoman Divacky     RHS = SVI.getOperand(1);
470f22ef01cSRoman Divacky     MadeChange = true;
471f22ef01cSRoman Divacky   }
472f22ef01cSRoman Divacky 
473f22ef01cSRoman Divacky   // Canonicalize shuffle(x    ,x,mask) -> shuffle(x, undef,mask')
474f22ef01cSRoman Divacky   // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
475f22ef01cSRoman Divacky   if (LHS == RHS || isa<UndefValue>(LHS)) {
476f22ef01cSRoman Divacky     if (isa<UndefValue>(LHS) && LHS == RHS) {
477f22ef01cSRoman Divacky       // shuffle(undef,undef,mask) -> undef.
478f22ef01cSRoman Divacky       return ReplaceInstUsesWith(SVI, LHS);
479f22ef01cSRoman Divacky     }
480f22ef01cSRoman Divacky 
481f22ef01cSRoman Divacky     // Remap any references to RHS to use LHS.
482f22ef01cSRoman Divacky     std::vector<Constant*> Elts;
483f22ef01cSRoman Divacky     for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
4842754fe60SDimitry Andric       if (Mask[i] < 0)
485f22ef01cSRoman Divacky         Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
486f22ef01cSRoman Divacky       else {
4872754fe60SDimitry Andric         if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
4882754fe60SDimitry Andric             (Mask[i] <  (int)e && isa<UndefValue>(LHS))) {
4892754fe60SDimitry Andric           Mask[i] = -1;     // Turn into undef.
490f22ef01cSRoman Divacky           Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
491f22ef01cSRoman Divacky         } else {
492f22ef01cSRoman Divacky           Mask[i] = Mask[i] % e;  // Force to LHS.
493f22ef01cSRoman Divacky           Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
494f22ef01cSRoman Divacky                                           Mask[i]));
495f22ef01cSRoman Divacky         }
496f22ef01cSRoman Divacky       }
497f22ef01cSRoman Divacky     }
498f22ef01cSRoman Divacky     SVI.setOperand(0, SVI.getOperand(1));
499f22ef01cSRoman Divacky     SVI.setOperand(1, UndefValue::get(RHS->getType()));
500f22ef01cSRoman Divacky     SVI.setOperand(2, ConstantVector::get(Elts));
501f22ef01cSRoman Divacky     LHS = SVI.getOperand(0);
502f22ef01cSRoman Divacky     RHS = SVI.getOperand(1);
503f22ef01cSRoman Divacky     MadeChange = true;
504f22ef01cSRoman Divacky   }
505f22ef01cSRoman Divacky 
506f22ef01cSRoman Divacky   // Analyze the shuffle, are the LHS or RHS and identity shuffles?
507f22ef01cSRoman Divacky   bool isLHSID = true, isRHSID = true;
508f22ef01cSRoman Divacky 
509f22ef01cSRoman Divacky   for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
5102754fe60SDimitry Andric     if (Mask[i] < 0) continue;  // Ignore undef values.
511f22ef01cSRoman Divacky     // Is this an identity shuffle of the LHS value?
5122754fe60SDimitry Andric     isLHSID &= (Mask[i] == (int)i);
513f22ef01cSRoman Divacky 
514f22ef01cSRoman Divacky     // Is this an identity shuffle of the RHS value?
515f22ef01cSRoman Divacky     isRHSID &= (Mask[i]-e == i);
516f22ef01cSRoman Divacky   }
517f22ef01cSRoman Divacky 
518f22ef01cSRoman Divacky   // Eliminate identity shuffles.
519f22ef01cSRoman Divacky   if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
520f22ef01cSRoman Divacky   if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
521f22ef01cSRoman Divacky 
522f22ef01cSRoman Divacky   // If the LHS is a shufflevector itself, see if we can combine it with this
523f22ef01cSRoman Divacky   // one without producing an unusual shuffle.  Here we are really conservative:
524f22ef01cSRoman Divacky   // we are absolutely afraid of producing a shuffle mask not in the input
525f22ef01cSRoman Divacky   // program, because the code gen may not be smart enough to turn a merged
526f22ef01cSRoman Divacky   // shuffle into two specific shuffles: it may produce worse code.  As such,
5272754fe60SDimitry Andric   // we only merge two shuffles if the result is either a splat or one of the
5282754fe60SDimitry Andric   // two input shuffle masks.  In this case, merging the shuffles just removes
5292754fe60SDimitry Andric   // one instruction, which we know is safe.  This is good for things like
5302754fe60SDimitry Andric   // turning: (splat(splat)) -> splat.
531f22ef01cSRoman Divacky   if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
532f22ef01cSRoman Divacky     if (isa<UndefValue>(RHS)) {
5332754fe60SDimitry Andric       std::vector<int> LHSMask = getShuffleMask(LHSSVI);
534f22ef01cSRoman Divacky 
535f22ef01cSRoman Divacky       if (LHSMask.size() == Mask.size()) {
5362754fe60SDimitry Andric         std::vector<int> NewMask;
5372754fe60SDimitry Andric         bool isSplat = true;
5382754fe60SDimitry Andric         int SplatElt = -1; // undef
5392754fe60SDimitry Andric         for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
5402754fe60SDimitry Andric           int MaskElt;
5412754fe60SDimitry Andric           if (Mask[i] < 0 || Mask[i] >= (int)e)
5422754fe60SDimitry Andric             MaskElt = -1; // undef
543f22ef01cSRoman Divacky           else
5442754fe60SDimitry Andric             MaskElt = LHSMask[Mask[i]];
5452754fe60SDimitry Andric           // Check if this could still be a splat.
5462754fe60SDimitry Andric           if (MaskElt >= 0) {
5472754fe60SDimitry Andric             if (SplatElt >=0 && SplatElt != MaskElt)
5482754fe60SDimitry Andric               isSplat = false;
5492754fe60SDimitry Andric             SplatElt = MaskElt;
5502754fe60SDimitry Andric           }
5512754fe60SDimitry Andric           NewMask.push_back(MaskElt);
5522754fe60SDimitry Andric         }
553f22ef01cSRoman Divacky 
554f22ef01cSRoman Divacky         // If the result mask is equal to the src shuffle or this
555f22ef01cSRoman Divacky         // shuffle mask, do the replacement.
5562754fe60SDimitry Andric         if (isSplat || NewMask == LHSMask || NewMask == Mask) {
557f22ef01cSRoman Divacky           std::vector<Constant*> Elts;
5582754fe60SDimitry Andric           const Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
559f22ef01cSRoman Divacky           for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
5602754fe60SDimitry Andric             if (NewMask[i] < 0) {
5612754fe60SDimitry Andric               Elts.push_back(UndefValue::get(Int32Ty));
562f22ef01cSRoman Divacky             } else {
5632754fe60SDimitry Andric               Elts.push_back(ConstantInt::get(Int32Ty, NewMask[i]));
564f22ef01cSRoman Divacky             }
565f22ef01cSRoman Divacky           }
566f22ef01cSRoman Divacky           return new ShuffleVectorInst(LHSSVI->getOperand(0),
567f22ef01cSRoman Divacky                                        LHSSVI->getOperand(1),
568f22ef01cSRoman Divacky                                        ConstantVector::get(Elts));
569f22ef01cSRoman Divacky         }
570f22ef01cSRoman Divacky       }
571f22ef01cSRoman Divacky     }
572f22ef01cSRoman Divacky   }
573f22ef01cSRoman Divacky 
574f22ef01cSRoman Divacky   return MadeChange ? &SVI : 0;
575f22ef01cSRoman Divacky }
576