blob: a76138756148098134aa21472afcfb89d865113c [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 Carrutha9174582015-01-22 05:25:13 +000015#include "InstCombineInternal.h"
JF Bastiend52c9902015-02-25 22:30:51 +000016#include "llvm/ADT/DenseMap.h"
David Majnemer599ca442015-07-13 01:15:53 +000017#include "llvm/Analysis/InstructionSimplify.h"
18#include "llvm/Analysis/VectorUtils.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000019#include "llvm/IR/PatternMatch.h"
Chris Lattnerec97a902010-01-05 05:36:20 +000020using namespace llvm;
Nadav Rotem7df85092013-01-15 23:43:14 +000021using namespace PatternMatch;
Chris Lattnerec97a902010-01-05 05:36:20 +000022
Chandler Carruth964daaa2014-04-22 02:55:47 +000023#define DEBUG_TYPE "instcombine"
24
Sanjay Patel6eccf482015-09-09 15:24:36 +000025/// Return true if the value is cheaper to scalarize than it is to leave as a
26/// vector operation. isConstant indicates whether we're extracting one known
27/// element. If false we're extracting a variable index.
Sanjay Patel431e1142015-11-17 17:24:08 +000028static bool cheapToScalarize(Value *V, bool isConstant) {
Chris Lattner8326bd82012-01-26 00:42:34 +000029 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +000030 if (isConstant) return true;
Chris Lattner8326bd82012-01-26 00:42:34 +000031
32 // If all elts are the same, we can extract it and use any of the values.
Benjamin Kramer09b0f882014-01-24 19:02:37 +000033 if (Constant *Op0 = C->getAggregateElement(0U)) {
34 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
35 ++i)
36 if (C->getAggregateElement(i) != Op0)
37 return false;
38 return true;
39 }
Chris Lattnerec97a902010-01-05 05:36:20 +000040 }
41 Instruction *I = dyn_cast<Instruction>(V);
42 if (!I) return false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000043
Chris Lattnerec97a902010-01-05 05:36:20 +000044 // Insert element gets simplified to the inserted element or is deleted if
45 // this is constant idx extract element and its a constant idx insertelt.
46 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
47 isa<ConstantInt>(I->getOperand(2)))
48 return true;
49 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
50 return true;
51 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
52 if (BO->hasOneUse() &&
Sanjay Patel431e1142015-11-17 17:24:08 +000053 (cheapToScalarize(BO->getOperand(0), isConstant) ||
54 cheapToScalarize(BO->getOperand(1), isConstant)))
Chris Lattnerec97a902010-01-05 05:36:20 +000055 return true;
56 if (CmpInst *CI = dyn_cast<CmpInst>(I))
57 if (CI->hasOneUse() &&
Sanjay Patel431e1142015-11-17 17:24:08 +000058 (cheapToScalarize(CI->getOperand(0), isConstant) ||
59 cheapToScalarize(CI->getOperand(1), isConstant)))
Chris Lattnerec97a902010-01-05 05:36:20 +000060 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000061
Chris Lattnerec97a902010-01-05 05:36:20 +000062 return false;
63}
64
Michael Kupersteina0c6ae02016-06-06 23:38:33 +000065// If we have a PHI node with a vector type that is only used to feed
Matt Arsenault38874732013-08-28 22:17:26 +000066// itself and be an operand of extractelement at a constant location,
67// try to replace the PHI of the vector type with a PHI of a scalar type.
Anat Shemer0c95efa2013-04-18 19:35:39 +000068Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
Michael Kupersteina0c6ae02016-06-06 23:38:33 +000069 SmallVector<Instruction *, 2> Extracts;
70 // The users we want the PHI to have are:
71 // 1) The EI ExtractElement (we already know this)
72 // 2) Possibly more ExtractElements with the same index.
73 // 3) Another operand, which will feed back into the PHI.
74 Instruction *PHIUser = nullptr;
75 for (auto U : PN->users()) {
76 if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
77 if (EI.getIndexOperand() == EU->getIndexOperand())
78 Extracts.push_back(EU);
79 else
80 return nullptr;
81 } else if (!PHIUser) {
82 PHIUser = cast<Instruction>(U);
83 } else {
84 return nullptr;
85 }
86 }
Anat Shemer0c95efa2013-04-18 19:35:39 +000087
Michael Kupersteina0c6ae02016-06-06 23:38:33 +000088 if (!PHIUser)
89 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +000090
91 // Verify that this PHI user has one use, which is the PHI itself,
92 // and that it is a binary operation which is cheap to scalarize.
93 // otherwise return NULL.
Chandler Carruthcdf47882014-03-09 03:16:01 +000094 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
Sanjay Patel431e1142015-11-17 17:24:08 +000095 !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true))
Craig Topperf40110f2014-04-25 05:29:35 +000096 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +000097
98 // Create a scalar PHI node that will replace the vector PHI node
99 // just before the current PHI node.
Joey Goulyb34294d2013-05-24 12:33:28 +0000100 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
101 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
Anat Shemer0c95efa2013-04-18 19:35:39 +0000102 // Scalarize each PHI operand.
Joey Goulyb34294d2013-05-24 12:33:28 +0000103 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
Anat Shemer0c95efa2013-04-18 19:35:39 +0000104 Value *PHIInVal = PN->getIncomingValue(i);
105 BasicBlock *inBB = PN->getIncomingBlock(i);
106 Value *Elt = EI.getIndexOperand();
107 // If the operand is the PHI induction variable:
108 if (PHIInVal == PHIUser) {
109 // Scalarize the binary operation. Its first operand is the
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000110 // scalar PHI, and the second operand is extracted from the other
Anat Shemer0c95efa2013-04-18 19:35:39 +0000111 // vector operand.
112 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
Joey Goulyb34294d2013-05-24 12:33:28 +0000113 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
Joey Gouly83699282013-05-24 12:29:54 +0000114 Value *Op = InsertNewInstWith(
115 ExtractElementInst::Create(B0->getOperand(opId), Elt,
116 B0->getOperand(opId)->getName() + ".Elt"),
117 *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000118 Value *newPHIUser = InsertNewInstWith(
Owen Anderson7ea02fc2016-03-01 19:35:52 +0000119 BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
120 scalarPHI, Op, B0), *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000121 scalarPHI->addIncoming(newPHIUser, inBB);
122 } else {
123 // Scalarize PHI input:
Joey Goulyb34294d2013-05-24 12:33:28 +0000124 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
Anat Shemer0c95efa2013-04-18 19:35:39 +0000125 // Insert the new instruction into the predecessor basic block.
126 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
127 BasicBlock::iterator InsertPos;
128 if (pos && !isa<PHINode>(pos)) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000129 InsertPos = ++pos->getIterator();
Anat Shemer0c95efa2013-04-18 19:35:39 +0000130 } else {
131 InsertPos = inBB->getFirstInsertionPt();
132 }
133
134 InsertNewInstWith(newEI, *InsertPos);
135
136 scalarPHI->addIncoming(newEI, inBB);
137 }
138 }
Michael Kupersteina0c6ae02016-06-06 23:38:33 +0000139
140 for (auto E : Extracts)
141 replaceInstUsesWith(*E, scalarPHI);
142
143 return &EI;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000144}
145
Chris Lattnerec97a902010-01-05 05:36:20 +0000146Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
David Majnemer599ca442015-07-13 01:15:53 +0000147 if (Value *V = SimplifyExtractElementInst(
148 EI.getVectorOperand(), EI.getIndexOperand(), DL, TLI, DT, AC))
Sanjay Patel4b198802016-02-01 22:23:39 +0000149 return replaceInstUsesWith(EI, V);
David Majnemer599ca442015-07-13 01:15:53 +0000150
Chris Lattner8326bd82012-01-26 00:42:34 +0000151 // If vector val is constant with all elements the same, replace EI with
152 // that element. We handle a known element # below.
153 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
Sanjay Patel431e1142015-11-17 17:24:08 +0000154 if (cheapToScalarize(C, false))
Sanjay Patel4b198802016-02-01 22:23:39 +0000155 return replaceInstUsesWith(EI, C->getAggregateElement(0U));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000156
Chris Lattnerec97a902010-01-05 05:36:20 +0000157 // If extracting a specified index from the vector, see if we can recursively
158 // find a previously computed scalar that was inserted into the vector.
159 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
160 unsigned IndexVal = IdxC->getZExtValue();
161 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000162
David Majnemer599ca442015-07-13 01:15:53 +0000163 // InstSimplify handles cases where the index is invalid.
164 assert(IndexVal < VectorWidth);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000165
Chris Lattnerec97a902010-01-05 05:36:20 +0000166 // This instruction only demands the single element from the input vector.
167 // If the input vector has a single use, simplify it based on this use
168 // property.
169 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
170 APInt UndefElts(VectorWidth, 0);
Chris Lattnerb22423c2010-02-08 23:56:03 +0000171 APInt DemandedMask(VectorWidth, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +0000172 DemandedMask.setBit(IndexVal);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000173 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
174 UndefElts)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000175 EI.setOperand(0, V);
176 return &EI;
177 }
178 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000179
Sanjay Patelb67076c2015-11-29 22:09:34 +0000180 // If this extractelement is directly using a bitcast from a vector of
Chris Lattnerec97a902010-01-05 05:36:20 +0000181 // the same number of elements, see if we can find the source element from
182 // it. In this case, we will end up needing to bitcast the scalars.
183 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
Chris Lattner8326bd82012-01-26 00:42:34 +0000184 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
Chris Lattnerec97a902010-01-05 05:36:20 +0000185 if (VT->getNumElements() == VectorWidth)
David Majnemer599ca442015-07-13 01:15:53 +0000186 if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal))
Chris Lattnerec97a902010-01-05 05:36:20 +0000187 return new BitCastInst(Elt, EI.getType());
188 }
Anat Shemer0c95efa2013-04-18 19:35:39 +0000189
190 // If there's a vector PHI feeding a scalar use through this extractelement
191 // instruction, try to scalarize the PHI.
192 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
Nick Lewycky881e9d62013-05-04 01:08:15 +0000193 Instruction *scalarPHI = scalarizePHI(EI, PN);
194 if (scalarPHI)
Joey Goulyb34294d2013-05-24 12:33:28 +0000195 return scalarPHI;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000196 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000197 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000198
Chris Lattnerec97a902010-01-05 05:36:20 +0000199 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
200 // Push extractelement into predecessor operation if legal and
Sanjay Patelb67076c2015-11-29 22:09:34 +0000201 // profitable to do so.
Chris Lattnerec97a902010-01-05 05:36:20 +0000202 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
203 if (I->hasOneUse() &&
Sanjay Patel431e1142015-11-17 17:24:08 +0000204 cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000205 Value *newEI0 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000206 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
207 EI.getName()+".lhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000208 Value *newEI1 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000209 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
210 EI.getName()+".rhs");
Owen Anderson7ea02fc2016-03-01 19:35:52 +0000211 return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(),
212 newEI0, newEI1, BO);
Chris Lattnerec97a902010-01-05 05:36:20 +0000213 }
214 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
215 // Extracting the inserted element?
216 if (IE->getOperand(2) == EI.getOperand(1))
Sanjay Patel4b198802016-02-01 22:23:39 +0000217 return replaceInstUsesWith(EI, IE->getOperand(1));
Chris Lattnerec97a902010-01-05 05:36:20 +0000218 // If the inserted and extracted elements are constants, they must not
219 // be the same value, extract from the pre-inserted value instead.
220 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
221 Worklist.AddValue(EI.getOperand(0));
222 EI.setOperand(0, IE->getOperand(0));
223 return &EI;
224 }
225 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
226 // If this is extracting an element from a shufflevector, figure out where
227 // it came from and extract from the appropriate input element instead.
228 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Eli Friedman303c81c2011-10-21 19:11:34 +0000229 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
Chris Lattnerec97a902010-01-05 05:36:20 +0000230 Value *Src;
231 unsigned LHSWidth =
Chris Lattner8326bd82012-01-26 00:42:34 +0000232 SVI->getOperand(0)->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000233
Bob Wilson11ee4562010-10-29 22:03:05 +0000234 if (SrcIdx < 0)
Sanjay Patel4b198802016-02-01 22:23:39 +0000235 return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Bob Wilson11ee4562010-10-29 22:03:05 +0000236 if (SrcIdx < (int)LHSWidth)
Chris Lattnerec97a902010-01-05 05:36:20 +0000237 Src = SVI->getOperand(0);
Bob Wilson11ee4562010-10-29 22:03:05 +0000238 else {
Chris Lattnerec97a902010-01-05 05:36:20 +0000239 SrcIdx -= LHSWidth;
240 Src = SVI->getOperand(1);
Chris Lattnerec97a902010-01-05 05:36:20 +0000241 }
Chris Lattner229907c2011-07-18 04:54:35 +0000242 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
Chris Lattnerec97a902010-01-05 05:36:20 +0000243 return ExtractElementInst::Create(Src,
Bob Wilson9d07f392010-10-29 22:03:07 +0000244 ConstantInt::get(Int32Ty,
Chris Lattnerec97a902010-01-05 05:36:20 +0000245 SrcIdx, false));
246 }
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000247 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Sanjay Patelb67076c2015-11-29 22:09:34 +0000248 // Canonicalize extractelement(cast) -> cast(extractelement).
249 // Bitcasts can change the number of vector elements, and they cost
250 // nothing.
Anat Shemer55703182013-04-18 19:56:44 +0000251 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
Anat Shemer10260a72013-04-22 20:51:10 +0000252 Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
253 EI.getIndexOperand());
254 Worklist.AddValue(EE);
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000255 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
256 }
Matt Arsenault243140f2013-11-04 20:36:06 +0000257 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
258 if (SI->hasOneUse()) {
259 // TODO: For a select on vectors, it might be useful to do this if it
260 // has multiple extractelement uses. For vector select, that seems to
261 // fight the vectorizer.
262
263 // If we are extracting an element from a vector select or a select on
Sanjay Patelb67076c2015-11-29 22:09:34 +0000264 // vectors, create a select on the scalars extracted from the vector
265 // arguments.
Matt Arsenault243140f2013-11-04 20:36:06 +0000266 Value *TrueVal = SI->getTrueValue();
267 Value *FalseVal = SI->getFalseValue();
268
269 Value *Cond = SI->getCondition();
270 if (Cond->getType()->isVectorTy()) {
271 Cond = Builder->CreateExtractElement(Cond,
272 EI.getIndexOperand(),
273 Cond->getName() + ".elt");
274 }
275
276 Value *V1Elem
277 = Builder->CreateExtractElement(TrueVal,
278 EI.getIndexOperand(),
279 TrueVal->getName() + ".elt");
280
281 Value *V2Elem
282 = Builder->CreateExtractElement(FalseVal,
283 EI.getIndexOperand(),
284 FalseVal->getName() + ".elt");
285 return SelectInst::Create(Cond,
286 V1Elem,
287 V2Elem,
288 SI->getName() + ".elt");
289 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000290 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000291 }
Craig Topperf40110f2014-04-25 05:29:35 +0000292 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000293}
294
Sanjay Patel6eccf482015-09-09 15:24:36 +0000295/// If V is a shuffle of values that ONLY returns elements from either LHS or
296/// RHS, return the shuffle mask and true. Otherwise, return false.
Sanjay Patel431e1142015-11-17 17:24:08 +0000297static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner0256be92012-01-27 03:08:05 +0000298 SmallVectorImpl<Constant*> &Mask) {
Tim Northoverfad27612014-03-07 10:24:44 +0000299 assert(LHS->getType() == RHS->getType() &&
Chris Lattnerec97a902010-01-05 05:36:20 +0000300 "Invalid CollectSingleShuffleElements");
Matt Arsenault8227b9f2013-09-06 00:37:24 +0000301 unsigned NumElts = V->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000302
Chris Lattnerec97a902010-01-05 05:36:20 +0000303 if (isa<UndefValue>(V)) {
304 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
305 return true;
306 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000307
Chris Lattnerec97a902010-01-05 05:36:20 +0000308 if (V == LHS) {
309 for (unsigned i = 0; i != NumElts; ++i)
310 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
311 return true;
312 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000313
Chris Lattnerec97a902010-01-05 05:36:20 +0000314 if (V == RHS) {
315 for (unsigned i = 0; i != NumElts; ++i)
316 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
317 i+NumElts));
318 return true;
319 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000320
Chris Lattnerec97a902010-01-05 05:36:20 +0000321 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
322 // If this is an insert of an extract from some other vector, include it.
323 Value *VecOp = IEI->getOperand(0);
324 Value *ScalarOp = IEI->getOperand(1);
325 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000326
Chris Lattnerec97a902010-01-05 05:36:20 +0000327 if (!isa<ConstantInt>(IdxOp))
328 return false;
329 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000330
Chris Lattnerec97a902010-01-05 05:36:20 +0000331 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000332 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000333 // transitively ok.
Sanjay Patel431e1142015-11-17 17:24:08 +0000334 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000335 // If so, update the mask to reflect the inserted undef.
336 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
337 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000338 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000339 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
Tim Northoverfad27612014-03-07 10:24:44 +0000340 if (isa<ConstantInt>(EI->getOperand(1))) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000341 unsigned ExtractedIdx =
342 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Tim Northoverfad27612014-03-07 10:24:44 +0000343 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000344
Chris Lattnerec97a902010-01-05 05:36:20 +0000345 // This must be extracting from either LHS or RHS.
346 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000347 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000348 // transitively ok.
Sanjay Patel431e1142015-11-17 17:24:08 +0000349 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000350 // If so, update the mask to reflect the inserted value.
351 if (EI->getOperand(0) == LHS) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000352 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000353 ConstantInt::get(Type::getInt32Ty(V->getContext()),
354 ExtractedIdx);
355 } else {
356 assert(EI->getOperand(0) == RHS);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000357 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000358 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000359 ExtractedIdx + NumLHSElts);
Chris Lattnerec97a902010-01-05 05:36:20 +0000360 }
361 return true;
362 }
363 }
364 }
365 }
366 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000367
Chris Lattnerec97a902010-01-05 05:36:20 +0000368 return false;
369}
370
Sanjay Patelae945e72015-12-24 21:17:56 +0000371/// If we have insertion into a vector that is wider than the vector that we
372/// are extracting from, try to widen the source vector to allow a single
373/// shufflevector to replace one or more insert/extract pairs.
374static void replaceExtractElements(InsertElementInst *InsElt,
375 ExtractElementInst *ExtElt,
376 InstCombiner &IC) {
377 VectorType *InsVecType = InsElt->getType();
378 VectorType *ExtVecType = ExtElt->getVectorOperandType();
379 unsigned NumInsElts = InsVecType->getVectorNumElements();
380 unsigned NumExtElts = ExtVecType->getVectorNumElements();
381
382 // The inserted-to vector must be wider than the extracted-from vector.
383 if (InsVecType->getElementType() != ExtVecType->getElementType() ||
384 NumExtElts >= NumInsElts)
385 return;
386
387 // Create a shuffle mask to widen the extended-from vector using undefined
388 // values. The mask selects all of the values of the original vector followed
389 // by as many undefined values as needed to create a vector of the same length
390 // as the inserted-to vector.
391 SmallVector<Constant *, 16> ExtendMask;
392 IntegerType *IntType = Type::getInt32Ty(InsElt->getContext());
393 for (unsigned i = 0; i < NumExtElts; ++i)
394 ExtendMask.push_back(ConstantInt::get(IntType, i));
395 for (unsigned i = NumExtElts; i < NumInsElts; ++i)
396 ExtendMask.push_back(UndefValue::get(IntType));
397
398 Value *ExtVecOp = ExtElt->getVectorOperand();
Sanjay Patel66fff732016-01-29 20:21:02 +0000399 auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
400 BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
401 ? ExtVecOpInst->getParent()
402 : ExtElt->getParent();
403
404 // TODO: This restriction matches the basic block check below when creating
405 // new extractelement instructions. If that limitation is removed, this one
406 // could also be removed. But for now, we just bail out to ensure that we
407 // will replace the extractelement instruction that is feeding our
408 // insertelement instruction. This allows the insertelement to then be
409 // replaced by a shufflevector. If the insertelement is not replaced, we can
410 // induce infinite looping because there's an optimization for extractelement
411 // that will delete our widening shuffle. This would trigger another attempt
412 // here to create that shuffle, and we spin forever.
413 if (InsertionBlock != InsElt->getParent())
414 return;
415
Sanjay Patelae945e72015-12-24 21:17:56 +0000416 auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
417 ConstantVector::get(ExtendMask));
418
Sanjay Patela1c53472016-01-05 19:09:47 +0000419 // Insert the new shuffle after the vector operand of the extract is defined
Sanjay Pateld72a4582016-01-08 01:39:16 +0000420 // (as long as it's not a PHI) or at the start of the basic block of the
421 // extract, so any subsequent extracts in the same basic block can use it.
422 // TODO: Insert before the earliest ExtractElementInst that is replaced.
Sanjay Pateld72a4582016-01-08 01:39:16 +0000423 if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
Sanjay Patela1c53472016-01-05 19:09:47 +0000424 WideVec->insertAfter(ExtVecOpInst);
Sanjay Pateld72a4582016-01-08 01:39:16 +0000425 else
Sanjay Patela1c53472016-01-05 19:09:47 +0000426 IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
Sanjay Patela1c53472016-01-05 19:09:47 +0000427
428 // Replace extracts from the original narrow vector with extracts from the new
429 // wide vector.
Sanjay Patelae945e72015-12-24 21:17:56 +0000430 for (User *U : ExtVecOp->users()) {
Sanjay Patela1c53472016-01-05 19:09:47 +0000431 ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
Sanjay Pateld72a4582016-01-08 01:39:16 +0000432 if (!OldExt || OldExt->getParent() != WideVec->getParent())
Sanjay Patela1c53472016-01-05 19:09:47 +0000433 continue;
434 auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
435 NewExt->insertAfter(WideVec);
Sanjay Patel4b198802016-02-01 22:23:39 +0000436 IC.replaceInstUsesWith(*OldExt, NewExt);
Sanjay Patelae945e72015-12-24 21:17:56 +0000437 }
438}
Tim Northoverfad27612014-03-07 10:24:44 +0000439
440/// We are building a shuffle to create V, which is a sequence of insertelement,
441/// extractelement pairs. If PermittedRHS is set, then we must either use it or
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000442/// not rely on the second vector source. Return a std::pair containing the
Tim Northoverfad27612014-03-07 10:24:44 +0000443/// left and right vectors of the proposed shuffle (or 0), and set the Mask
444/// parameter as required.
445///
446/// Note: we intentionally don't try to fold earlier shuffles since they have
447/// often been chosen carefully to be efficiently implementable on the target.
448typedef std::pair<Value *, Value *> ShuffleOps;
449
Sanjay Patel431e1142015-11-17 17:24:08 +0000450static ShuffleOps collectShuffleElements(Value *V,
Tim Northoverfad27612014-03-07 10:24:44 +0000451 SmallVectorImpl<Constant *> &Mask,
Sanjay Patelae945e72015-12-24 21:17:56 +0000452 Value *PermittedRHS,
453 InstCombiner &IC) {
Tim Northoverfad27612014-03-07 10:24:44 +0000454 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
Chris Lattnerec97a902010-01-05 05:36:20 +0000455 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000456
Chris Lattnerec97a902010-01-05 05:36:20 +0000457 if (isa<UndefValue>(V)) {
458 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Tim Northoverfad27612014-03-07 10:24:44 +0000459 return std::make_pair(
460 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000461 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000462
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000463 if (isa<ConstantAggregateZero>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000464 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Tim Northoverfad27612014-03-07 10:24:44 +0000465 return std::make_pair(V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000466 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000467
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000468 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000469 // If this is an insert of an extract from some other vector, include it.
470 Value *VecOp = IEI->getOperand(0);
471 Value *ScalarOp = IEI->getOperand(1);
472 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000473
Chris Lattnerec97a902010-01-05 05:36:20 +0000474 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000475 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000476 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000477 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000478 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000479
Chris Lattnerec97a902010-01-05 05:36:20 +0000480 // Either the extracted from or inserted into vector must be RHSVec,
481 // otherwise we'd end up with a shuffle of three inputs.
Craig Topperf40110f2014-04-25 05:29:35 +0000482 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
Tim Northoverfad27612014-03-07 10:24:44 +0000483 Value *RHS = EI->getOperand(0);
Sanjay Patelae945e72015-12-24 21:17:56 +0000484 ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
Craig Toppere73658d2014-04-28 04:05:08 +0000485 assert(LR.second == nullptr || LR.second == RHS);
Tim Northoverfad27612014-03-07 10:24:44 +0000486
487 if (LR.first->getType() != RHS->getType()) {
Sanjay Patelae945e72015-12-24 21:17:56 +0000488 // Although we are giving up for now, see if we can create extracts
489 // that match the inserts for another round of combining.
490 replaceExtractElements(IEI, EI, IC);
491
Tim Northoverfad27612014-03-07 10:24:44 +0000492 // We tried our best, but we can't find anything compatible with RHS
493 // further up the chain. Return a trivial shuffle.
494 for (unsigned i = 0; i < NumElts; ++i)
495 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
496 return std::make_pair(V, nullptr);
497 }
498
499 unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000500 Mask[InsertedIdx % NumElts] =
Bob Wilson67a6f322010-10-29 22:20:45 +0000501 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000502 NumLHSElts+ExtractedIdx);
503 return std::make_pair(LR.first, RHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000504 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000505
Tim Northoverfad27612014-03-07 10:24:44 +0000506 if (VecOp == PermittedRHS) {
507 // We've gone as far as we can: anything on the other side of the
508 // extractelement will already have been converted into a shuffle.
509 unsigned NumLHSElts =
510 EI->getOperand(0)->getType()->getVectorNumElements();
511 for (unsigned i = 0; i != NumElts; ++i)
512 Mask.push_back(ConstantInt::get(
513 Type::getInt32Ty(V->getContext()),
514 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
515 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000516 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000517
Chris Lattnerec97a902010-01-05 05:36:20 +0000518 // If this insertelement is a chain that comes from exactly these two
519 // vectors, return the vector and the effective shuffle.
Tim Northoverfad27612014-03-07 10:24:44 +0000520 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
Sanjay Patel431e1142015-11-17 17:24:08 +0000521 collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
Tim Northoverfad27612014-03-07 10:24:44 +0000522 Mask))
523 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000524 }
525 }
526 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000527
Sanjay Patelb67076c2015-11-29 22:09:34 +0000528 // Otherwise, we can't do anything fancy. Return an identity vector.
Chris Lattnerec97a902010-01-05 05:36:20 +0000529 for (unsigned i = 0; i != NumElts; ++i)
530 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Tim Northoverfad27612014-03-07 10:24:44 +0000531 return std::make_pair(V, nullptr);
Chris Lattnerec97a902010-01-05 05:36:20 +0000532}
533
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000534/// Try to find redundant insertvalue instructions, like the following ones:
535/// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
536/// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
537/// Here the second instruction inserts values at the same indices, as the
538/// first one, making the first one redundant.
539/// It should be transformed to:
540/// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
541Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
542 bool IsRedundant = false;
543 ArrayRef<unsigned int> FirstIndices = I.getIndices();
544
545 // If there is a chain of insertvalue instructions (each of them except the
546 // last one has only one use and it's another insertvalue insn from this
547 // chain), check if any of the 'children' uses the same indices as the first
548 // instruction. In this case, the first one is redundant.
549 Value *V = &I;
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000550 unsigned Depth = 0;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000551 while (V->hasOneUse() && Depth < 10) {
552 User *U = V->user_back();
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000553 auto UserInsInst = dyn_cast<InsertValueInst>(U);
554 if (!UserInsInst || U->getOperand(0) != V)
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000555 break;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000556 if (UserInsInst->getIndices() == FirstIndices) {
557 IsRedundant = true;
558 break;
559 }
560 V = UserInsInst;
561 Depth++;
562 }
563
564 if (IsRedundant)
Sanjay Patel4b198802016-02-01 22:23:39 +0000565 return replaceInstUsesWith(I, I.getOperand(0));
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000566 return nullptr;
567}
568
Chris Lattnerec97a902010-01-05 05:36:20 +0000569Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
570 Value *VecOp = IE.getOperand(0);
571 Value *ScalarOp = IE.getOperand(1);
572 Value *IdxOp = IE.getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000573
Chris Lattnerec97a902010-01-05 05:36:20 +0000574 // Inserting an undef or into an undefined place, remove this.
575 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
Sanjay Patel4b198802016-02-01 22:23:39 +0000576 replaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000577
578 // If the inserted element was extracted from some other vector, and if the
Chris Lattnerec97a902010-01-05 05:36:20 +0000579 // indexes are constant, try to turn this into a shufflevector operation.
580 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000581 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
582 unsigned NumInsertVectorElts = IE.getType()->getNumElements();
583 unsigned NumExtractVectorElts =
584 EI->getOperand(0)->getType()->getVectorNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +0000585 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000586 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000587 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000588
Tim Northoverfad27612014-03-07 10:24:44 +0000589 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
Sanjay Patel4b198802016-02-01 22:23:39 +0000590 return replaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000591
Tim Northoverfad27612014-03-07 10:24:44 +0000592 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
Sanjay Patel4b198802016-02-01 22:23:39 +0000593 return replaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000594
Chris Lattnerec97a902010-01-05 05:36:20 +0000595 // If we are extracting a value from a vector, then inserting it right
596 // back into the same place, just use the input vector.
597 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
Sanjay Patel4b198802016-02-01 22:23:39 +0000598 return replaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000599
Chris Lattnerec97a902010-01-05 05:36:20 +0000600 // If this insertelement isn't used by some other insertelement, turn it
601 // (and any insertelements it points to), into one big shuffle.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000602 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
Chris Lattner0256be92012-01-27 03:08:05 +0000603 SmallVector<Constant*, 16> Mask;
Sanjay Patelae945e72015-12-24 21:17:56 +0000604 ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
Tim Northoverfad27612014-03-07 10:24:44 +0000605
606 // The proposed shuffle may be trivial, in which case we shouldn't
607 // perform the combine.
608 if (LR.first != &IE && LR.second != &IE) {
609 // We now have a shuffle of LHS, RHS, Mask.
Craig Topperf40110f2014-04-25 05:29:35 +0000610 if (LR.second == nullptr)
611 LR.second = UndefValue::get(LR.first->getType());
Tim Northoverfad27612014-03-07 10:24:44 +0000612 return new ShuffleVectorInst(LR.first, LR.second,
613 ConstantVector::get(Mask));
614 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000615 }
616 }
617 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000618
Chris Lattnerec97a902010-01-05 05:36:20 +0000619 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
620 APInt UndefElts(VWidth, 0);
621 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000622 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
623 if (V != &IE)
Sanjay Patel4b198802016-02-01 22:23:39 +0000624 return replaceInstUsesWith(IE, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000625 return &IE;
Eli Friedmanef200db2011-02-19 22:42:40 +0000626 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000627
Craig Topperf40110f2014-04-25 05:29:35 +0000628 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000629}
630
Nick Lewyckya2b77202013-05-31 00:59:42 +0000631/// Return true if we can evaluate the specified expression tree if the vector
632/// elements were shuffled in a different order.
633static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
Nick Lewycky3f715e22013-06-01 20:51:31 +0000634 unsigned Depth = 5) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000635 // We can always reorder the elements of a constant.
636 if (isa<Constant>(V))
637 return true;
638
639 // We won't reorder vector arguments. No IPO here.
640 Instruction *I = dyn_cast<Instruction>(V);
641 if (!I) return false;
642
643 // Two users may expect different orders of the elements. Don't try it.
644 if (!I->hasOneUse())
645 return false;
646
647 if (Depth == 0) return false;
648
649 switch (I->getOpcode()) {
650 case Instruction::Add:
651 case Instruction::FAdd:
652 case Instruction::Sub:
653 case Instruction::FSub:
654 case Instruction::Mul:
655 case Instruction::FMul:
656 case Instruction::UDiv:
657 case Instruction::SDiv:
658 case Instruction::FDiv:
659 case Instruction::URem:
660 case Instruction::SRem:
661 case Instruction::FRem:
662 case Instruction::Shl:
663 case Instruction::LShr:
664 case Instruction::AShr:
665 case Instruction::And:
666 case Instruction::Or:
667 case Instruction::Xor:
668 case Instruction::ICmp:
669 case Instruction::FCmp:
670 case Instruction::Trunc:
671 case Instruction::ZExt:
672 case Instruction::SExt:
673 case Instruction::FPToUI:
674 case Instruction::FPToSI:
675 case Instruction::UIToFP:
676 case Instruction::SIToFP:
677 case Instruction::FPTrunc:
678 case Instruction::FPExt:
679 case Instruction::GetElementPtr: {
Sanjay Patel4e28753142015-11-16 22:16:52 +0000680 for (Value *Operand : I->operands()) {
681 if (!CanEvaluateShuffled(Operand, Mask, Depth-1))
Nick Lewyckya2b77202013-05-31 00:59:42 +0000682 return false;
683 }
684 return true;
685 }
686 case Instruction::InsertElement: {
687 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
688 if (!CI) return false;
689 int ElementNumber = CI->getLimitedValue();
690
691 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
692 // can't put an element into multiple indices.
693 bool SeenOnce = false;
694 for (int i = 0, e = Mask.size(); i != e; ++i) {
695 if (Mask[i] == ElementNumber) {
696 if (SeenOnce)
697 return false;
698 SeenOnce = true;
699 }
700 }
701 return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
702 }
703 }
704 return false;
705}
706
707/// Rebuild a new instruction just like 'I' but with the new operands given.
708/// In the event of type mismatch, the type of the operands is correct.
Sanjay Patel431e1142015-11-17 17:24:08 +0000709static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000710 // We don't want to use the IRBuilder here because we want the replacement
711 // instructions to appear next to 'I', not the builder's insertion point.
712 switch (I->getOpcode()) {
713 case Instruction::Add:
714 case Instruction::FAdd:
715 case Instruction::Sub:
716 case Instruction::FSub:
717 case Instruction::Mul:
718 case Instruction::FMul:
719 case Instruction::UDiv:
720 case Instruction::SDiv:
721 case Instruction::FDiv:
722 case Instruction::URem:
723 case Instruction::SRem:
724 case Instruction::FRem:
725 case Instruction::Shl:
726 case Instruction::LShr:
727 case Instruction::AShr:
728 case Instruction::And:
729 case Instruction::Or:
730 case Instruction::Xor: {
731 BinaryOperator *BO = cast<BinaryOperator>(I);
732 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
733 BinaryOperator *New =
734 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
735 NewOps[0], NewOps[1], "", BO);
736 if (isa<OverflowingBinaryOperator>(BO)) {
737 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
738 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
739 }
740 if (isa<PossiblyExactOperator>(BO)) {
741 New->setIsExact(BO->isExact());
742 }
Owen Anderson48b842e2014-01-18 00:48:14 +0000743 if (isa<FPMathOperator>(BO))
744 New->copyFastMathFlags(I);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000745 return New;
746 }
747 case Instruction::ICmp:
748 assert(NewOps.size() == 2 && "icmp with #ops != 2");
749 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
750 NewOps[0], NewOps[1]);
751 case Instruction::FCmp:
752 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
753 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
754 NewOps[0], NewOps[1]);
755 case Instruction::Trunc:
756 case Instruction::ZExt:
757 case Instruction::SExt:
758 case Instruction::FPToUI:
759 case Instruction::FPToSI:
760 case Instruction::UIToFP:
761 case Instruction::SIToFP:
762 case Instruction::FPTrunc:
763 case Instruction::FPExt: {
764 // It's possible that the mask has a different number of elements from
765 // the original cast. We recompute the destination type to match the mask.
766 Type *DestTy =
767 VectorType::get(I->getType()->getScalarType(),
768 NewOps[0]->getType()->getVectorNumElements());
769 assert(NewOps.size() == 1 && "cast with #ops != 1");
770 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
771 "", I);
772 }
773 case Instruction::GetElementPtr: {
774 Value *Ptr = NewOps[0];
775 ArrayRef<Value*> Idx = NewOps.slice(1);
David Blaikie22319eb2015-03-14 19:24:04 +0000776 GetElementPtrInst *GEP = GetElementPtrInst::Create(
777 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000778 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
779 return GEP;
780 }
781 }
782 llvm_unreachable("failed to rebuild vector instructions");
783}
784
785Value *
786InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
787 // Mask.size() does not need to be equal to the number of vector elements.
788
789 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
790 if (isa<UndefValue>(V)) {
791 return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
792 Mask.size()));
793 }
794 if (isa<ConstantAggregateZero>(V)) {
795 return ConstantAggregateZero::get(
796 VectorType::get(V->getType()->getScalarType(),
797 Mask.size()));
798 }
799 if (Constant *C = dyn_cast<Constant>(V)) {
800 SmallVector<Constant *, 16> MaskValues;
801 for (int i = 0, e = Mask.size(); i != e; ++i) {
802 if (Mask[i] == -1)
803 MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
804 else
805 MaskValues.push_back(Builder->getInt32(Mask[i]));
806 }
807 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
808 ConstantVector::get(MaskValues));
809 }
810
811 Instruction *I = cast<Instruction>(V);
812 switch (I->getOpcode()) {
813 case Instruction::Add:
814 case Instruction::FAdd:
815 case Instruction::Sub:
816 case Instruction::FSub:
817 case Instruction::Mul:
818 case Instruction::FMul:
819 case Instruction::UDiv:
820 case Instruction::SDiv:
821 case Instruction::FDiv:
822 case Instruction::URem:
823 case Instruction::SRem:
824 case Instruction::FRem:
825 case Instruction::Shl:
826 case Instruction::LShr:
827 case Instruction::AShr:
828 case Instruction::And:
829 case Instruction::Or:
830 case Instruction::Xor:
831 case Instruction::ICmp:
832 case Instruction::FCmp:
833 case Instruction::Trunc:
834 case Instruction::ZExt:
835 case Instruction::SExt:
836 case Instruction::FPToUI:
837 case Instruction::FPToSI:
838 case Instruction::UIToFP:
839 case Instruction::SIToFP:
840 case Instruction::FPTrunc:
841 case Instruction::FPExt:
842 case Instruction::Select:
843 case Instruction::GetElementPtr: {
844 SmallVector<Value*, 8> NewOps;
845 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
846 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
847 Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
848 NewOps.push_back(V);
849 NeedsRebuild |= (V != I->getOperand(i));
850 }
851 if (NeedsRebuild) {
Sanjay Patel431e1142015-11-17 17:24:08 +0000852 return buildNew(I, NewOps);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000853 }
854 return I;
855 }
856 case Instruction::InsertElement: {
857 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
Nick Lewyckya2b77202013-05-31 00:59:42 +0000858
859 // The insertelement was inserting at Element. Figure out which element
860 // that becomes after shuffling. The answer is guaranteed to be unique
861 // by CanEvaluateShuffled.
Nick Lewycky3f715e22013-06-01 20:51:31 +0000862 bool Found = false;
Nick Lewyckya2b77202013-05-31 00:59:42 +0000863 int Index = 0;
Nick Lewycky3f715e22013-06-01 20:51:31 +0000864 for (int e = Mask.size(); Index != e; ++Index) {
865 if (Mask[Index] == Element) {
866 Found = true;
Nick Lewyckya2b77202013-05-31 00:59:42 +0000867 break;
Nick Lewycky3f715e22013-06-01 20:51:31 +0000868 }
869 }
Nick Lewyckya2b77202013-05-31 00:59:42 +0000870
Hao Liu26abebb2014-01-08 03:06:15 +0000871 // If element is not in Mask, no need to handle the operand 1 (element to
872 // be inserted). Just evaluate values in operand 0 according to Mask.
Nick Lewycky3f715e22013-06-01 20:51:31 +0000873 if (!Found)
Hao Liu26abebb2014-01-08 03:06:15 +0000874 return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
Joey Goulya3250f22013-07-12 23:08:06 +0000875
Nick Lewyckya2b77202013-05-31 00:59:42 +0000876 Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
877 return InsertElementInst::Create(V, I->getOperand(1),
878 Builder->getInt32(Index), "", I);
879 }
880 }
881 llvm_unreachable("failed to reorder elements of vector instruction!");
882}
Chris Lattnerec97a902010-01-05 05:36:20 +0000883
Sanjay Patel431e1142015-11-17 17:24:08 +0000884static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask,
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000885 bool &isLHSID, bool &isRHSID) {
886 isLHSID = isRHSID = true;
887
888 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
889 if (Mask[i] < 0) continue; // Ignore undef values.
890 // Is this an identity shuffle of the LHS value?
891 isLHSID &= (Mask[i] == (int)i);
892
893 // Is this an identity shuffle of the RHS value?
894 isRHSID &= (Mask[i]-e == i);
895 }
896}
897
JF Bastiend52c9902015-02-25 22:30:51 +0000898// Returns true if the shuffle is extracting a contiguous range of values from
899// LHS, for example:
900// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
901// Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
902// Shuffles to: |EE|FF|GG|HH|
903// +--+--+--+--+
904static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
905 SmallVector<int, 16> &Mask) {
906 unsigned LHSElems =
907 cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements();
908 unsigned MaskElems = Mask.size();
909 unsigned BegIdx = Mask.front();
910 unsigned EndIdx = Mask.back();
911 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
912 return false;
913 for (unsigned I = 0; I != MaskElems; ++I)
914 if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
915 return false;
916 return true;
917}
918
Chris Lattnerec97a902010-01-05 05:36:20 +0000919Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
920 Value *LHS = SVI.getOperand(0);
921 Value *RHS = SVI.getOperand(1);
Chris Lattner8326bd82012-01-26 00:42:34 +0000922 SmallVector<int, 16> Mask = SVI.getShuffleMask();
JF Bastiend52c9902015-02-25 22:30:51 +0000923 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000924
Chris Lattnerec97a902010-01-05 05:36:20 +0000925 bool MadeChange = false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000926
Chris Lattnerec97a902010-01-05 05:36:20 +0000927 // Undefined shuffle mask -> undefined value.
928 if (isa<UndefValue>(SVI.getOperand(2)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000929 return replaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000930
Eric Christopher51edc7b2010-08-17 22:55:27 +0000931 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000932
Chris Lattnerec97a902010-01-05 05:36:20 +0000933 APInt UndefElts(VWidth, 0);
934 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000935 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
936 if (V != &SVI)
Sanjay Patel4b198802016-02-01 22:23:39 +0000937 return replaceInstUsesWith(SVI, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000938 LHS = SVI.getOperand(0);
939 RHS = SVI.getOperand(1);
940 MadeChange = true;
941 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000942
Eli Friedmance818272011-10-21 19:06:29 +0000943 unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
944
Chris Lattnerec97a902010-01-05 05:36:20 +0000945 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
946 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
947 if (LHS == RHS || isa<UndefValue>(LHS)) {
Eric Christopher51edc7b2010-08-17 22:55:27 +0000948 if (isa<UndefValue>(LHS) && LHS == RHS) {
949 // shuffle(undef,undef,mask) -> undef.
Nick Lewyckya2b77202013-05-31 00:59:42 +0000950 Value *Result = (VWidth == LHSWidth)
Eli Friedmance818272011-10-21 19:06:29 +0000951 ? LHS : UndefValue::get(SVI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +0000952 return replaceInstUsesWith(SVI, Result);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000953 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000954
Chris Lattnerec97a902010-01-05 05:36:20 +0000955 // Remap any references to RHS to use LHS.
Chris Lattner0256be92012-01-27 03:08:05 +0000956 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +0000957 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +0000958 if (Mask[i] < 0) {
JF Bastiend52c9902015-02-25 22:30:51 +0000959 Elts.push_back(UndefValue::get(Int32Ty));
Chris Lattner0256be92012-01-27 03:08:05 +0000960 continue;
961 }
962
963 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
964 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
965 Mask[i] = -1; // Turn into undef.
JF Bastiend52c9902015-02-25 22:30:51 +0000966 Elts.push_back(UndefValue::get(Int32Ty));
Chris Lattner0256be92012-01-27 03:08:05 +0000967 } else {
968 Mask[i] = Mask[i] % e; // Force to LHS.
JF Bastiend52c9902015-02-25 22:30:51 +0000969 Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
Chris Lattnerec97a902010-01-05 05:36:20 +0000970 }
971 }
972 SVI.setOperand(0, SVI.getOperand(1));
973 SVI.setOperand(1, UndefValue::get(RHS->getType()));
974 SVI.setOperand(2, ConstantVector::get(Elts));
975 LHS = SVI.getOperand(0);
976 RHS = SVI.getOperand(1);
977 MadeChange = true;
978 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000979
Eli Friedmance818272011-10-21 19:06:29 +0000980 if (VWidth == LHSWidth) {
981 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000982 bool isLHSID, isRHSID;
Sanjay Patel431e1142015-11-17 17:24:08 +0000983 recognizeIdentityMask(Mask, isLHSID, isRHSID);
Eli Friedmance818272011-10-21 19:06:29 +0000984
985 // Eliminate identity shuffles.
Sanjay Patel4b198802016-02-01 22:23:39 +0000986 if (isLHSID) return replaceInstUsesWith(SVI, LHS);
987 if (isRHSID) return replaceInstUsesWith(SVI, RHS);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000988 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000989
Nick Lewycky688d6682013-06-03 23:15:20 +0000990 if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000991 Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
Sanjay Patel4b198802016-02-01 22:23:39 +0000992 return replaceInstUsesWith(SVI, V);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000993 }
994
JF Bastiend52c9902015-02-25 22:30:51 +0000995 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
996 // a non-vector type. We can instead bitcast the original vector followed by
997 // an extract of the desired element:
998 //
999 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
1000 // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
1001 // %1 = bitcast <4 x i8> %sroa to i32
1002 // Becomes:
1003 // %bc = bitcast <16 x i8> %in to <4 x i32>
1004 // %ext = extractelement <4 x i32> %bc, i32 0
1005 //
1006 // If the shuffle is extracting a contiguous range of values from the input
1007 // vector then each use which is a bitcast of the extracted size can be
1008 // replaced. This will work if the vector types are compatible, and the begin
1009 // index is aligned to a value in the casted vector type. If the begin index
1010 // isn't aligned then we can shuffle the original vector (keeping the same
1011 // vector type) before extracting.
1012 //
1013 // This code will bail out if the target type is fundamentally incompatible
1014 // with vectors of the source type.
1015 //
1016 // Example of <16 x i8>, target type i32:
1017 // Index range [4,8): v-----------v Will work.
1018 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1019 // <16 x i8>: | | | | | | | | | | | | | | | | |
1020 // <4 x i32>: | | | | |
1021 // +-----------+-----------+-----------+-----------+
1022 // Index range [6,10): ^-----------^ Needs an extra shuffle.
1023 // Target type i40: ^--------------^ Won't work, bail.
1024 if (isShuffleExtractingFromLHS(SVI, Mask)) {
1025 Value *V = LHS;
1026 unsigned MaskElems = Mask.size();
1027 unsigned BegIdx = Mask.front();
1028 VectorType *SrcTy = cast<VectorType>(V->getType());
1029 unsigned VecBitWidth = SrcTy->getBitWidth();
David Majnemer98cfe2b2015-04-03 20:18:40 +00001030 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
JF Bastiend52c9902015-02-25 22:30:51 +00001031 assert(SrcElemBitWidth && "vector elements must have a bitwidth");
1032 unsigned SrcNumElems = SrcTy->getNumElements();
1033 SmallVector<BitCastInst *, 8> BCs;
1034 DenseMap<Type *, Value *> NewBCs;
1035 for (User *U : SVI.users())
1036 if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
1037 if (!BC->use_empty())
1038 // Only visit bitcasts that weren't previously handled.
1039 BCs.push_back(BC);
1040 for (BitCastInst *BC : BCs) {
1041 Type *TgtTy = BC->getDestTy();
David Majnemer98cfe2b2015-04-03 20:18:40 +00001042 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
JF Bastiend52c9902015-02-25 22:30:51 +00001043 if (!TgtElemBitWidth)
1044 continue;
1045 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1046 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1047 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1048 if (!VecBitWidthsEqual)
1049 continue;
1050 if (!VectorType::isValidElementType(TgtTy))
1051 continue;
1052 VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1053 if (!BegIsAligned) {
1054 // Shuffle the input so [0,NumElements) contains the output, and
1055 // [NumElems,SrcNumElems) is undef.
1056 SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1057 UndefValue::get(Int32Ty));
1058 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1059 ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
1060 V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()),
1061 ConstantVector::get(ShuffleMask),
1062 SVI.getName() + ".extract");
1063 BegIdx = 0;
1064 }
1065 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1066 assert(SrcElemsPerTgtElem);
1067 BegIdx /= SrcElemsPerTgtElem;
1068 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1069 auto *NewBC =
1070 BCAlreadyExists
1071 ? NewBCs[CastSrcTy]
1072 : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
1073 if (!BCAlreadyExists)
1074 NewBCs[CastSrcTy] = NewBC;
1075 auto *Ext = Builder->CreateExtractElement(
1076 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1077 // The shufflevector isn't being replaced: the bitcast that used it
1078 // is. InstCombine will visit the newly-created instructions.
Sanjay Patel4b198802016-02-01 22:23:39 +00001079 replaceInstUsesWith(*BC, Ext);
JF Bastiend52c9902015-02-25 22:30:51 +00001080 MadeChange = true;
1081 }
1082 }
1083
Eric Christopher51edc7b2010-08-17 22:55:27 +00001084 // If the LHS is a shufflevector itself, see if we can combine it with this
Eli Friedmance818272011-10-21 19:06:29 +00001085 // one without producing an unusual shuffle.
1086 // Cases that might be simplified:
1087 // 1.
1088 // x1=shuffle(v1,v2,mask1)
1089 // x=shuffle(x1,undef,mask)
1090 // ==>
1091 // x=shuffle(v1,undef,newMask)
1092 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1093 // 2.
1094 // x1=shuffle(v1,undef,mask1)
1095 // x=shuffle(x1,x2,mask)
1096 // where v1.size() == mask1.size()
1097 // ==>
1098 // x=shuffle(v1,x2,newMask)
1099 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1100 // 3.
1101 // x2=shuffle(v2,undef,mask2)
1102 // x=shuffle(x1,x2,mask)
1103 // where v2.size() == mask2.size()
1104 // ==>
1105 // x=shuffle(x1,v2,newMask)
1106 // newMask[i] = (mask[i] < x1.size())
1107 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1108 // 4.
1109 // x1=shuffle(v1,undef,mask1)
1110 // x2=shuffle(v2,undef,mask2)
1111 // x=shuffle(x1,x2,mask)
1112 // where v1.size() == v2.size()
1113 // ==>
1114 // x=shuffle(v1,v2,newMask)
1115 // newMask[i] = (mask[i] < x1.size())
1116 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1117 //
1118 // Here we are really conservative:
Eric Christopher51edc7b2010-08-17 22:55:27 +00001119 // we are absolutely afraid of producing a shuffle mask not in the input
1120 // program, because the code gen may not be smart enough to turn a merged
1121 // shuffle into two specific shuffles: it may produce worse code. As such,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001122 // we only merge two shuffles if the result is either a splat or one of the
1123 // input shuffle masks. In this case, merging the shuffles just removes
1124 // one instruction, which we know is safe. This is good for things like
Eli Friedmance818272011-10-21 19:06:29 +00001125 // turning: (splat(splat)) -> splat, or
1126 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1127 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1128 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1129 if (LHSShuffle)
1130 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
Craig Topperf40110f2014-04-25 05:29:35 +00001131 LHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001132 if (RHSShuffle)
1133 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +00001134 RHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001135 if (!LHSShuffle && !RHSShuffle)
Craig Topperf40110f2014-04-25 05:29:35 +00001136 return MadeChange ? &SVI : nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001137
Craig Topperf40110f2014-04-25 05:29:35 +00001138 Value* LHSOp0 = nullptr;
1139 Value* LHSOp1 = nullptr;
1140 Value* RHSOp0 = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001141 unsigned LHSOp0Width = 0;
1142 unsigned RHSOp0Width = 0;
1143 if (LHSShuffle) {
1144 LHSOp0 = LHSShuffle->getOperand(0);
1145 LHSOp1 = LHSShuffle->getOperand(1);
1146 LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
1147 }
1148 if (RHSShuffle) {
1149 RHSOp0 = RHSShuffle->getOperand(0);
1150 RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
1151 }
1152 Value* newLHS = LHS;
1153 Value* newRHS = RHS;
1154 if (LHSShuffle) {
1155 // case 1
Eric Christopher51edc7b2010-08-17 22:55:27 +00001156 if (isa<UndefValue>(RHS)) {
Eli Friedmance818272011-10-21 19:06:29 +00001157 newLHS = LHSOp0;
1158 newRHS = LHSOp1;
1159 }
1160 // case 2 or 4
1161 else if (LHSOp0Width == LHSWidth) {
1162 newLHS = LHSOp0;
1163 }
1164 }
1165 // case 3 or 4
1166 if (RHSShuffle && RHSOp0Width == LHSWidth) {
1167 newRHS = RHSOp0;
1168 }
1169 // case 4
1170 if (LHSOp0 == RHSOp0) {
1171 newLHS = LHSOp0;
Craig Topperf40110f2014-04-25 05:29:35 +00001172 newRHS = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001173 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001174
Eli Friedmance818272011-10-21 19:06:29 +00001175 if (newLHS == LHS && newRHS == RHS)
Craig Topperf40110f2014-04-25 05:29:35 +00001176 return MadeChange ? &SVI : nullptr;
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001177
Eli Friedmance818272011-10-21 19:06:29 +00001178 SmallVector<int, 16> LHSMask;
1179 SmallVector<int, 16> RHSMask;
Chris Lattner8326bd82012-01-26 00:42:34 +00001180 if (newLHS != LHS)
1181 LHSMask = LHSShuffle->getShuffleMask();
1182 if (RHSShuffle && newRHS != RHS)
1183 RHSMask = RHSShuffle->getShuffleMask();
1184
Eli Friedmance818272011-10-21 19:06:29 +00001185 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1186 SmallVector<int, 16> newMask;
1187 bool isSplat = true;
1188 int SplatElt = -1;
1189 // Create a new mask for the new ShuffleVectorInst so that the new
1190 // ShuffleVectorInst is equivalent to the original one.
1191 for (unsigned i = 0; i < VWidth; ++i) {
1192 int eltMask;
Craig Topper45d9f4b2013-01-18 05:30:07 +00001193 if (Mask[i] < 0) {
Eli Friedmance818272011-10-21 19:06:29 +00001194 // This element is an undef value.
1195 eltMask = -1;
1196 } else if (Mask[i] < (int)LHSWidth) {
1197 // This element is from left hand side vector operand.
Craig Topper2ea22b02013-01-18 05:09:16 +00001198 //
Eli Friedmance818272011-10-21 19:06:29 +00001199 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1200 // new mask value for the element.
1201 if (newLHS != LHS) {
1202 eltMask = LHSMask[Mask[i]];
1203 // If the value selected is an undef value, explicitly specify it
1204 // with a -1 mask value.
1205 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1206 eltMask = -1;
Craig Topper2ea22b02013-01-18 05:09:16 +00001207 } else
Eli Friedmance818272011-10-21 19:06:29 +00001208 eltMask = Mask[i];
1209 } else {
1210 // This element is from right hand side vector operand
1211 //
1212 // If the value selected is an undef value, explicitly specify it
1213 // with a -1 mask value. (case 1)
1214 if (isa<UndefValue>(RHS))
1215 eltMask = -1;
1216 // If RHS is going to be replaced (case 3 or 4), calculate the
1217 // new mask value for the element.
1218 else if (newRHS != RHS) {
1219 eltMask = RHSMask[Mask[i]-LHSWidth];
1220 // If the value selected is an undef value, explicitly specify it
1221 // with a -1 mask value.
1222 if (eltMask >= (int)RHSOp0Width) {
1223 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1224 && "should have been check above");
1225 eltMask = -1;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001226 }
Craig Topper2ea22b02013-01-18 05:09:16 +00001227 } else
Eli Friedmance818272011-10-21 19:06:29 +00001228 eltMask = Mask[i]-LHSWidth;
1229
1230 // If LHS's width is changed, shift the mask value accordingly.
1231 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
Michael Gottesman02a11412012-10-16 21:29:38 +00001232 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1233 // If newRHS == newLHS, we want to remap any references from newRHS to
1234 // newLHS so that we can properly identify splats that may occur due to
Alp Tokercb402912014-01-24 17:20:08 +00001235 // obfuscation across the two vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001236 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001237 eltMask += newLHSWidth;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001238 }
Eli Friedmance818272011-10-21 19:06:29 +00001239
1240 // Check if this could still be a splat.
1241 if (eltMask >= 0) {
1242 if (SplatElt >= 0 && SplatElt != eltMask)
1243 isSplat = false;
1244 SplatElt = eltMask;
1245 }
1246
1247 newMask.push_back(eltMask);
1248 }
1249
1250 // If the result mask is equal to one of the original shuffle masks,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001251 // or is a splat, do the replacement.
1252 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
Eli Friedmance818272011-10-21 19:06:29 +00001253 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +00001254 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1255 if (newMask[i] < 0) {
1256 Elts.push_back(UndefValue::get(Int32Ty));
1257 } else {
1258 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1259 }
1260 }
Craig Topperf40110f2014-04-25 05:29:35 +00001261 if (!newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001262 newRHS = UndefValue::get(newLHS->getType());
1263 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001264 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001265
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001266 // If the result mask is an identity, replace uses of this instruction with
1267 // corresponding argument.
Serge Pavlovb575ee82014-05-13 06:07:21 +00001268 bool isLHSID, isRHSID;
Sanjay Patel431e1142015-11-17 17:24:08 +00001269 recognizeIdentityMask(newMask, isLHSID, isRHSID);
Sanjay Patel4b198802016-02-01 22:23:39 +00001270 if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS);
1271 if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001272
Craig Topperf40110f2014-04-25 05:29:35 +00001273 return MadeChange ? &SVI : nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +00001274}