blob: 501d87ca4ada70d8b6f5cbca553522b68c543e9f [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
Chandler Carruth5f1f26e2014-04-21 19:51:41 +000015#define DEBUG_TYPE "instcombine"
Chris Lattnerec97a902010-01-05 05:36:20 +000016#include "InstCombine.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000017#include "llvm/IR/PatternMatch.h"
Chris Lattnerec97a902010-01-05 05:36:20 +000018using namespace llvm;
Nadav Rotem7df85092013-01-15 23:43:14 +000019using namespace PatternMatch;
Chris Lattnerec97a902010-01-05 05:36:20 +000020
21/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
Chris Lattnera0d01ff2012-01-24 14:31:22 +000022/// is to leave as a vector operation. isConstant indicates whether we're
23/// extracting one known element. If false we're extracting a variable index.
Chris Lattnerec97a902010-01-05 05:36:20 +000024static bool CheapToScalarize(Value *V, bool isConstant) {
Chris Lattner8326bd82012-01-26 00:42:34 +000025 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +000026 if (isConstant) return true;
Chris Lattner8326bd82012-01-26 00:42:34 +000027
28 // If all elts are the same, we can extract it and use any of the values.
Benjamin Kramer09b0f882014-01-24 19:02:37 +000029 if (Constant *Op0 = C->getAggregateElement(0U)) {
30 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
31 ++i)
32 if (C->getAggregateElement(i) != Op0)
33 return false;
34 return true;
35 }
Chris Lattnerec97a902010-01-05 05:36:20 +000036 }
37 Instruction *I = dyn_cast<Instruction>(V);
38 if (!I) return false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000039
Chris Lattnerec97a902010-01-05 05:36:20 +000040 // Insert element gets simplified to the inserted element or is deleted if
41 // this is constant idx extract element and its a constant idx insertelt.
42 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
43 isa<ConstantInt>(I->getOperand(2)))
44 return true;
45 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
46 return true;
47 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
48 if (BO->hasOneUse() &&
49 (CheapToScalarize(BO->getOperand(0), isConstant) ||
50 CheapToScalarize(BO->getOperand(1), isConstant)))
51 return true;
52 if (CmpInst *CI = dyn_cast<CmpInst>(I))
53 if (CI->hasOneUse() &&
54 (CheapToScalarize(CI->getOperand(0), isConstant) ||
55 CheapToScalarize(CI->getOperand(1), isConstant)))
56 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000057
Chris Lattnerec97a902010-01-05 05:36:20 +000058 return false;
59}
60
Chris Lattnerec97a902010-01-05 05:36:20 +000061/// FindScalarElement - Given a vector and an element number, see if the scalar
62/// value is already around as a register, for example if it were inserted then
63/// extracted from the vector.
64static Value *FindScalarElement(Value *V, unsigned EltNo) {
Duncan Sands19d0b472010-02-16 11:11:14 +000065 assert(V->getType()->isVectorTy() && "Not looking at a vector?");
Chris Lattner8326bd82012-01-26 00:42:34 +000066 VectorType *VTy = cast<VectorType>(V->getType());
67 unsigned Width = VTy->getNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +000068 if (EltNo >= Width) // Out of range access.
Chris Lattner8326bd82012-01-26 00:42:34 +000069 return UndefValue::get(VTy->getElementType());
Bob Wilson8ecf98b2010-10-29 22:20:43 +000070
Chris Lattner8326bd82012-01-26 00:42:34 +000071 if (Constant *C = dyn_cast<Constant>(V))
72 return C->getAggregateElement(EltNo);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000073
Chris Lattner841af4f2010-01-05 05:42:08 +000074 if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +000075 // If this is an insert to a variable element, we don't know what it is.
Bob Wilson8ecf98b2010-10-29 22:20:43 +000076 if (!isa<ConstantInt>(III->getOperand(2)))
Chris Lattnerec97a902010-01-05 05:36:20 +000077 return 0;
78 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +000079
Chris Lattnerec97a902010-01-05 05:36:20 +000080 // If this is an insert to the element we are looking for, return the
81 // inserted value.
Bob Wilson8ecf98b2010-10-29 22:20:43 +000082 if (EltNo == IIElt)
Chris Lattnerec97a902010-01-05 05:36:20 +000083 return III->getOperand(1);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000084
Chris Lattnerec97a902010-01-05 05:36:20 +000085 // Otherwise, the insertelement doesn't modify the value, recurse on its
86 // vector input.
87 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner841af4f2010-01-05 05:42:08 +000088 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +000089
Chris Lattner841af4f2010-01-05 05:42:08 +000090 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner8326bd82012-01-26 00:42:34 +000091 unsigned LHSWidth = SVI->getOperand(0)->getType()->getVectorNumElements();
Eli Friedman303c81c2011-10-21 19:11:34 +000092 int InEl = SVI->getMaskValue(EltNo);
Bob Wilson8ecf98b2010-10-29 22:20:43 +000093 if (InEl < 0)
Chris Lattner8326bd82012-01-26 00:42:34 +000094 return UndefValue::get(VTy->getElementType());
Bob Wilson11ee4562010-10-29 22:03:05 +000095 if (InEl < (int)LHSWidth)
96 return FindScalarElement(SVI->getOperand(0), InEl);
97 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Chris Lattnerec97a902010-01-05 05:36:20 +000098 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +000099
Nadav Rotem7df85092013-01-15 23:43:14 +0000100 // Extract a value from a vector add operation with a constant zero.
101 Value *Val = 0; Constant *Con = 0;
102 if (match(V, m_Add(m_Value(Val), m_Constant(Con)))) {
103 if (Con->getAggregateElement(EltNo)->isNullValue())
104 return FindScalarElement(Val, EltNo);
105 }
106
Chris Lattnerec97a902010-01-05 05:36:20 +0000107 // Otherwise, we don't know.
108 return 0;
109}
110
Anat Shemer0c95efa2013-04-18 19:35:39 +0000111// If we have a PHI node with a vector type that has only 2 uses: feed
Matt Arsenault38874732013-08-28 22:17:26 +0000112// itself and be an operand of extractelement at a constant location,
113// try to replace the PHI of the vector type with a PHI of a scalar type.
Anat Shemer0c95efa2013-04-18 19:35:39 +0000114Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
115 // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
116 if (!PN->hasNUses(2))
117 return NULL;
118
119 // If so, it's known at this point that one operand is PHI and the other is
120 // an extractelement node. Find the PHI user that is not the extractelement
121 // node.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000122 auto iu = PN->user_begin();
Anat Shemer0c95efa2013-04-18 19:35:39 +0000123 Instruction *PHIUser = dyn_cast<Instruction>(*iu);
124 if (PHIUser == cast<Instruction>(&EI))
125 PHIUser = cast<Instruction>(*(++iu));
126
127 // Verify that this PHI user has one use, which is the PHI itself,
128 // and that it is a binary operation which is cheap to scalarize.
129 // otherwise return NULL.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000130 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
Joey Goulyb34294d2013-05-24 12:33:28 +0000131 !(isa<BinaryOperator>(PHIUser)) || !CheapToScalarize(PHIUser, true))
Anat Shemer0c95efa2013-04-18 19:35:39 +0000132 return NULL;
133
134 // Create a scalar PHI node that will replace the vector PHI node
135 // just before the current PHI node.
Joey Goulyb34294d2013-05-24 12:33:28 +0000136 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
137 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
Anat Shemer0c95efa2013-04-18 19:35:39 +0000138 // Scalarize each PHI operand.
Joey Goulyb34294d2013-05-24 12:33:28 +0000139 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
Anat Shemer0c95efa2013-04-18 19:35:39 +0000140 Value *PHIInVal = PN->getIncomingValue(i);
141 BasicBlock *inBB = PN->getIncomingBlock(i);
142 Value *Elt = EI.getIndexOperand();
143 // If the operand is the PHI induction variable:
144 if (PHIInVal == PHIUser) {
145 // Scalarize the binary operation. Its first operand is the
146 // scalar PHI and the second operand is extracted from the other
147 // vector operand.
148 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
Joey Goulyb34294d2013-05-24 12:33:28 +0000149 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
Joey Gouly83699282013-05-24 12:29:54 +0000150 Value *Op = InsertNewInstWith(
151 ExtractElementInst::Create(B0->getOperand(opId), Elt,
152 B0->getOperand(opId)->getName() + ".Elt"),
153 *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000154 Value *newPHIUser = InsertNewInstWith(
Joey Goulyb34294d2013-05-24 12:33:28 +0000155 BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000156 scalarPHI->addIncoming(newPHIUser, inBB);
157 } else {
158 // Scalarize PHI input:
Joey Goulyb34294d2013-05-24 12:33:28 +0000159 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
Anat Shemer0c95efa2013-04-18 19:35:39 +0000160 // Insert the new instruction into the predecessor basic block.
161 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
162 BasicBlock::iterator InsertPos;
163 if (pos && !isa<PHINode>(pos)) {
164 InsertPos = pos;
165 ++InsertPos;
166 } else {
167 InsertPos = inBB->getFirstInsertionPt();
168 }
169
170 InsertNewInstWith(newEI, *InsertPos);
171
172 scalarPHI->addIncoming(newEI, inBB);
173 }
174 }
175 return ReplaceInstUsesWith(EI, scalarPHI);
176}
177
Chris Lattnerec97a902010-01-05 05:36:20 +0000178Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner8326bd82012-01-26 00:42:34 +0000179 // If vector val is constant with all elements the same, replace EI with
180 // that element. We handle a known element # below.
181 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
182 if (CheapToScalarize(C, false))
183 return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000184
Chris Lattnerec97a902010-01-05 05:36:20 +0000185 // If extracting a specified index from the vector, see if we can recursively
186 // find a previously computed scalar that was inserted into the vector.
187 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
188 unsigned IndexVal = IdxC->getZExtValue();
189 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000190
Chris Lattnerec97a902010-01-05 05:36:20 +0000191 // If this is extracting an invalid index, turn this into undef, to avoid
192 // crashing the code below.
193 if (IndexVal >= VectorWidth)
194 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000195
Chris Lattnerec97a902010-01-05 05:36:20 +0000196 // This instruction only demands the single element from the input vector.
197 // If the input vector has a single use, simplify it based on this use
198 // property.
199 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
200 APInt UndefElts(VectorWidth, 0);
Chris Lattnerb22423c2010-02-08 23:56:03 +0000201 APInt DemandedMask(VectorWidth, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +0000202 DemandedMask.setBit(IndexVal);
Chris Lattnerec97a902010-01-05 05:36:20 +0000203 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
204 DemandedMask, UndefElts)) {
205 EI.setOperand(0, V);
206 return &EI;
207 }
208 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000209
Chris Lattnerec97a902010-01-05 05:36:20 +0000210 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
211 return ReplaceInstUsesWith(EI, Elt);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000212
Chris Lattnerec97a902010-01-05 05:36:20 +0000213 // If the this extractelement is directly using a bitcast from a vector of
214 // the same number of elements, see if we can find the source element from
215 // it. In this case, we will end up needing to bitcast the scalars.
216 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
Chris Lattner8326bd82012-01-26 00:42:34 +0000217 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
Chris Lattnerec97a902010-01-05 05:36:20 +0000218 if (VT->getNumElements() == VectorWidth)
219 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
220 return new BitCastInst(Elt, EI.getType());
221 }
Anat Shemer0c95efa2013-04-18 19:35:39 +0000222
223 // If there's a vector PHI feeding a scalar use through this extractelement
224 // instruction, try to scalarize the PHI.
225 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
Nick Lewycky881e9d62013-05-04 01:08:15 +0000226 Instruction *scalarPHI = scalarizePHI(EI, PN);
227 if (scalarPHI)
Joey Goulyb34294d2013-05-24 12:33:28 +0000228 return scalarPHI;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000229 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000230 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000231
Chris Lattnerec97a902010-01-05 05:36:20 +0000232 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
233 // Push extractelement into predecessor operation if legal and
234 // profitable to do so
235 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
236 if (I->hasOneUse() &&
237 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
238 Value *newEI0 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000239 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
240 EI.getName()+".lhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000241 Value *newEI1 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000242 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
243 EI.getName()+".rhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000244 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
245 }
246 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
247 // Extracting the inserted element?
248 if (IE->getOperand(2) == EI.getOperand(1))
249 return ReplaceInstUsesWith(EI, IE->getOperand(1));
250 // If the inserted and extracted elements are constants, they must not
251 // be the same value, extract from the pre-inserted value instead.
252 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
253 Worklist.AddValue(EI.getOperand(0));
254 EI.setOperand(0, IE->getOperand(0));
255 return &EI;
256 }
257 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
258 // If this is extracting an element from a shufflevector, figure out where
259 // it came from and extract from the appropriate input element instead.
260 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Eli Friedman303c81c2011-10-21 19:11:34 +0000261 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
Chris Lattnerec97a902010-01-05 05:36:20 +0000262 Value *Src;
263 unsigned LHSWidth =
Chris Lattner8326bd82012-01-26 00:42:34 +0000264 SVI->getOperand(0)->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000265
Bob Wilson11ee4562010-10-29 22:03:05 +0000266 if (SrcIdx < 0)
267 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
268 if (SrcIdx < (int)LHSWidth)
Chris Lattnerec97a902010-01-05 05:36:20 +0000269 Src = SVI->getOperand(0);
Bob Wilson11ee4562010-10-29 22:03:05 +0000270 else {
Chris Lattnerec97a902010-01-05 05:36:20 +0000271 SrcIdx -= LHSWidth;
272 Src = SVI->getOperand(1);
Chris Lattnerec97a902010-01-05 05:36:20 +0000273 }
Chris Lattner229907c2011-07-18 04:54:35 +0000274 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
Chris Lattnerec97a902010-01-05 05:36:20 +0000275 return ExtractElementInst::Create(Src,
Bob Wilson9d07f392010-10-29 22:03:07 +0000276 ConstantInt::get(Int32Ty,
Chris Lattnerec97a902010-01-05 05:36:20 +0000277 SrcIdx, false));
278 }
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000279 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
280 // Canonicalize extractelement(cast) -> cast(extractelement)
281 // bitcasts can change the number of vector elements and they cost nothing
Anat Shemer55703182013-04-18 19:56:44 +0000282 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
Anat Shemer10260a72013-04-22 20:51:10 +0000283 Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
284 EI.getIndexOperand());
285 Worklist.AddValue(EE);
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000286 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
287 }
Matt Arsenault243140f2013-11-04 20:36:06 +0000288 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
289 if (SI->hasOneUse()) {
290 // TODO: For a select on vectors, it might be useful to do this if it
291 // has multiple extractelement uses. For vector select, that seems to
292 // fight the vectorizer.
293
294 // If we are extracting an element from a vector select or a select on
295 // vectors, a select on the scalars extracted from the vector arguments.
296 Value *TrueVal = SI->getTrueValue();
297 Value *FalseVal = SI->getFalseValue();
298
299 Value *Cond = SI->getCondition();
300 if (Cond->getType()->isVectorTy()) {
301 Cond = Builder->CreateExtractElement(Cond,
302 EI.getIndexOperand(),
303 Cond->getName() + ".elt");
304 }
305
306 Value *V1Elem
307 = Builder->CreateExtractElement(TrueVal,
308 EI.getIndexOperand(),
309 TrueVal->getName() + ".elt");
310
311 Value *V2Elem
312 = Builder->CreateExtractElement(FalseVal,
313 EI.getIndexOperand(),
314 FalseVal->getName() + ".elt");
315 return SelectInst::Create(Cond,
316 V1Elem,
317 V2Elem,
318 SI->getName() + ".elt");
319 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000320 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000321 }
322 return 0;
323}
324
325/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000326/// elements from either LHS or RHS, return the shuffle mask and true.
Chris Lattnerec97a902010-01-05 05:36:20 +0000327/// Otherwise, return false.
328static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner0256be92012-01-27 03:08:05 +0000329 SmallVectorImpl<Constant*> &Mask) {
Tim Northoverfad27612014-03-07 10:24:44 +0000330 assert(LHS->getType() == RHS->getType() &&
Chris Lattnerec97a902010-01-05 05:36:20 +0000331 "Invalid CollectSingleShuffleElements");
Matt Arsenault8227b9f2013-09-06 00:37:24 +0000332 unsigned NumElts = V->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000333
Chris Lattnerec97a902010-01-05 05:36:20 +0000334 if (isa<UndefValue>(V)) {
335 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
336 return true;
337 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000338
Chris Lattnerec97a902010-01-05 05:36:20 +0000339 if (V == LHS) {
340 for (unsigned i = 0; i != NumElts; ++i)
341 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
342 return true;
343 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000344
Chris Lattnerec97a902010-01-05 05:36:20 +0000345 if (V == RHS) {
346 for (unsigned i = 0; i != NumElts; ++i)
347 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
348 i+NumElts));
349 return true;
350 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000351
Chris Lattnerec97a902010-01-05 05:36:20 +0000352 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
353 // If this is an insert of an extract from some other vector, include it.
354 Value *VecOp = IEI->getOperand(0);
355 Value *ScalarOp = IEI->getOperand(1);
356 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000357
Chris Lattnerec97a902010-01-05 05:36:20 +0000358 if (!isa<ConstantInt>(IdxOp))
359 return false;
360 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000361
Chris Lattnerec97a902010-01-05 05:36:20 +0000362 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
363 // Okay, we can handle this if the vector we are insertinting into is
364 // transitively ok.
365 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
366 // If so, update the mask to reflect the inserted undef.
367 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
368 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000369 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000370 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
Tim Northoverfad27612014-03-07 10:24:44 +0000371 if (isa<ConstantInt>(EI->getOperand(1))) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000372 unsigned ExtractedIdx =
373 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Tim Northoverfad27612014-03-07 10:24:44 +0000374 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000375
Chris Lattnerec97a902010-01-05 05:36:20 +0000376 // This must be extracting from either LHS or RHS.
377 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
378 // Okay, we can handle this if the vector we are insertinting into is
379 // transitively ok.
380 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
381 // If so, update the mask to reflect the inserted value.
382 if (EI->getOperand(0) == LHS) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000383 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000384 ConstantInt::get(Type::getInt32Ty(V->getContext()),
385 ExtractedIdx);
386 } else {
387 assert(EI->getOperand(0) == RHS);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000388 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000389 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000390 ExtractedIdx + NumLHSElts);
Chris Lattnerec97a902010-01-05 05:36:20 +0000391 }
392 return true;
393 }
394 }
395 }
396 }
397 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000398
Chris Lattnerec97a902010-01-05 05:36:20 +0000399 return false;
400}
401
Tim Northoverfad27612014-03-07 10:24:44 +0000402
403/// We are building a shuffle to create V, which is a sequence of insertelement,
404/// extractelement pairs. If PermittedRHS is set, then we must either use it or
405/// not rely on the second vector source. Return an std::pair containing the
406/// left and right vectors of the proposed shuffle (or 0), and set the Mask
407/// parameter as required.
408///
409/// Note: we intentionally don't try to fold earlier shuffles since they have
410/// often been chosen carefully to be efficiently implementable on the target.
411typedef std::pair<Value *, Value *> ShuffleOps;
412
413static ShuffleOps CollectShuffleElements(Value *V,
414 SmallVectorImpl<Constant *> &Mask,
415 Value *PermittedRHS) {
416 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
Chris Lattnerec97a902010-01-05 05:36:20 +0000417 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000418
Chris Lattnerec97a902010-01-05 05:36:20 +0000419 if (isa<UndefValue>(V)) {
420 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Tim Northoverfad27612014-03-07 10:24:44 +0000421 return std::make_pair(
422 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000423 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000424
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000425 if (isa<ConstantAggregateZero>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000426 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Tim Northoverfad27612014-03-07 10:24:44 +0000427 return std::make_pair(V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000428 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000429
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000430 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000431 // If this is an insert of an extract from some other vector, include it.
432 Value *VecOp = IEI->getOperand(0);
433 Value *ScalarOp = IEI->getOperand(1);
434 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000435
Chris Lattnerec97a902010-01-05 05:36:20 +0000436 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000437 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000438 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000439 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000440 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000441
Chris Lattnerec97a902010-01-05 05:36:20 +0000442 // Either the extracted from or inserted into vector must be RHSVec,
443 // otherwise we'd end up with a shuffle of three inputs.
Tim Northoverfad27612014-03-07 10:24:44 +0000444 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == 0) {
445 Value *RHS = EI->getOperand(0);
446 ShuffleOps LR = CollectShuffleElements(VecOp, Mask, RHS);
447 assert(LR.second == 0 || LR.second == RHS);
448
449 if (LR.first->getType() != RHS->getType()) {
450 // We tried our best, but we can't find anything compatible with RHS
451 // further up the chain. Return a trivial shuffle.
452 for (unsigned i = 0; i < NumElts; ++i)
453 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
454 return std::make_pair(V, nullptr);
455 }
456
457 unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000458 Mask[InsertedIdx % NumElts] =
Bob Wilson67a6f322010-10-29 22:20:45 +0000459 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000460 NumLHSElts+ExtractedIdx);
461 return std::make_pair(LR.first, RHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000462 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000463
Tim Northoverfad27612014-03-07 10:24:44 +0000464 if (VecOp == PermittedRHS) {
465 // We've gone as far as we can: anything on the other side of the
466 // extractelement will already have been converted into a shuffle.
467 unsigned NumLHSElts =
468 EI->getOperand(0)->getType()->getVectorNumElements();
469 for (unsigned i = 0; i != NumElts; ++i)
470 Mask.push_back(ConstantInt::get(
471 Type::getInt32Ty(V->getContext()),
472 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
473 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000474 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000475
Chris Lattnerec97a902010-01-05 05:36:20 +0000476 // If this insertelement is a chain that comes from exactly these two
477 // vectors, return the vector and the effective shuffle.
Tim Northoverfad27612014-03-07 10:24:44 +0000478 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
479 CollectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
480 Mask))
481 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000482 }
483 }
484 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000485
Chris Lattnerec97a902010-01-05 05:36:20 +0000486 // Otherwise, can't do anything fancy. Return an identity vector.
487 for (unsigned i = 0; i != NumElts; ++i)
488 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Tim Northoverfad27612014-03-07 10:24:44 +0000489 return std::make_pair(V, nullptr);
Chris Lattnerec97a902010-01-05 05:36:20 +0000490}
491
492Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
493 Value *VecOp = IE.getOperand(0);
494 Value *ScalarOp = IE.getOperand(1);
495 Value *IdxOp = IE.getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000496
Chris Lattnerec97a902010-01-05 05:36:20 +0000497 // Inserting an undef or into an undefined place, remove this.
498 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
499 ReplaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000500
501 // If the inserted element was extracted from some other vector, and if the
Chris Lattnerec97a902010-01-05 05:36:20 +0000502 // indexes are constant, try to turn this into a shufflevector operation.
503 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000504 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
505 unsigned NumInsertVectorElts = IE.getType()->getNumElements();
506 unsigned NumExtractVectorElts =
507 EI->getOperand(0)->getType()->getVectorNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +0000508 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000509 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000510 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000511
Tim Northoverfad27612014-03-07 10:24:44 +0000512 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
Chris Lattnerec97a902010-01-05 05:36:20 +0000513 return ReplaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000514
Tim Northoverfad27612014-03-07 10:24:44 +0000515 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
Chris Lattnerec97a902010-01-05 05:36:20 +0000516 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000517
Chris Lattnerec97a902010-01-05 05:36:20 +0000518 // If we are extracting a value from a vector, then inserting it right
519 // back into the same place, just use the input vector.
520 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000521 return ReplaceInstUsesWith(IE, VecOp);
522
Chris Lattnerec97a902010-01-05 05:36:20 +0000523 // If this insertelement isn't used by some other insertelement, turn it
524 // (and any insertelements it points to), into one big shuffle.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000525 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
Chris Lattner0256be92012-01-27 03:08:05 +0000526 SmallVector<Constant*, 16> Mask;
Tim Northoverfad27612014-03-07 10:24:44 +0000527 ShuffleOps LR = CollectShuffleElements(&IE, Mask, 0);
528
529 // The proposed shuffle may be trivial, in which case we shouldn't
530 // perform the combine.
531 if (LR.first != &IE && LR.second != &IE) {
532 // We now have a shuffle of LHS, RHS, Mask.
533 if (LR.second == 0) LR.second = UndefValue::get(LR.first->getType());
534 return new ShuffleVectorInst(LR.first, LR.second,
535 ConstantVector::get(Mask));
536 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000537 }
538 }
539 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000540
Chris Lattnerec97a902010-01-05 05:36:20 +0000541 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
542 APInt UndefElts(VWidth, 0);
543 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000544 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
545 if (V != &IE)
546 return ReplaceInstUsesWith(IE, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000547 return &IE;
Eli Friedmanef200db2011-02-19 22:42:40 +0000548 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000549
Chris Lattnerec97a902010-01-05 05:36:20 +0000550 return 0;
551}
552
Nick Lewyckya2b77202013-05-31 00:59:42 +0000553/// Return true if we can evaluate the specified expression tree if the vector
554/// elements were shuffled in a different order.
555static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
Nick Lewycky3f715e22013-06-01 20:51:31 +0000556 unsigned Depth = 5) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000557 // We can always reorder the elements of a constant.
558 if (isa<Constant>(V))
559 return true;
560
561 // We won't reorder vector arguments. No IPO here.
562 Instruction *I = dyn_cast<Instruction>(V);
563 if (!I) return false;
564
565 // Two users may expect different orders of the elements. Don't try it.
566 if (!I->hasOneUse())
567 return false;
568
569 if (Depth == 0) return false;
570
571 switch (I->getOpcode()) {
572 case Instruction::Add:
573 case Instruction::FAdd:
574 case Instruction::Sub:
575 case Instruction::FSub:
576 case Instruction::Mul:
577 case Instruction::FMul:
578 case Instruction::UDiv:
579 case Instruction::SDiv:
580 case Instruction::FDiv:
581 case Instruction::URem:
582 case Instruction::SRem:
583 case Instruction::FRem:
584 case Instruction::Shl:
585 case Instruction::LShr:
586 case Instruction::AShr:
587 case Instruction::And:
588 case Instruction::Or:
589 case Instruction::Xor:
590 case Instruction::ICmp:
591 case Instruction::FCmp:
592 case Instruction::Trunc:
593 case Instruction::ZExt:
594 case Instruction::SExt:
595 case Instruction::FPToUI:
596 case Instruction::FPToSI:
597 case Instruction::UIToFP:
598 case Instruction::SIToFP:
599 case Instruction::FPTrunc:
600 case Instruction::FPExt:
601 case Instruction::GetElementPtr: {
602 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
603 if (!CanEvaluateShuffled(I->getOperand(i), Mask, Depth-1))
604 return false;
605 }
606 return true;
607 }
608 case Instruction::InsertElement: {
609 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
610 if (!CI) return false;
611 int ElementNumber = CI->getLimitedValue();
612
613 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
614 // can't put an element into multiple indices.
615 bool SeenOnce = false;
616 for (int i = 0, e = Mask.size(); i != e; ++i) {
617 if (Mask[i] == ElementNumber) {
618 if (SeenOnce)
619 return false;
620 SeenOnce = true;
621 }
622 }
623 return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
624 }
625 }
626 return false;
627}
628
629/// Rebuild a new instruction just like 'I' but with the new operands given.
630/// In the event of type mismatch, the type of the operands is correct.
631static Value *BuildNew(Instruction *I, ArrayRef<Value*> NewOps) {
632 // We don't want to use the IRBuilder here because we want the replacement
633 // instructions to appear next to 'I', not the builder's insertion point.
634 switch (I->getOpcode()) {
635 case Instruction::Add:
636 case Instruction::FAdd:
637 case Instruction::Sub:
638 case Instruction::FSub:
639 case Instruction::Mul:
640 case Instruction::FMul:
641 case Instruction::UDiv:
642 case Instruction::SDiv:
643 case Instruction::FDiv:
644 case Instruction::URem:
645 case Instruction::SRem:
646 case Instruction::FRem:
647 case Instruction::Shl:
648 case Instruction::LShr:
649 case Instruction::AShr:
650 case Instruction::And:
651 case Instruction::Or:
652 case Instruction::Xor: {
653 BinaryOperator *BO = cast<BinaryOperator>(I);
654 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
655 BinaryOperator *New =
656 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
657 NewOps[0], NewOps[1], "", BO);
658 if (isa<OverflowingBinaryOperator>(BO)) {
659 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
660 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
661 }
662 if (isa<PossiblyExactOperator>(BO)) {
663 New->setIsExact(BO->isExact());
664 }
Owen Anderson48b842e2014-01-18 00:48:14 +0000665 if (isa<FPMathOperator>(BO))
666 New->copyFastMathFlags(I);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000667 return New;
668 }
669 case Instruction::ICmp:
670 assert(NewOps.size() == 2 && "icmp with #ops != 2");
671 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
672 NewOps[0], NewOps[1]);
673 case Instruction::FCmp:
674 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
675 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
676 NewOps[0], NewOps[1]);
677 case Instruction::Trunc:
678 case Instruction::ZExt:
679 case Instruction::SExt:
680 case Instruction::FPToUI:
681 case Instruction::FPToSI:
682 case Instruction::UIToFP:
683 case Instruction::SIToFP:
684 case Instruction::FPTrunc:
685 case Instruction::FPExt: {
686 // It's possible that the mask has a different number of elements from
687 // the original cast. We recompute the destination type to match the mask.
688 Type *DestTy =
689 VectorType::get(I->getType()->getScalarType(),
690 NewOps[0]->getType()->getVectorNumElements());
691 assert(NewOps.size() == 1 && "cast with #ops != 1");
692 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
693 "", I);
694 }
695 case Instruction::GetElementPtr: {
696 Value *Ptr = NewOps[0];
697 ArrayRef<Value*> Idx = NewOps.slice(1);
698 GetElementPtrInst *GEP = GetElementPtrInst::Create(Ptr, Idx, "", I);
699 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
700 return GEP;
701 }
702 }
703 llvm_unreachable("failed to rebuild vector instructions");
704}
705
706Value *
707InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
708 // Mask.size() does not need to be equal to the number of vector elements.
709
710 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
711 if (isa<UndefValue>(V)) {
712 return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
713 Mask.size()));
714 }
715 if (isa<ConstantAggregateZero>(V)) {
716 return ConstantAggregateZero::get(
717 VectorType::get(V->getType()->getScalarType(),
718 Mask.size()));
719 }
720 if (Constant *C = dyn_cast<Constant>(V)) {
721 SmallVector<Constant *, 16> MaskValues;
722 for (int i = 0, e = Mask.size(); i != e; ++i) {
723 if (Mask[i] == -1)
724 MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
725 else
726 MaskValues.push_back(Builder->getInt32(Mask[i]));
727 }
728 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
729 ConstantVector::get(MaskValues));
730 }
731
732 Instruction *I = cast<Instruction>(V);
733 switch (I->getOpcode()) {
734 case Instruction::Add:
735 case Instruction::FAdd:
736 case Instruction::Sub:
737 case Instruction::FSub:
738 case Instruction::Mul:
739 case Instruction::FMul:
740 case Instruction::UDiv:
741 case Instruction::SDiv:
742 case Instruction::FDiv:
743 case Instruction::URem:
744 case Instruction::SRem:
745 case Instruction::FRem:
746 case Instruction::Shl:
747 case Instruction::LShr:
748 case Instruction::AShr:
749 case Instruction::And:
750 case Instruction::Or:
751 case Instruction::Xor:
752 case Instruction::ICmp:
753 case Instruction::FCmp:
754 case Instruction::Trunc:
755 case Instruction::ZExt:
756 case Instruction::SExt:
757 case Instruction::FPToUI:
758 case Instruction::FPToSI:
759 case Instruction::UIToFP:
760 case Instruction::SIToFP:
761 case Instruction::FPTrunc:
762 case Instruction::FPExt:
763 case Instruction::Select:
764 case Instruction::GetElementPtr: {
765 SmallVector<Value*, 8> NewOps;
766 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
767 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
768 Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
769 NewOps.push_back(V);
770 NeedsRebuild |= (V != I->getOperand(i));
771 }
772 if (NeedsRebuild) {
773 return BuildNew(I, NewOps);
774 }
775 return I;
776 }
777 case Instruction::InsertElement: {
778 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
Nick Lewyckya2b77202013-05-31 00:59:42 +0000779
780 // The insertelement was inserting at Element. Figure out which element
781 // that becomes after shuffling. The answer is guaranteed to be unique
782 // by CanEvaluateShuffled.
Nick Lewycky3f715e22013-06-01 20:51:31 +0000783 bool Found = false;
Nick Lewyckya2b77202013-05-31 00:59:42 +0000784 int Index = 0;
Nick Lewycky3f715e22013-06-01 20:51:31 +0000785 for (int e = Mask.size(); Index != e; ++Index) {
786 if (Mask[Index] == Element) {
787 Found = true;
Nick Lewyckya2b77202013-05-31 00:59:42 +0000788 break;
Nick Lewycky3f715e22013-06-01 20:51:31 +0000789 }
790 }
Nick Lewyckya2b77202013-05-31 00:59:42 +0000791
Hao Liu26abebb2014-01-08 03:06:15 +0000792 // If element is not in Mask, no need to handle the operand 1 (element to
793 // be inserted). Just evaluate values in operand 0 according to Mask.
Nick Lewycky3f715e22013-06-01 20:51:31 +0000794 if (!Found)
Hao Liu26abebb2014-01-08 03:06:15 +0000795 return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
Joey Goulya3250f22013-07-12 23:08:06 +0000796
Nick Lewyckya2b77202013-05-31 00:59:42 +0000797 Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
798 return InsertElementInst::Create(V, I->getOperand(1),
799 Builder->getInt32(Index), "", I);
800 }
801 }
802 llvm_unreachable("failed to reorder elements of vector instruction!");
803}
Chris Lattnerec97a902010-01-05 05:36:20 +0000804
805Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
806 Value *LHS = SVI.getOperand(0);
807 Value *RHS = SVI.getOperand(1);
Chris Lattner8326bd82012-01-26 00:42:34 +0000808 SmallVector<int, 16> Mask = SVI.getShuffleMask();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000809
Chris Lattnerec97a902010-01-05 05:36:20 +0000810 bool MadeChange = false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000811
Chris Lattnerec97a902010-01-05 05:36:20 +0000812 // Undefined shuffle mask -> undefined value.
813 if (isa<UndefValue>(SVI.getOperand(2)))
814 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000815
Eric Christopher51edc7b2010-08-17 22:55:27 +0000816 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000817
Chris Lattnerec97a902010-01-05 05:36:20 +0000818 APInt UndefElts(VWidth, 0);
819 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000820 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
821 if (V != &SVI)
822 return ReplaceInstUsesWith(SVI, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000823 LHS = SVI.getOperand(0);
824 RHS = SVI.getOperand(1);
825 MadeChange = true;
826 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000827
Eli Friedmance818272011-10-21 19:06:29 +0000828 unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
829
Chris Lattnerec97a902010-01-05 05:36:20 +0000830 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
831 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
832 if (LHS == RHS || isa<UndefValue>(LHS)) {
Eric Christopher51edc7b2010-08-17 22:55:27 +0000833 if (isa<UndefValue>(LHS) && LHS == RHS) {
834 // shuffle(undef,undef,mask) -> undef.
Nick Lewyckya2b77202013-05-31 00:59:42 +0000835 Value *Result = (VWidth == LHSWidth)
Eli Friedmance818272011-10-21 19:06:29 +0000836 ? LHS : UndefValue::get(SVI.getType());
Nick Lewyckya2b77202013-05-31 00:59:42 +0000837 return ReplaceInstUsesWith(SVI, Result);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000838 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000839
Chris Lattnerec97a902010-01-05 05:36:20 +0000840 // Remap any references to RHS to use LHS.
Chris Lattner0256be92012-01-27 03:08:05 +0000841 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +0000842 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +0000843 if (Mask[i] < 0) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000844 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
Chris Lattner0256be92012-01-27 03:08:05 +0000845 continue;
846 }
847
848 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
849 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
850 Mask[i] = -1; // Turn into undef.
851 Elts.push_back(UndefValue::get(Type::getInt32Ty(SVI.getContext())));
852 } else {
853 Mask[i] = Mask[i] % e; // Force to LHS.
854 Elts.push_back(ConstantInt::get(Type::getInt32Ty(SVI.getContext()),
855 Mask[i]));
Chris Lattnerec97a902010-01-05 05:36:20 +0000856 }
857 }
858 SVI.setOperand(0, SVI.getOperand(1));
859 SVI.setOperand(1, UndefValue::get(RHS->getType()));
860 SVI.setOperand(2, ConstantVector::get(Elts));
861 LHS = SVI.getOperand(0);
862 RHS = SVI.getOperand(1);
863 MadeChange = true;
864 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000865
Eli Friedmance818272011-10-21 19:06:29 +0000866 if (VWidth == LHSWidth) {
867 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
868 bool isLHSID = true, isRHSID = true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000869
Eli Friedmance818272011-10-21 19:06:29 +0000870 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
871 if (Mask[i] < 0) continue; // Ignore undef values.
872 // Is this an identity shuffle of the LHS value?
873 isLHSID &= (Mask[i] == (int)i);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000874
Eli Friedmance818272011-10-21 19:06:29 +0000875 // Is this an identity shuffle of the RHS value?
876 isRHSID &= (Mask[i]-e == i);
877 }
878
879 // Eliminate identity shuffles.
880 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
881 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000882 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000883
Nick Lewycky688d6682013-06-03 23:15:20 +0000884 if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000885 Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
886 return ReplaceInstUsesWith(SVI, V);
887 }
888
Eric Christopher51edc7b2010-08-17 22:55:27 +0000889 // If the LHS is a shufflevector itself, see if we can combine it with this
Eli Friedmance818272011-10-21 19:06:29 +0000890 // one without producing an unusual shuffle.
891 // Cases that might be simplified:
892 // 1.
893 // x1=shuffle(v1,v2,mask1)
894 // x=shuffle(x1,undef,mask)
895 // ==>
896 // x=shuffle(v1,undef,newMask)
897 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
898 // 2.
899 // x1=shuffle(v1,undef,mask1)
900 // x=shuffle(x1,x2,mask)
901 // where v1.size() == mask1.size()
902 // ==>
903 // x=shuffle(v1,x2,newMask)
904 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
905 // 3.
906 // x2=shuffle(v2,undef,mask2)
907 // x=shuffle(x1,x2,mask)
908 // where v2.size() == mask2.size()
909 // ==>
910 // x=shuffle(x1,v2,newMask)
911 // newMask[i] = (mask[i] < x1.size())
912 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
913 // 4.
914 // x1=shuffle(v1,undef,mask1)
915 // x2=shuffle(v2,undef,mask2)
916 // x=shuffle(x1,x2,mask)
917 // where v1.size() == v2.size()
918 // ==>
919 // x=shuffle(v1,v2,newMask)
920 // newMask[i] = (mask[i] < x1.size())
921 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
922 //
923 // Here we are really conservative:
Eric Christopher51edc7b2010-08-17 22:55:27 +0000924 // we are absolutely afraid of producing a shuffle mask not in the input
925 // program, because the code gen may not be smart enough to turn a merged
926 // shuffle into two specific shuffles: it may produce worse code. As such,
Jim Grosbachd11584a2013-05-01 00:25:27 +0000927 // we only merge two shuffles if the result is either a splat or one of the
928 // input shuffle masks. In this case, merging the shuffles just removes
929 // one instruction, which we know is safe. This is good for things like
Eli Friedmance818272011-10-21 19:06:29 +0000930 // turning: (splat(splat)) -> splat, or
931 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
932 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
933 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
934 if (LHSShuffle)
935 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
936 LHSShuffle = NULL;
937 if (RHSShuffle)
938 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
939 RHSShuffle = NULL;
940 if (!LHSShuffle && !RHSShuffle)
941 return MadeChange ? &SVI : 0;
942
943 Value* LHSOp0 = NULL;
944 Value* LHSOp1 = NULL;
945 Value* RHSOp0 = NULL;
946 unsigned LHSOp0Width = 0;
947 unsigned RHSOp0Width = 0;
948 if (LHSShuffle) {
949 LHSOp0 = LHSShuffle->getOperand(0);
950 LHSOp1 = LHSShuffle->getOperand(1);
951 LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
952 }
953 if (RHSShuffle) {
954 RHSOp0 = RHSShuffle->getOperand(0);
955 RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
956 }
957 Value* newLHS = LHS;
958 Value* newRHS = RHS;
959 if (LHSShuffle) {
960 // case 1
Eric Christopher51edc7b2010-08-17 22:55:27 +0000961 if (isa<UndefValue>(RHS)) {
Eli Friedmance818272011-10-21 19:06:29 +0000962 newLHS = LHSOp0;
963 newRHS = LHSOp1;
964 }
965 // case 2 or 4
966 else if (LHSOp0Width == LHSWidth) {
967 newLHS = LHSOp0;
968 }
969 }
970 // case 3 or 4
971 if (RHSShuffle && RHSOp0Width == LHSWidth) {
972 newRHS = RHSOp0;
973 }
974 // case 4
975 if (LHSOp0 == RHSOp0) {
976 newLHS = LHSOp0;
977 newRHS = NULL;
978 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000979
Eli Friedmance818272011-10-21 19:06:29 +0000980 if (newLHS == LHS && newRHS == RHS)
981 return MadeChange ? &SVI : 0;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000982
Eli Friedmance818272011-10-21 19:06:29 +0000983 SmallVector<int, 16> LHSMask;
984 SmallVector<int, 16> RHSMask;
Chris Lattner8326bd82012-01-26 00:42:34 +0000985 if (newLHS != LHS)
986 LHSMask = LHSShuffle->getShuffleMask();
987 if (RHSShuffle && newRHS != RHS)
988 RHSMask = RHSShuffle->getShuffleMask();
989
Eli Friedmance818272011-10-21 19:06:29 +0000990 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
991 SmallVector<int, 16> newMask;
992 bool isSplat = true;
993 int SplatElt = -1;
994 // Create a new mask for the new ShuffleVectorInst so that the new
995 // ShuffleVectorInst is equivalent to the original one.
996 for (unsigned i = 0; i < VWidth; ++i) {
997 int eltMask;
Craig Topper45d9f4b2013-01-18 05:30:07 +0000998 if (Mask[i] < 0) {
Eli Friedmance818272011-10-21 19:06:29 +0000999 // This element is an undef value.
1000 eltMask = -1;
1001 } else if (Mask[i] < (int)LHSWidth) {
1002 // This element is from left hand side vector operand.
Craig Topper2ea22b02013-01-18 05:09:16 +00001003 //
Eli Friedmance818272011-10-21 19:06:29 +00001004 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1005 // new mask value for the element.
1006 if (newLHS != LHS) {
1007 eltMask = LHSMask[Mask[i]];
1008 // If the value selected is an undef value, explicitly specify it
1009 // with a -1 mask value.
1010 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1011 eltMask = -1;
Craig Topper2ea22b02013-01-18 05:09:16 +00001012 } else
Eli Friedmance818272011-10-21 19:06:29 +00001013 eltMask = Mask[i];
1014 } else {
1015 // This element is from right hand side vector operand
1016 //
1017 // If the value selected is an undef value, explicitly specify it
1018 // with a -1 mask value. (case 1)
1019 if (isa<UndefValue>(RHS))
1020 eltMask = -1;
1021 // If RHS is going to be replaced (case 3 or 4), calculate the
1022 // new mask value for the element.
1023 else if (newRHS != RHS) {
1024 eltMask = RHSMask[Mask[i]-LHSWidth];
1025 // If the value selected is an undef value, explicitly specify it
1026 // with a -1 mask value.
1027 if (eltMask >= (int)RHSOp0Width) {
1028 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1029 && "should have been check above");
1030 eltMask = -1;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001031 }
Craig Topper2ea22b02013-01-18 05:09:16 +00001032 } else
Eli Friedmance818272011-10-21 19:06:29 +00001033 eltMask = Mask[i]-LHSWidth;
1034
1035 // If LHS's width is changed, shift the mask value accordingly.
1036 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
Michael Gottesman02a11412012-10-16 21:29:38 +00001037 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1038 // If newRHS == newLHS, we want to remap any references from newRHS to
1039 // newLHS so that we can properly identify splats that may occur due to
Alp Tokercb402912014-01-24 17:20:08 +00001040 // obfuscation across the two vectors.
Michael Gottesman02a11412012-10-16 21:29:38 +00001041 if (eltMask >= 0 && newRHS != NULL && newLHS != newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001042 eltMask += newLHSWidth;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001043 }
Eli Friedmance818272011-10-21 19:06:29 +00001044
1045 // Check if this could still be a splat.
1046 if (eltMask >= 0) {
1047 if (SplatElt >= 0 && SplatElt != eltMask)
1048 isSplat = false;
1049 SplatElt = eltMask;
1050 }
1051
1052 newMask.push_back(eltMask);
1053 }
1054
1055 // If the result mask is equal to one of the original shuffle masks,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001056 // or is a splat, do the replacement.
1057 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
Eli Friedmance818272011-10-21 19:06:29 +00001058 SmallVector<Constant*, 16> Elts;
1059 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
1060 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1061 if (newMask[i] < 0) {
1062 Elts.push_back(UndefValue::get(Int32Ty));
1063 } else {
1064 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1065 }
1066 }
1067 if (newRHS == NULL)
1068 newRHS = UndefValue::get(newLHS->getType());
1069 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001070 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001071
Chris Lattnerec97a902010-01-05 05:36:20 +00001072 return MadeChange ? &SVI : 0;
1073}