blob: 0f8ffb9aebc9bf461d67511621f21b571c1965d5 [file] [log] [blame]
Chris Lattnerec97a902010-01-05 05:36:20 +00001//===- InstCombineVectorOps.cpp -------------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements instcombine for ExtractElement, InsertElement and
11// ShuffleVector.
12//
13//===----------------------------------------------------------------------===//
14
15#include "InstCombine.h"
16using namespace llvm;
17
18/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
Chris Lattnera0d01ff2012-01-24 14:31:22 +000019/// is to leave as a vector operation. isConstant indicates whether we're
20/// extracting one known element. If false we're extracting a variable index.
Chris Lattnerec97a902010-01-05 05:36:20 +000021static bool CheapToScalarize(Value *V, bool isConstant) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +000022 if (isa<ConstantAggregateZero>(V))
Chris Lattnerec97a902010-01-05 05:36:20 +000023 return true;
24 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
25 if (isConstant) return true;
26 // If all elts are the same, we can extract.
27 Constant *Op0 = C->getOperand(0);
28 for (unsigned i = 1; i < C->getNumOperands(); ++i)
29 if (C->getOperand(i) != Op0)
30 return false;
31 return true;
32 }
33 Instruction *I = dyn_cast<Instruction>(V);
34 if (!I) return false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000035
Chris Lattnerec97a902010-01-05 05:36:20 +000036 // Insert element gets simplified to the inserted element or is deleted if
37 // this is constant idx extract element and its a constant idx insertelt.
38 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
39 isa<ConstantInt>(I->getOperand(2)))
40 return true;
41 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
42 return true;
43 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
44 if (BO->hasOneUse() &&
45 (CheapToScalarize(BO->getOperand(0), isConstant) ||
46 CheapToScalarize(BO->getOperand(1), isConstant)))
47 return true;
48 if (CmpInst *CI = dyn_cast<CmpInst>(I))
49 if (CI->hasOneUse() &&
50 (CheapToScalarize(CI->getOperand(0), isConstant) ||
51 CheapToScalarize(CI->getOperand(1), isConstant)))
52 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000053
Chris Lattnerec97a902010-01-05 05:36:20 +000054 return false;
55}
56
Bob Wilson11ee4562010-10-29 22:03:05 +000057/// getShuffleMask - Read and decode a shufflevector mask.
58/// Turn undef elements into negative values.
Eli Friedmance818272011-10-21 19:06:29 +000059static SmallVector<int, 16> getShuffleMask(const ShuffleVectorInst *SVI) {
Chris Lattnerec97a902010-01-05 05:36:20 +000060 unsigned NElts = SVI->getType()->getNumElements();
61 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
Eli Friedmance818272011-10-21 19:06:29 +000062 return SmallVector<int, 16>(NElts, 0);
Chris Lattnerec97a902010-01-05 05:36:20 +000063 if (isa<UndefValue>(SVI->getOperand(2)))
Eli Friedmance818272011-10-21 19:06:29 +000064 return SmallVector<int, 16>(NElts, -1);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000065
Eli Friedmance818272011-10-21 19:06:29 +000066 SmallVector<int, 16> Result;
Chris Lattnerec97a902010-01-05 05:36:20 +000067 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
68 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
69 if (isa<UndefValue>(*i))
Bob Wilson11ee4562010-10-29 22:03:05 +000070 Result.push_back(-1); // undef
Chris Lattnerec97a902010-01-05 05:36:20 +000071 else
72 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
73 return Result;
74}
75
76/// FindScalarElement - Given a vector and an element number, see if the scalar
77/// value is already around as a register, for example if it were inserted then
78/// extracted from the vector.
79static Value *FindScalarElement(Value *V, unsigned EltNo) {
Duncan Sands19d0b472010-02-16 11:11:14 +000080 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
Chris Lattner229907c2011-07-18 04:54:35 +000081 VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattnerec97a902010-01-05 05:36:20 +000082 unsigned Width = PTy->getNumElements();
83 if (EltNo >= Width) // Out of range access.
84 return UndefValue::get(PTy->getElementType());
Bob Wilson8ecf98b2010-10-29 22:20:43 +000085
Chris Lattnerec97a902010-01-05 05:36:20 +000086 if (isa<UndefValue>(V))
87 return UndefValue::get(PTy->getElementType());
Chris Lattner841af4f2010-01-05 05:42:08 +000088 if (isa<ConstantAggregateZero>(V))
Chris Lattnerec97a902010-01-05 05:36:20 +000089 return Constant::getNullValue(PTy->getElementType());
Chris Lattner841af4f2010-01-05 05:42:08 +000090 if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattnerec97a902010-01-05 05:36:20 +000091 return CP->getOperand(EltNo);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000092
Chris Lattner841af4f2010-01-05 05:42:08 +000093 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +000094 // If this is an insert to a variable element, we don't know what it is.
Bob Wilson8ecf98b2010-10-29 22:20:43 +000095 if (!isa<ConstantInt>(III->getOperand(2)))
Chris Lattnerec97a902010-01-05 05:36:20 +000096 return 0;
97 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +000098
Chris Lattnerec97a902010-01-05 05:36:20 +000099 // If this is an insert to the element we are looking for, return the
100 // inserted value.
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000101 if (EltNo == IIElt)
Chris Lattnerec97a902010-01-05 05:36:20 +0000102 return III->getOperand(1);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000103
Chris Lattnerec97a902010-01-05 05:36:20 +0000104 // Otherwise, the insertelement doesn't modify the value, recurse on its
105 // vector input.
106 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner841af4f2010-01-05 05:42:08 +0000107 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000108
Chris Lattner841af4f2010-01-05 05:42:08 +0000109 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000110 unsigned LHSWidth =
Bob Wilson11ee4562010-10-29 22:03:05 +0000111 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Eli Friedman303c81c2011-10-21 19:11:34 +0000112 int InEl = SVI->getMaskValue(EltNo);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000113 if (InEl < 0)
Chris Lattnerec97a902010-01-05 05:36:20 +0000114 return UndefValue::get(PTy->getElementType());
Bob Wilson11ee4562010-10-29 22:03:05 +0000115 if (InEl < (int)LHSWidth)
116 return FindScalarElement(SVI->getOperand(0), InEl);
117 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattnerec97a902010-01-05 05:36:20 +0000118 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000119
Chris Lattnerec97a902010-01-05 05:36:20 +0000120 // Otherwise, we don't know.
121 return 0;
122}
123
124Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
125 // If vector val is undef, replace extract with scalar undef.
126 if (isa<UndefValue>(EI.getOperand(0)))
127 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000128
Chris Lattnerec97a902010-01-05 05:36:20 +0000129 // If vector val is constant 0, replace extract with scalar 0.
130 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
131 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000132
Chris Lattnerec97a902010-01-05 05:36:20 +0000133 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
134 // If vector val is constant with all elements the same, replace EI with
135 // that element. When the elements are not identical, we cannot replace yet
136 // (we do that below, but only when the index is constant).
137 Constant *op0 = C->getOperand(0);
138 for (unsigned i = 1; i != C->getNumOperands(); ++i)
139 if (C->getOperand(i) != op0) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000140 op0 = 0;
Chris Lattnerec97a902010-01-05 05:36:20 +0000141 break;
142 }
143 if (op0)
144 return ReplaceInstUsesWith(EI, op0);
145 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000146
Chris Lattnerec97a902010-01-05 05:36:20 +0000147 // If extracting a specified index from the vector, see if we can recursively
148 // find a previously computed scalar that was inserted into the vector.
149 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
150 unsigned IndexVal = IdxC->getZExtValue();
151 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000152
Chris Lattnerec97a902010-01-05 05:36:20 +0000153 // If this is extracting an invalid index, turn this into undef, to avoid
154 // crashing the code below.
155 if (IndexVal >= VectorWidth)
156 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000157
Chris Lattnerec97a902010-01-05 05:36:20 +0000158 // This instruction only demands the single element from the input vector.
159 // If the input vector has a single use, simplify it based on this use
160 // property.
161 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
162 APInt UndefElts(VectorWidth, 0);
Chris Lattnerb22423c2010-02-08 23:56:03 +0000163 APInt DemandedMask(VectorWidth, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +0000164 DemandedMask.setBit(IndexVal);
Chris Lattnerec97a902010-01-05 05:36:20 +0000165 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
166 DemandedMask, UndefElts)) {
167 EI.setOperand(0, V);
168 return &EI;
169 }
170 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000171
Chris Lattnerec97a902010-01-05 05:36:20 +0000172 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
173 return ReplaceInstUsesWith(EI, Elt);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000174
Chris Lattnerec97a902010-01-05 05:36:20 +0000175 // If the this extractelement is directly using a bitcast from a vector of
176 // the same number of elements, see if we can find the source element from
177 // it. In this case, we will end up needing to bitcast the scalars.
178 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
Chris Lattner229907c2011-07-18 04:54:35 +0000179 if (VectorType *VT =
Chris Lattnerec97a902010-01-05 05:36:20 +0000180 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
181 if (VT->getNumElements() == VectorWidth)
182 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
183 return new BitCastInst(Elt, EI.getType());
184 }
185 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000186
Chris Lattnerec97a902010-01-05 05:36:20 +0000187 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
188 // Push extractelement into predecessor operation if legal and
189 // profitable to do so
190 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
191 if (I->hasOneUse() &&
192 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
193 Value *newEI0 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000194 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
195 EI.getName()+".lhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000196 Value *newEI1 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000197 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
198 EI.getName()+".rhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000199 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
200 }
201 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
202 // Extracting the inserted element?
203 if (IE->getOperand(2) == EI.getOperand(1))
204 return ReplaceInstUsesWith(EI, IE->getOperand(1));
205 // If the inserted and extracted elements are constants, they must not
206 // be the same value, extract from the pre-inserted value instead.
207 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
208 Worklist.AddValue(EI.getOperand(0));
209 EI.setOperand(0, IE->getOperand(0));
210 return &EI;
211 }
212 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
213 // If this is extracting an element from a shufflevector, figure out where
214 // it came from and extract from the appropriate input element instead.
215 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Eli Friedman303c81c2011-10-21 19:11:34 +0000216 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
Chris Lattnerec97a902010-01-05 05:36:20 +0000217 Value *Src;
218 unsigned LHSWidth =
Bob Wilson11ee4562010-10-29 22:03:05 +0000219 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000220
Bob Wilson11ee4562010-10-29 22:03:05 +0000221 if (SrcIdx < 0)
222 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
223 if (SrcIdx < (int)LHSWidth)
Chris Lattnerec97a902010-01-05 05:36:20 +0000224 Src = SVI->getOperand(0);
Bob Wilson11ee4562010-10-29 22:03:05 +0000225 else {
Chris Lattnerec97a902010-01-05 05:36:20 +0000226 SrcIdx -= LHSWidth;
227 Src = SVI->getOperand(1);
Chris Lattnerec97a902010-01-05 05:36:20 +0000228 }
Chris Lattner229907c2011-07-18 04:54:35 +0000229 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
Chris Lattnerec97a902010-01-05 05:36:20 +0000230 return ExtractElementInst::Create(Src,
Bob Wilson9d07f392010-10-29 22:03:07 +0000231 ConstantInt::get(Int32Ty,
Chris Lattnerec97a902010-01-05 05:36:20 +0000232 SrcIdx, false));
233 }
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000234 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
235 // Canonicalize extractelement(cast) -> cast(extractelement)
236 // bitcasts can change the number of vector elements and they cost nothing
237 if (CI->hasOneUse() && EI.hasOneUse() &&
238 (CI->getOpcode() != Instruction::BitCast)) {
239 Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
240 EI.getIndexOperand());
241 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
242 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000243 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000244 }
245 return 0;
246}
247
248/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000249/// elements from either LHS or RHS, return the shuffle mask and true.
Chris Lattnerec97a902010-01-05 05:36:20 +0000250/// Otherwise, return false.
251static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
252 std::vector<Constant*> &Mask) {
253 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
254 "Invalid CollectSingleShuffleElements");
255 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000256
Chris Lattnerec97a902010-01-05 05:36:20 +0000257 if (isa<UndefValue>(V)) {
258 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
259 return true;
260 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000261
Chris Lattnerec97a902010-01-05 05:36:20 +0000262 if (V == LHS) {
263 for (unsigned i = 0; i != NumElts; ++i)
264 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
265 return true;
266 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000267
Chris Lattnerec97a902010-01-05 05:36:20 +0000268 if (V == RHS) {
269 for (unsigned i = 0; i != NumElts; ++i)
270 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
271 i+NumElts));
272 return true;
273 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000274
Chris Lattnerec97a902010-01-05 05:36:20 +0000275 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
276 // If this is an insert of an extract from some other vector, include it.
277 Value *VecOp = IEI->getOperand(0);
278 Value *ScalarOp = IEI->getOperand(1);
279 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000280
Chris Lattnerec97a902010-01-05 05:36:20 +0000281 if (!isa<ConstantInt>(IdxOp))
282 return false;
283 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000284
Chris Lattnerec97a902010-01-05 05:36:20 +0000285 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
286 // Okay, we can handle this if the vector we are insertinting into is
287 // transitively ok.
288 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
289 // If so, update the mask to reflect the inserted undef.
290 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
291 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000292 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000293 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
294 if (isa<ConstantInt>(EI->getOperand(1)) &&
295 EI->getOperand(0)->getType() == V->getType()) {
296 unsigned ExtractedIdx =
297 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000298
Chris Lattnerec97a902010-01-05 05:36:20 +0000299 // This must be extracting from either LHS or RHS.
300 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
301 // Okay, we can handle this if the vector we are insertinting into is
302 // transitively ok.
303 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
304 // If so, update the mask to reflect the inserted value.
305 if (EI->getOperand(0) == LHS) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000306 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000307 ConstantInt::get(Type::getInt32Ty(V->getContext()),
308 ExtractedIdx);
309 } else {
310 assert(EI->getOperand(0) == RHS);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000311 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000312 ConstantInt::get(Type::getInt32Ty(V->getContext()),
313 ExtractedIdx+NumElts);
Chris Lattnerec97a902010-01-05 05:36:20 +0000314 }
315 return true;
316 }
317 }
318 }
319 }
320 }
321 // TODO: Handle shufflevector here!
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000322
Chris Lattnerec97a902010-01-05 05:36:20 +0000323 return false;
324}
325
326/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
327/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
328/// that computes V and the LHS value of the shuffle.
329static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
330 Value *&RHS) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000331 assert(V->getType()->isVectorTy() &&
Chris Lattnerec97a902010-01-05 05:36:20 +0000332 (RHS == 0 || V->getType() == RHS->getType()) &&
333 "Invalid shuffle!");
334 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000335
Chris Lattnerec97a902010-01-05 05:36:20 +0000336 if (isa<UndefValue>(V)) {
337 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
338 return V;
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000339 }
340
341 if (isa<ConstantAggregateZero>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000342 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
343 return V;
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000344 }
345
346 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000347 // If this is an insert of an extract from some other vector, include it.
348 Value *VecOp = IEI->getOperand(0);
349 Value *ScalarOp = IEI->getOperand(1);
350 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000351
Chris Lattnerec97a902010-01-05 05:36:20 +0000352 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
353 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
354 EI->getOperand(0)->getType() == V->getType()) {
355 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000356 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000357 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000358
Chris Lattnerec97a902010-01-05 05:36:20 +0000359 // Either the extracted from or inserted into vector must be RHSVec,
360 // otherwise we'd end up with a shuffle of three inputs.
361 if (EI->getOperand(0) == RHS || RHS == 0) {
362 RHS = EI->getOperand(0);
363 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000364 Mask[InsertedIdx % NumElts] =
Bob Wilson67a6f322010-10-29 22:20:45 +0000365 ConstantInt::get(Type::getInt32Ty(V->getContext()),
366 NumElts+ExtractedIdx);
Chris Lattnerec97a902010-01-05 05:36:20 +0000367 return V;
368 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000369
Chris Lattnerec97a902010-01-05 05:36:20 +0000370 if (VecOp == RHS) {
371 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
372 // Everything but the extracted element is replaced with the RHS.
373 for (unsigned i = 0; i != NumElts; ++i) {
374 if (i != InsertedIdx)
375 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()),
376 NumElts+i);
377 }
378 return V;
379 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000380
Chris Lattnerec97a902010-01-05 05:36:20 +0000381 // If this insertelement is a chain that comes from exactly these two
382 // vectors, return the vector and the effective shuffle.
383 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
384 return EI->getOperand(0);
385 }
386 }
387 }
388 // TODO: Handle shufflevector here!
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000389
Chris Lattnerec97a902010-01-05 05:36:20 +0000390 // Otherwise, can't do anything fancy. Return an identity vector.
391 for (unsigned i = 0; i != NumElts; ++i)
392 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
393 return V;
394}
395
396Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
397 Value *VecOp = IE.getOperand(0);
398 Value *ScalarOp = IE.getOperand(1);
399 Value *IdxOp = IE.getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000400
Chris Lattnerec97a902010-01-05 05:36:20 +0000401 // Inserting an undef or into an undefined place, remove this.
402 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
403 ReplaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000404
405 // If the inserted element was extracted from some other vector, and if the
Chris Lattnerec97a902010-01-05 05:36:20 +0000406 // indexes are constant, try to turn this into a shufflevector operation.
407 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
408 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
409 EI->getOperand(0)->getType() == IE.getType()) {
410 unsigned NumVectorElts = IE.getType()->getNumElements();
411 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000412 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000413 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000414
Chris Lattnerec97a902010-01-05 05:36:20 +0000415 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
416 return ReplaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000417
Chris Lattnerec97a902010-01-05 05:36:20 +0000418 if (InsertedIdx >= NumVectorElts) // Out of range insert.
419 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000420
Chris Lattnerec97a902010-01-05 05:36:20 +0000421 // If we are extracting a value from a vector, then inserting it right
422 // back into the same place, just use the input vector.
423 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000424 return ReplaceInstUsesWith(IE, VecOp);
425
Chris Lattnerec97a902010-01-05 05:36:20 +0000426 // If this insertelement isn't used by some other insertelement, turn it
427 // (and any insertelements it points to), into one big shuffle.
428 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
429 std::vector<Constant*> Mask;
430 Value *RHS = 0;
431 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
432 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
433 // We now have a shuffle of LHS, RHS, Mask.
Bob Wilson67a6f322010-10-29 22:20:45 +0000434 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerec97a902010-01-05 05:36:20 +0000435 }
436 }
437 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000438
Chris Lattnerec97a902010-01-05 05:36:20 +0000439 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
440 APInt UndefElts(VWidth, 0);
441 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000442 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
443 if (V != &IE)
444 return ReplaceInstUsesWith(IE, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000445 return &IE;
Eli Friedmanef200db2011-02-19 22:42:40 +0000446 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000447
Chris Lattnerec97a902010-01-05 05:36:20 +0000448 return 0;
449}
450
451
452Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
453 Value *LHS = SVI.getOperand(0);
454 Value *RHS = SVI.getOperand(1);
Eli Friedmance818272011-10-21 19:06:29 +0000455 SmallVector<int, 16> Mask = getShuffleMask(&SVI);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000456
Chris Lattnerec97a902010-01-05 05:36:20 +0000457 bool MadeChange = false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000458
Chris Lattnerec97a902010-01-05 05:36:20 +0000459 // Undefined shuffle mask -> undefined value.
460 if (isa<UndefValue>(SVI.getOperand(2)))
461 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000462
Eric Christopher51edc7b2010-08-17 22:55:27 +0000463 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000464
Chris Lattnerec97a902010-01-05 05:36:20 +0000465 APInt UndefElts(VWidth, 0);
466 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000467 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
468 if (V != &SVI)
469 return ReplaceInstUsesWith(SVI, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000470 LHS = SVI.getOperand(0);
471 RHS = SVI.getOperand(1);
472 MadeChange = true;
473 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000474
Eli Friedmance818272011-10-21 19:06:29 +0000475 unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
476
Chris Lattnerec97a902010-01-05 05:36:20 +0000477 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
478 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
479 if (LHS == RHS || isa<UndefValue>(LHS)) {
Eric Christopher51edc7b2010-08-17 22:55:27 +0000480 if (isa<UndefValue>(LHS) && LHS == RHS) {
481 // shuffle(undef,undef,mask) -> undef.
Eli Friedmance818272011-10-21 19:06:29 +0000482 Value* result = (VWidth == LHSWidth)
483 ? LHS : UndefValue::get(SVI.getType());
484 return ReplaceInstUsesWith(SVI, result);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000485 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000486
Chris Lattnerec97a902010-01-05 05:36:20 +0000487 // Remap any references to RHS to use LHS.
488 std::vector<Constant*> Elts;
Eli Friedmance818272011-10-21 19:06:29 +0000489 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
Bob Wilson11ee4562010-10-29 22:03:05 +0000490 if (Mask[i] < 0)
Chris Lattnerec97a902010-01-05 05:36:20 +0000491 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
492 else {
Bob Wilson11ee4562010-10-29 22:03:05 +0000493 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
494 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
495 Mask[i] = -1; // Turn into undef.
Chris Lattnerec97a902010-01-05 05:36:20 +0000496 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
497 } else {
498 Mask[i] = Mask[i] % e; // Force to LHS.
499 Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
500 Mask[i]));
501 }
502 }
503 }
504 SVI.setOperand(0, SVI.getOperand(1));
505 SVI.setOperand(1, UndefValue::get(RHS->getType()));
506 SVI.setOperand(2, ConstantVector::get(Elts));
507 LHS = SVI.getOperand(0);
508 RHS = SVI.getOperand(1);
509 MadeChange = true;
510 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000511
Eli Friedmance818272011-10-21 19:06:29 +0000512 if (VWidth == LHSWidth) {
513 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
514 bool isLHSID = true, isRHSID = true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000515
Eli Friedmance818272011-10-21 19:06:29 +0000516 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
517 if (Mask[i] < 0) continue; // Ignore undef values.
518 // Is this an identity shuffle of the LHS value?
519 isLHSID &= (Mask[i] == (int)i);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000520
Eli Friedmance818272011-10-21 19:06:29 +0000521 // Is this an identity shuffle of the RHS value?
522 isRHSID &= (Mask[i]-e == i);
523 }
524
525 // Eliminate identity shuffles.
526 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
527 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000528 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000529
Eric Christopher51edc7b2010-08-17 22:55:27 +0000530 // If the LHS is a shufflevector itself, see if we can combine it with this
Eli Friedmance818272011-10-21 19:06:29 +0000531 // one without producing an unusual shuffle.
532 // Cases that might be simplified:
533 // 1.
534 // x1=shuffle(v1,v2,mask1)
535 // x=shuffle(x1,undef,mask)
536 // ==>
537 // x=shuffle(v1,undef,newMask)
538 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
539 // 2.
540 // x1=shuffle(v1,undef,mask1)
541 // x=shuffle(x1,x2,mask)
542 // where v1.size() == mask1.size()
543 // ==>
544 // x=shuffle(v1,x2,newMask)
545 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
546 // 3.
547 // x2=shuffle(v2,undef,mask2)
548 // x=shuffle(x1,x2,mask)
549 // where v2.size() == mask2.size()
550 // ==>
551 // x=shuffle(x1,v2,newMask)
552 // newMask[i] = (mask[i] < x1.size())
553 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
554 // 4.
555 // x1=shuffle(v1,undef,mask1)
556 // x2=shuffle(v2,undef,mask2)
557 // x=shuffle(x1,x2,mask)
558 // where v1.size() == v2.size()
559 // ==>
560 // x=shuffle(v1,v2,newMask)
561 // newMask[i] = (mask[i] < x1.size())
562 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
563 //
564 // Here we are really conservative:
Eric Christopher51edc7b2010-08-17 22:55:27 +0000565 // we are absolutely afraid of producing a shuffle mask not in the input
566 // program, because the code gen may not be smart enough to turn a merged
567 // shuffle into two specific shuffles: it may produce worse code. As such,
Bob Wilsoncb11b482010-10-29 22:02:50 +0000568 // we only merge two shuffles if the result is either a splat or one of the
Eli Friedmance818272011-10-21 19:06:29 +0000569 // input shuffle masks. In this case, merging the shuffles just removes
Bob Wilsoncb11b482010-10-29 22:02:50 +0000570 // one instruction, which we know is safe. This is good for things like
Eli Friedmance818272011-10-21 19:06:29 +0000571 // turning: (splat(splat)) -> splat, or
572 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
573 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
574 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
575 if (LHSShuffle)
576 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
577 LHSShuffle = NULL;
578 if (RHSShuffle)
579 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
580 RHSShuffle = NULL;
581 if (!LHSShuffle && !RHSShuffle)
582 return MadeChange ? &SVI : 0;
583
584 Value* LHSOp0 = NULL;
585 Value* LHSOp1 = NULL;
586 Value* RHSOp0 = NULL;
587 unsigned LHSOp0Width = 0;
588 unsigned RHSOp0Width = 0;
589 if (LHSShuffle) {
590 LHSOp0 = LHSShuffle->getOperand(0);
591 LHSOp1 = LHSShuffle->getOperand(1);
592 LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
593 }
594 if (RHSShuffle) {
595 RHSOp0 = RHSShuffle->getOperand(0);
596 RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
597 }
598 Value* newLHS = LHS;
599 Value* newRHS = RHS;
600 if (LHSShuffle) {
601 // case 1
Eric Christopher51edc7b2010-08-17 22:55:27 +0000602 if (isa<UndefValue>(RHS)) {
Eli Friedmance818272011-10-21 19:06:29 +0000603 newLHS = LHSOp0;
604 newRHS = LHSOp1;
605 }
606 // case 2 or 4
607 else if (LHSOp0Width == LHSWidth) {
608 newLHS = LHSOp0;
609 }
610 }
611 // case 3 or 4
612 if (RHSShuffle && RHSOp0Width == LHSWidth) {
613 newRHS = RHSOp0;
614 }
615 // case 4
616 if (LHSOp0 == RHSOp0) {
617 newLHS = LHSOp0;
618 newRHS = NULL;
619 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000620
Eli Friedmance818272011-10-21 19:06:29 +0000621 if (newLHS == LHS && newRHS == RHS)
622 return MadeChange ? &SVI : 0;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000623
Eli Friedmance818272011-10-21 19:06:29 +0000624 SmallVector<int, 16> LHSMask;
625 SmallVector<int, 16> RHSMask;
626 if (newLHS != LHS) {
627 LHSMask = getShuffleMask(LHSShuffle);
628 }
629 if (RHSShuffle && newRHS != RHS) {
630 RHSMask = getShuffleMask(RHSShuffle);
631 }
632 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
633 SmallVector<int, 16> newMask;
634 bool isSplat = true;
635 int SplatElt = -1;
636 // Create a new mask for the new ShuffleVectorInst so that the new
637 // ShuffleVectorInst is equivalent to the original one.
638 for (unsigned i = 0; i < VWidth; ++i) {
639 int eltMask;
640 if (Mask[i] == -1) {
641 // This element is an undef value.
642 eltMask = -1;
643 } else if (Mask[i] < (int)LHSWidth) {
644 // This element is from left hand side vector operand.
645 //
646 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
647 // new mask value for the element.
648 if (newLHS != LHS) {
649 eltMask = LHSMask[Mask[i]];
650 // If the value selected is an undef value, explicitly specify it
651 // with a -1 mask value.
652 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
653 eltMask = -1;
654 }
655 else
656 eltMask = Mask[i];
657 } else {
658 // This element is from right hand side vector operand
659 //
660 // If the value selected is an undef value, explicitly specify it
661 // with a -1 mask value. (case 1)
662 if (isa<UndefValue>(RHS))
663 eltMask = -1;
664 // If RHS is going to be replaced (case 3 or 4), calculate the
665 // new mask value for the element.
666 else if (newRHS != RHS) {
667 eltMask = RHSMask[Mask[i]-LHSWidth];
668 // If the value selected is an undef value, explicitly specify it
669 // with a -1 mask value.
670 if (eltMask >= (int)RHSOp0Width) {
671 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
672 && "should have been check above");
673 eltMask = -1;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +0000674 }
675 }
Eli Friedmance818272011-10-21 19:06:29 +0000676 else
677 eltMask = Mask[i]-LHSWidth;
678
679 // If LHS's width is changed, shift the mask value accordingly.
680 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
681 // references to RHSOp0 to LHSOp0, so we don't need to shift the mask.
682 if (eltMask >= 0 && newRHS != NULL)
683 eltMask += newLHSWidth;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +0000684 }
Eli Friedmance818272011-10-21 19:06:29 +0000685
686 // Check if this could still be a splat.
687 if (eltMask >= 0) {
688 if (SplatElt >= 0 && SplatElt != eltMask)
689 isSplat = false;
690 SplatElt = eltMask;
691 }
692
693 newMask.push_back(eltMask);
694 }
695
696 // If the result mask is equal to one of the original shuffle masks,
697 // or is a splat, do the replacement.
698 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
699 SmallVector<Constant*, 16> Elts;
700 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
701 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
702 if (newMask[i] < 0) {
703 Elts.push_back(UndefValue::get(Int32Ty));
704 } else {
705 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
706 }
707 }
708 if (newRHS == NULL)
709 newRHS = UndefValue::get(newLHS->getType());
710 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
Nate Begeman2a0ca3e92010-08-13 00:17:53 +0000711 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000712
Chris Lattnerec97a902010-01-05 05:36:20 +0000713 return MadeChange ? &SVI : 0;
714}