blob: 1896d48d1f3c1d4f28f1faa458a782e7e64283c6 [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.
Chris Lattnerec97a902010-01-05 05:36:20 +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() &&
53 (CheapToScalarize(BO->getOperand(0), isConstant) ||
54 CheapToScalarize(BO->getOperand(1), isConstant)))
55 return true;
56 if (CmpInst *CI = dyn_cast<CmpInst>(I))
57 if (CI->hasOneUse() &&
58 (CheapToScalarize(CI->getOperand(0), isConstant) ||
59 CheapToScalarize(CI->getOperand(1), isConstant)))
60 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000061
Chris Lattnerec97a902010-01-05 05:36:20 +000062 return false;
63}
64
Anat Shemer0c95efa2013-04-18 19:35:39 +000065// If we have a PHI node with a vector type that has only 2 uses: 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) {
69 // Verify that the PHI node has exactly 2 uses. Otherwise return NULL.
70 if (!PN->hasNUses(2))
Craig Topperf40110f2014-04-25 05:29:35 +000071 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +000072
73 // If so, it's known at this point that one operand is PHI and the other is
74 // an extractelement node. Find the PHI user that is not the extractelement
75 // node.
Chandler Carruthcdf47882014-03-09 03:16:01 +000076 auto iu = PN->user_begin();
Anat Shemer0c95efa2013-04-18 19:35:39 +000077 Instruction *PHIUser = dyn_cast<Instruction>(*iu);
78 if (PHIUser == cast<Instruction>(&EI))
79 PHIUser = cast<Instruction>(*(++iu));
80
81 // Verify that this PHI user has one use, which is the PHI itself,
82 // and that it is a binary operation which is cheap to scalarize.
83 // otherwise return NULL.
Chandler Carruthcdf47882014-03-09 03:16:01 +000084 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
Joey Goulyb34294d2013-05-24 12:33:28 +000085 !(isa<BinaryOperator>(PHIUser)) || !CheapToScalarize(PHIUser, true))
Craig Topperf40110f2014-04-25 05:29:35 +000086 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +000087
88 // Create a scalar PHI node that will replace the vector PHI node
89 // just before the current PHI node.
Joey Goulyb34294d2013-05-24 12:33:28 +000090 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
91 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
Anat Shemer0c95efa2013-04-18 19:35:39 +000092 // Scalarize each PHI operand.
Joey Goulyb34294d2013-05-24 12:33:28 +000093 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
Anat Shemer0c95efa2013-04-18 19:35:39 +000094 Value *PHIInVal = PN->getIncomingValue(i);
95 BasicBlock *inBB = PN->getIncomingBlock(i);
96 Value *Elt = EI.getIndexOperand();
97 // If the operand is the PHI induction variable:
98 if (PHIInVal == PHIUser) {
99 // Scalarize the binary operation. Its first operand is the
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000100 // scalar PHI, and the second operand is extracted from the other
Anat Shemer0c95efa2013-04-18 19:35:39 +0000101 // vector operand.
102 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
Joey Goulyb34294d2013-05-24 12:33:28 +0000103 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
Joey Gouly83699282013-05-24 12:29:54 +0000104 Value *Op = InsertNewInstWith(
105 ExtractElementInst::Create(B0->getOperand(opId), Elt,
106 B0->getOperand(opId)->getName() + ".Elt"),
107 *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000108 Value *newPHIUser = InsertNewInstWith(
Joey Goulyb34294d2013-05-24 12:33:28 +0000109 BinaryOperator::Create(B0->getOpcode(), scalarPHI, Op), *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000110 scalarPHI->addIncoming(newPHIUser, inBB);
111 } else {
112 // Scalarize PHI input:
Joey Goulyb34294d2013-05-24 12:33:28 +0000113 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
Anat Shemer0c95efa2013-04-18 19:35:39 +0000114 // Insert the new instruction into the predecessor basic block.
115 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
116 BasicBlock::iterator InsertPos;
117 if (pos && !isa<PHINode>(pos)) {
118 InsertPos = pos;
119 ++InsertPos;
120 } else {
121 InsertPos = inBB->getFirstInsertionPt();
122 }
123
124 InsertNewInstWith(newEI, *InsertPos);
125
126 scalarPHI->addIncoming(newEI, inBB);
127 }
128 }
129 return ReplaceInstUsesWith(EI, scalarPHI);
130}
131
Chris Lattnerec97a902010-01-05 05:36:20 +0000132Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
David Majnemer599ca442015-07-13 01:15:53 +0000133 if (Value *V = SimplifyExtractElementInst(
134 EI.getVectorOperand(), EI.getIndexOperand(), DL, TLI, DT, AC))
135 return ReplaceInstUsesWith(EI, V);
136
Chris Lattner8326bd82012-01-26 00:42:34 +0000137 // If vector val is constant with all elements the same, replace EI with
138 // that element. We handle a known element # below.
139 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
140 if (CheapToScalarize(C, false))
141 return ReplaceInstUsesWith(EI, C->getAggregateElement(0U));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000142
Chris Lattnerec97a902010-01-05 05:36:20 +0000143 // If extracting a specified index from the vector, see if we can recursively
144 // find a previously computed scalar that was inserted into the vector.
145 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
146 unsigned IndexVal = IdxC->getZExtValue();
147 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000148
David Majnemer599ca442015-07-13 01:15:53 +0000149 // InstSimplify handles cases where the index is invalid.
150 assert(IndexVal < VectorWidth);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000151
Chris Lattnerec97a902010-01-05 05:36:20 +0000152 // This instruction only demands the single element from the input vector.
153 // If the input vector has a single use, simplify it based on this use
154 // property.
155 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
156 APInt UndefElts(VectorWidth, 0);
Chris Lattnerb22423c2010-02-08 23:56:03 +0000157 APInt DemandedMask(VectorWidth, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +0000158 DemandedMask.setBit(IndexVal);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000159 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
160 UndefElts)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000161 EI.setOperand(0, V);
162 return &EI;
163 }
164 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000165
Chris Lattnerec97a902010-01-05 05:36:20 +0000166 // If the this extractelement is directly using a bitcast from a vector of
167 // the same number of elements, see if we can find the source element from
168 // it. In this case, we will end up needing to bitcast the scalars.
169 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
Chris Lattner8326bd82012-01-26 00:42:34 +0000170 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
Chris Lattnerec97a902010-01-05 05:36:20 +0000171 if (VT->getNumElements() == VectorWidth)
David Majnemer599ca442015-07-13 01:15:53 +0000172 if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal))
Chris Lattnerec97a902010-01-05 05:36:20 +0000173 return new BitCastInst(Elt, EI.getType());
174 }
Anat Shemer0c95efa2013-04-18 19:35:39 +0000175
176 // If there's a vector PHI feeding a scalar use through this extractelement
177 // instruction, try to scalarize the PHI.
178 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
Nick Lewycky881e9d62013-05-04 01:08:15 +0000179 Instruction *scalarPHI = scalarizePHI(EI, PN);
180 if (scalarPHI)
Joey Goulyb34294d2013-05-24 12:33:28 +0000181 return scalarPHI;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000182 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000183 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000184
Chris Lattnerec97a902010-01-05 05:36:20 +0000185 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
186 // Push extractelement into predecessor operation if legal and
187 // profitable to do so
188 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
189 if (I->hasOneUse() &&
190 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
191 Value *newEI0 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000192 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
193 EI.getName()+".lhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000194 Value *newEI1 =
Bob Wilson67a6f322010-10-29 22:20:45 +0000195 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
196 EI.getName()+".rhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000197 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
198 }
199 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
200 // Extracting the inserted element?
201 if (IE->getOperand(2) == EI.getOperand(1))
202 return ReplaceInstUsesWith(EI, IE->getOperand(1));
203 // If the inserted and extracted elements are constants, they must not
204 // be the same value, extract from the pre-inserted value instead.
205 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
206 Worklist.AddValue(EI.getOperand(0));
207 EI.setOperand(0, IE->getOperand(0));
208 return &EI;
209 }
210 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
211 // If this is extracting an element from a shufflevector, figure out where
212 // it came from and extract from the appropriate input element instead.
213 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Eli Friedman303c81c2011-10-21 19:11:34 +0000214 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
Chris Lattnerec97a902010-01-05 05:36:20 +0000215 Value *Src;
216 unsigned LHSWidth =
Chris Lattner8326bd82012-01-26 00:42:34 +0000217 SVI->getOperand(0)->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000218
Bob Wilson11ee4562010-10-29 22:03:05 +0000219 if (SrcIdx < 0)
220 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
221 if (SrcIdx < (int)LHSWidth)
Chris Lattnerec97a902010-01-05 05:36:20 +0000222 Src = SVI->getOperand(0);
Bob Wilson11ee4562010-10-29 22:03:05 +0000223 else {
Chris Lattnerec97a902010-01-05 05:36:20 +0000224 SrcIdx -= LHSWidth;
225 Src = SVI->getOperand(1);
Chris Lattnerec97a902010-01-05 05:36:20 +0000226 }
Chris Lattner229907c2011-07-18 04:54:35 +0000227 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
Chris Lattnerec97a902010-01-05 05:36:20 +0000228 return ExtractElementInst::Create(Src,
Bob Wilson9d07f392010-10-29 22:03:07 +0000229 ConstantInt::get(Int32Ty,
Chris Lattnerec97a902010-01-05 05:36:20 +0000230 SrcIdx, false));
231 }
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000232 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
233 // Canonicalize extractelement(cast) -> cast(extractelement)
234 // bitcasts can change the number of vector elements and they cost nothing
Anat Shemer55703182013-04-18 19:56:44 +0000235 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
Anat Shemer10260a72013-04-22 20:51:10 +0000236 Value *EE = Builder->CreateExtractElement(CI->getOperand(0),
237 EI.getIndexOperand());
238 Worklist.AddValue(EE);
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000239 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
240 }
Matt Arsenault243140f2013-11-04 20:36:06 +0000241 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
242 if (SI->hasOneUse()) {
243 // TODO: For a select on vectors, it might be useful to do this if it
244 // has multiple extractelement uses. For vector select, that seems to
245 // fight the vectorizer.
246
247 // If we are extracting an element from a vector select or a select on
248 // vectors, a select on the scalars extracted from the vector arguments.
249 Value *TrueVal = SI->getTrueValue();
250 Value *FalseVal = SI->getFalseValue();
251
252 Value *Cond = SI->getCondition();
253 if (Cond->getType()->isVectorTy()) {
254 Cond = Builder->CreateExtractElement(Cond,
255 EI.getIndexOperand(),
256 Cond->getName() + ".elt");
257 }
258
259 Value *V1Elem
260 = Builder->CreateExtractElement(TrueVal,
261 EI.getIndexOperand(),
262 TrueVal->getName() + ".elt");
263
264 Value *V2Elem
265 = Builder->CreateExtractElement(FalseVal,
266 EI.getIndexOperand(),
267 FalseVal->getName() + ".elt");
268 return SelectInst::Create(Cond,
269 V1Elem,
270 V2Elem,
271 SI->getName() + ".elt");
272 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000273 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000274 }
Craig Topperf40110f2014-04-25 05:29:35 +0000275 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000276}
277
Sanjay Patel6eccf482015-09-09 15:24:36 +0000278/// If V is a shuffle of values that ONLY returns elements from either LHS or
279/// RHS, return the shuffle mask and true. Otherwise, return false.
Chris Lattnerec97a902010-01-05 05:36:20 +0000280static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner0256be92012-01-27 03:08:05 +0000281 SmallVectorImpl<Constant*> &Mask) {
Tim Northoverfad27612014-03-07 10:24:44 +0000282 assert(LHS->getType() == RHS->getType() &&
Chris Lattnerec97a902010-01-05 05:36:20 +0000283 "Invalid CollectSingleShuffleElements");
Matt Arsenault8227b9f2013-09-06 00:37:24 +0000284 unsigned NumElts = V->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000285
Chris Lattnerec97a902010-01-05 05:36:20 +0000286 if (isa<UndefValue>(V)) {
287 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
288 return true;
289 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000290
Chris Lattnerec97a902010-01-05 05:36:20 +0000291 if (V == LHS) {
292 for (unsigned i = 0; i != NumElts; ++i)
293 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
294 return true;
295 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000296
Chris Lattnerec97a902010-01-05 05:36:20 +0000297 if (V == RHS) {
298 for (unsigned i = 0; i != NumElts; ++i)
299 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
300 i+NumElts));
301 return true;
302 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000303
Chris Lattnerec97a902010-01-05 05:36:20 +0000304 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
305 // If this is an insert of an extract from some other vector, include it.
306 Value *VecOp = IEI->getOperand(0);
307 Value *ScalarOp = IEI->getOperand(1);
308 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000309
Chris Lattnerec97a902010-01-05 05:36:20 +0000310 if (!isa<ConstantInt>(IdxOp))
311 return false;
312 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000313
Chris Lattnerec97a902010-01-05 05:36:20 +0000314 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000315 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000316 // transitively ok.
317 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
318 // If so, update the mask to reflect the inserted undef.
319 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
320 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000321 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000322 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
Tim Northoverfad27612014-03-07 10:24:44 +0000323 if (isa<ConstantInt>(EI->getOperand(1))) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000324 unsigned ExtractedIdx =
325 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Tim Northoverfad27612014-03-07 10:24:44 +0000326 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000327
Chris Lattnerec97a902010-01-05 05:36:20 +0000328 // This must be extracting from either LHS or RHS.
329 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000330 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000331 // transitively ok.
332 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
333 // If so, update the mask to reflect the inserted value.
334 if (EI->getOperand(0) == LHS) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000335 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000336 ConstantInt::get(Type::getInt32Ty(V->getContext()),
337 ExtractedIdx);
338 } else {
339 assert(EI->getOperand(0) == RHS);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000340 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000341 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000342 ExtractedIdx + NumLHSElts);
Chris Lattnerec97a902010-01-05 05:36:20 +0000343 }
344 return true;
345 }
346 }
347 }
348 }
349 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000350
Chris Lattnerec97a902010-01-05 05:36:20 +0000351 return false;
352}
353
Tim Northoverfad27612014-03-07 10:24:44 +0000354
355/// We are building a shuffle to create V, which is a sequence of insertelement,
356/// extractelement pairs. If PermittedRHS is set, then we must either use it or
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000357/// not rely on the second vector source. Return a std::pair containing the
Tim Northoverfad27612014-03-07 10:24:44 +0000358/// left and right vectors of the proposed shuffle (or 0), and set the Mask
359/// parameter as required.
360///
361/// Note: we intentionally don't try to fold earlier shuffles since they have
362/// often been chosen carefully to be efficiently implementable on the target.
363typedef std::pair<Value *, Value *> ShuffleOps;
364
365static ShuffleOps CollectShuffleElements(Value *V,
366 SmallVectorImpl<Constant *> &Mask,
367 Value *PermittedRHS) {
368 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
Chris Lattnerec97a902010-01-05 05:36:20 +0000369 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000370
Chris Lattnerec97a902010-01-05 05:36:20 +0000371 if (isa<UndefValue>(V)) {
372 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Tim Northoverfad27612014-03-07 10:24:44 +0000373 return std::make_pair(
374 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000375 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000376
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000377 if (isa<ConstantAggregateZero>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000378 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Tim Northoverfad27612014-03-07 10:24:44 +0000379 return std::make_pair(V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000380 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000381
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000382 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000383 // If this is an insert of an extract from some other vector, include it.
384 Value *VecOp = IEI->getOperand(0);
385 Value *ScalarOp = IEI->getOperand(1);
386 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000387
Chris Lattnerec97a902010-01-05 05:36:20 +0000388 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000389 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000390 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000391 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000392 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000393
Chris Lattnerec97a902010-01-05 05:36:20 +0000394 // Either the extracted from or inserted into vector must be RHSVec,
395 // otherwise we'd end up with a shuffle of three inputs.
Craig Topperf40110f2014-04-25 05:29:35 +0000396 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
Tim Northoverfad27612014-03-07 10:24:44 +0000397 Value *RHS = EI->getOperand(0);
398 ShuffleOps LR = CollectShuffleElements(VecOp, Mask, RHS);
Craig Toppere73658d2014-04-28 04:05:08 +0000399 assert(LR.second == nullptr || LR.second == RHS);
Tim Northoverfad27612014-03-07 10:24:44 +0000400
401 if (LR.first->getType() != RHS->getType()) {
402 // We tried our best, but we can't find anything compatible with RHS
403 // further up the chain. Return a trivial shuffle.
404 for (unsigned i = 0; i < NumElts; ++i)
405 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
406 return std::make_pair(V, nullptr);
407 }
408
409 unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000410 Mask[InsertedIdx % NumElts] =
Bob Wilson67a6f322010-10-29 22:20:45 +0000411 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000412 NumLHSElts+ExtractedIdx);
413 return std::make_pair(LR.first, RHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000414 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000415
Tim Northoverfad27612014-03-07 10:24:44 +0000416 if (VecOp == PermittedRHS) {
417 // We've gone as far as we can: anything on the other side of the
418 // extractelement will already have been converted into a shuffle.
419 unsigned NumLHSElts =
420 EI->getOperand(0)->getType()->getVectorNumElements();
421 for (unsigned i = 0; i != NumElts; ++i)
422 Mask.push_back(ConstantInt::get(
423 Type::getInt32Ty(V->getContext()),
424 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
425 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000426 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000427
Chris Lattnerec97a902010-01-05 05:36:20 +0000428 // If this insertelement is a chain that comes from exactly these two
429 // vectors, return the vector and the effective shuffle.
Tim Northoverfad27612014-03-07 10:24:44 +0000430 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
431 CollectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
432 Mask))
433 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000434 }
435 }
436 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000437
Chris Lattnerec97a902010-01-05 05:36:20 +0000438 // Otherwise, can't do anything fancy. Return an identity vector.
439 for (unsigned i = 0; i != NumElts; ++i)
440 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Tim Northoverfad27612014-03-07 10:24:44 +0000441 return std::make_pair(V, nullptr);
Chris Lattnerec97a902010-01-05 05:36:20 +0000442}
443
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000444/// Try to find redundant insertvalue instructions, like the following ones:
445/// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
446/// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
447/// Here the second instruction inserts values at the same indices, as the
448/// first one, making the first one redundant.
449/// It should be transformed to:
450/// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
451Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
452 bool IsRedundant = false;
453 ArrayRef<unsigned int> FirstIndices = I.getIndices();
454
455 // If there is a chain of insertvalue instructions (each of them except the
456 // last one has only one use and it's another insertvalue insn from this
457 // chain), check if any of the 'children' uses the same indices as the first
458 // instruction. In this case, the first one is redundant.
459 Value *V = &I;
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000460 unsigned Depth = 0;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000461 while (V->hasOneUse() && Depth < 10) {
462 User *U = V->user_back();
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000463 auto UserInsInst = dyn_cast<InsertValueInst>(U);
464 if (!UserInsInst || U->getOperand(0) != V)
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000465 break;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000466 if (UserInsInst->getIndices() == FirstIndices) {
467 IsRedundant = true;
468 break;
469 }
470 V = UserInsInst;
471 Depth++;
472 }
473
474 if (IsRedundant)
475 return ReplaceInstUsesWith(I, I.getOperand(0));
476 return nullptr;
477}
478
Chris Lattnerec97a902010-01-05 05:36:20 +0000479Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
480 Value *VecOp = IE.getOperand(0);
481 Value *ScalarOp = IE.getOperand(1);
482 Value *IdxOp = IE.getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000483
Chris Lattnerec97a902010-01-05 05:36:20 +0000484 // Inserting an undef or into an undefined place, remove this.
485 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
486 ReplaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000487
488 // If the inserted element was extracted from some other vector, and if the
Chris Lattnerec97a902010-01-05 05:36:20 +0000489 // indexes are constant, try to turn this into a shufflevector operation.
490 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000491 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
492 unsigned NumInsertVectorElts = IE.getType()->getNumElements();
493 unsigned NumExtractVectorElts =
494 EI->getOperand(0)->getType()->getVectorNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +0000495 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000496 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000497 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000498
Tim Northoverfad27612014-03-07 10:24:44 +0000499 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
Chris Lattnerec97a902010-01-05 05:36:20 +0000500 return ReplaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000501
Tim Northoverfad27612014-03-07 10:24:44 +0000502 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
Chris Lattnerec97a902010-01-05 05:36:20 +0000503 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000504
Chris Lattnerec97a902010-01-05 05:36:20 +0000505 // If we are extracting a value from a vector, then inserting it right
506 // back into the same place, just use the input vector.
507 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000508 return ReplaceInstUsesWith(IE, VecOp);
509
Chris Lattnerec97a902010-01-05 05:36:20 +0000510 // If this insertelement isn't used by some other insertelement, turn it
511 // (and any insertelements it points to), into one big shuffle.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000512 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
Chris Lattner0256be92012-01-27 03:08:05 +0000513 SmallVector<Constant*, 16> Mask;
Craig Topperf40110f2014-04-25 05:29:35 +0000514 ShuffleOps LR = CollectShuffleElements(&IE, Mask, nullptr);
Tim Northoverfad27612014-03-07 10:24:44 +0000515
516 // The proposed shuffle may be trivial, in which case we shouldn't
517 // perform the combine.
518 if (LR.first != &IE && LR.second != &IE) {
519 // We now have a shuffle of LHS, RHS, Mask.
Craig Topperf40110f2014-04-25 05:29:35 +0000520 if (LR.second == nullptr)
521 LR.second = UndefValue::get(LR.first->getType());
Tim Northoverfad27612014-03-07 10:24:44 +0000522 return new ShuffleVectorInst(LR.first, LR.second,
523 ConstantVector::get(Mask));
524 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000525 }
526 }
527 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000528
Chris Lattnerec97a902010-01-05 05:36:20 +0000529 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
530 APInt UndefElts(VWidth, 0);
531 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000532 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
533 if (V != &IE)
534 return ReplaceInstUsesWith(IE, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000535 return &IE;
Eli Friedmanef200db2011-02-19 22:42:40 +0000536 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000537
Craig Topperf40110f2014-04-25 05:29:35 +0000538 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000539}
540
Nick Lewyckya2b77202013-05-31 00:59:42 +0000541/// Return true if we can evaluate the specified expression tree if the vector
542/// elements were shuffled in a different order.
543static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
Nick Lewycky3f715e22013-06-01 20:51:31 +0000544 unsigned Depth = 5) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000545 // We can always reorder the elements of a constant.
546 if (isa<Constant>(V))
547 return true;
548
549 // We won't reorder vector arguments. No IPO here.
550 Instruction *I = dyn_cast<Instruction>(V);
551 if (!I) return false;
552
553 // Two users may expect different orders of the elements. Don't try it.
554 if (!I->hasOneUse())
555 return false;
556
557 if (Depth == 0) return false;
558
559 switch (I->getOpcode()) {
560 case Instruction::Add:
561 case Instruction::FAdd:
562 case Instruction::Sub:
563 case Instruction::FSub:
564 case Instruction::Mul:
565 case Instruction::FMul:
566 case Instruction::UDiv:
567 case Instruction::SDiv:
568 case Instruction::FDiv:
569 case Instruction::URem:
570 case Instruction::SRem:
571 case Instruction::FRem:
572 case Instruction::Shl:
573 case Instruction::LShr:
574 case Instruction::AShr:
575 case Instruction::And:
576 case Instruction::Or:
577 case Instruction::Xor:
578 case Instruction::ICmp:
579 case Instruction::FCmp:
580 case Instruction::Trunc:
581 case Instruction::ZExt:
582 case Instruction::SExt:
583 case Instruction::FPToUI:
584 case Instruction::FPToSI:
585 case Instruction::UIToFP:
586 case Instruction::SIToFP:
587 case Instruction::FPTrunc:
588 case Instruction::FPExt:
589 case Instruction::GetElementPtr: {
590 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
591 if (!CanEvaluateShuffled(I->getOperand(i), Mask, Depth-1))
592 return false;
593 }
594 return true;
595 }
596 case Instruction::InsertElement: {
597 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
598 if (!CI) return false;
599 int ElementNumber = CI->getLimitedValue();
600
601 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
602 // can't put an element into multiple indices.
603 bool SeenOnce = false;
604 for (int i = 0, e = Mask.size(); i != e; ++i) {
605 if (Mask[i] == ElementNumber) {
606 if (SeenOnce)
607 return false;
608 SeenOnce = true;
609 }
610 }
611 return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
612 }
613 }
614 return false;
615}
616
617/// Rebuild a new instruction just like 'I' but with the new operands given.
618/// In the event of type mismatch, the type of the operands is correct.
619static Value *BuildNew(Instruction *I, ArrayRef<Value*> NewOps) {
620 // We don't want to use the IRBuilder here because we want the replacement
621 // instructions to appear next to 'I', not the builder's insertion point.
622 switch (I->getOpcode()) {
623 case Instruction::Add:
624 case Instruction::FAdd:
625 case Instruction::Sub:
626 case Instruction::FSub:
627 case Instruction::Mul:
628 case Instruction::FMul:
629 case Instruction::UDiv:
630 case Instruction::SDiv:
631 case Instruction::FDiv:
632 case Instruction::URem:
633 case Instruction::SRem:
634 case Instruction::FRem:
635 case Instruction::Shl:
636 case Instruction::LShr:
637 case Instruction::AShr:
638 case Instruction::And:
639 case Instruction::Or:
640 case Instruction::Xor: {
641 BinaryOperator *BO = cast<BinaryOperator>(I);
642 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
643 BinaryOperator *New =
644 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
645 NewOps[0], NewOps[1], "", BO);
646 if (isa<OverflowingBinaryOperator>(BO)) {
647 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
648 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
649 }
650 if (isa<PossiblyExactOperator>(BO)) {
651 New->setIsExact(BO->isExact());
652 }
Owen Anderson48b842e2014-01-18 00:48:14 +0000653 if (isa<FPMathOperator>(BO))
654 New->copyFastMathFlags(I);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000655 return New;
656 }
657 case Instruction::ICmp:
658 assert(NewOps.size() == 2 && "icmp with #ops != 2");
659 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
660 NewOps[0], NewOps[1]);
661 case Instruction::FCmp:
662 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
663 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
664 NewOps[0], NewOps[1]);
665 case Instruction::Trunc:
666 case Instruction::ZExt:
667 case Instruction::SExt:
668 case Instruction::FPToUI:
669 case Instruction::FPToSI:
670 case Instruction::UIToFP:
671 case Instruction::SIToFP:
672 case Instruction::FPTrunc:
673 case Instruction::FPExt: {
674 // It's possible that the mask has a different number of elements from
675 // the original cast. We recompute the destination type to match the mask.
676 Type *DestTy =
677 VectorType::get(I->getType()->getScalarType(),
678 NewOps[0]->getType()->getVectorNumElements());
679 assert(NewOps.size() == 1 && "cast with #ops != 1");
680 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
681 "", I);
682 }
683 case Instruction::GetElementPtr: {
684 Value *Ptr = NewOps[0];
685 ArrayRef<Value*> Idx = NewOps.slice(1);
David Blaikie22319eb2015-03-14 19:24:04 +0000686 GetElementPtrInst *GEP = GetElementPtrInst::Create(
687 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000688 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
689 return GEP;
690 }
691 }
692 llvm_unreachable("failed to rebuild vector instructions");
693}
694
695Value *
696InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
697 // Mask.size() does not need to be equal to the number of vector elements.
698
699 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
700 if (isa<UndefValue>(V)) {
701 return UndefValue::get(VectorType::get(V->getType()->getScalarType(),
702 Mask.size()));
703 }
704 if (isa<ConstantAggregateZero>(V)) {
705 return ConstantAggregateZero::get(
706 VectorType::get(V->getType()->getScalarType(),
707 Mask.size()));
708 }
709 if (Constant *C = dyn_cast<Constant>(V)) {
710 SmallVector<Constant *, 16> MaskValues;
711 for (int i = 0, e = Mask.size(); i != e; ++i) {
712 if (Mask[i] == -1)
713 MaskValues.push_back(UndefValue::get(Builder->getInt32Ty()));
714 else
715 MaskValues.push_back(Builder->getInt32(Mask[i]));
716 }
717 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
718 ConstantVector::get(MaskValues));
719 }
720
721 Instruction *I = cast<Instruction>(V);
722 switch (I->getOpcode()) {
723 case Instruction::Add:
724 case Instruction::FAdd:
725 case Instruction::Sub:
726 case Instruction::FSub:
727 case Instruction::Mul:
728 case Instruction::FMul:
729 case Instruction::UDiv:
730 case Instruction::SDiv:
731 case Instruction::FDiv:
732 case Instruction::URem:
733 case Instruction::SRem:
734 case Instruction::FRem:
735 case Instruction::Shl:
736 case Instruction::LShr:
737 case Instruction::AShr:
738 case Instruction::And:
739 case Instruction::Or:
740 case Instruction::Xor:
741 case Instruction::ICmp:
742 case Instruction::FCmp:
743 case Instruction::Trunc:
744 case Instruction::ZExt:
745 case Instruction::SExt:
746 case Instruction::FPToUI:
747 case Instruction::FPToSI:
748 case Instruction::UIToFP:
749 case Instruction::SIToFP:
750 case Instruction::FPTrunc:
751 case Instruction::FPExt:
752 case Instruction::Select:
753 case Instruction::GetElementPtr: {
754 SmallVector<Value*, 8> NewOps;
755 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
756 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
757 Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
758 NewOps.push_back(V);
759 NeedsRebuild |= (V != I->getOperand(i));
760 }
761 if (NeedsRebuild) {
762 return BuildNew(I, NewOps);
763 }
764 return I;
765 }
766 case Instruction::InsertElement: {
767 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
Nick Lewyckya2b77202013-05-31 00:59:42 +0000768
769 // The insertelement was inserting at Element. Figure out which element
770 // that becomes after shuffling. The answer is guaranteed to be unique
771 // by CanEvaluateShuffled.
Nick Lewycky3f715e22013-06-01 20:51:31 +0000772 bool Found = false;
Nick Lewyckya2b77202013-05-31 00:59:42 +0000773 int Index = 0;
Nick Lewycky3f715e22013-06-01 20:51:31 +0000774 for (int e = Mask.size(); Index != e; ++Index) {
775 if (Mask[Index] == Element) {
776 Found = true;
Nick Lewyckya2b77202013-05-31 00:59:42 +0000777 break;
Nick Lewycky3f715e22013-06-01 20:51:31 +0000778 }
779 }
Nick Lewyckya2b77202013-05-31 00:59:42 +0000780
Hao Liu26abebb2014-01-08 03:06:15 +0000781 // If element is not in Mask, no need to handle the operand 1 (element to
782 // be inserted). Just evaluate values in operand 0 according to Mask.
Nick Lewycky3f715e22013-06-01 20:51:31 +0000783 if (!Found)
Hao Liu26abebb2014-01-08 03:06:15 +0000784 return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
Joey Goulya3250f22013-07-12 23:08:06 +0000785
Nick Lewyckya2b77202013-05-31 00:59:42 +0000786 Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
787 return InsertElementInst::Create(V, I->getOperand(1),
788 Builder->getInt32(Index), "", I);
789 }
790 }
791 llvm_unreachable("failed to reorder elements of vector instruction!");
792}
Chris Lattnerec97a902010-01-05 05:36:20 +0000793
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000794static void RecognizeIdentityMask(const SmallVectorImpl<int> &Mask,
795 bool &isLHSID, bool &isRHSID) {
796 isLHSID = isRHSID = true;
797
798 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
799 if (Mask[i] < 0) continue; // Ignore undef values.
800 // Is this an identity shuffle of the LHS value?
801 isLHSID &= (Mask[i] == (int)i);
802
803 // Is this an identity shuffle of the RHS value?
804 isRHSID &= (Mask[i]-e == i);
805 }
806}
807
JF Bastiend52c9902015-02-25 22:30:51 +0000808// Returns true if the shuffle is extracting a contiguous range of values from
809// LHS, for example:
810// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
811// Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
812// Shuffles to: |EE|FF|GG|HH|
813// +--+--+--+--+
814static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
815 SmallVector<int, 16> &Mask) {
816 unsigned LHSElems =
817 cast<VectorType>(SVI.getOperand(0)->getType())->getNumElements();
818 unsigned MaskElems = Mask.size();
819 unsigned BegIdx = Mask.front();
820 unsigned EndIdx = Mask.back();
821 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
822 return false;
823 for (unsigned I = 0; I != MaskElems; ++I)
824 if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
825 return false;
826 return true;
827}
828
Chris Lattnerec97a902010-01-05 05:36:20 +0000829Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
830 Value *LHS = SVI.getOperand(0);
831 Value *RHS = SVI.getOperand(1);
Chris Lattner8326bd82012-01-26 00:42:34 +0000832 SmallVector<int, 16> Mask = SVI.getShuffleMask();
JF Bastiend52c9902015-02-25 22:30:51 +0000833 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000834
Chris Lattnerec97a902010-01-05 05:36:20 +0000835 bool MadeChange = false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000836
Chris Lattnerec97a902010-01-05 05:36:20 +0000837 // Undefined shuffle mask -> undefined value.
838 if (isa<UndefValue>(SVI.getOperand(2)))
839 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000840
Eric Christopher51edc7b2010-08-17 22:55:27 +0000841 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000842
Chris Lattnerec97a902010-01-05 05:36:20 +0000843 APInt UndefElts(VWidth, 0);
844 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000845 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
846 if (V != &SVI)
847 return ReplaceInstUsesWith(SVI, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000848 LHS = SVI.getOperand(0);
849 RHS = SVI.getOperand(1);
850 MadeChange = true;
851 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000852
Eli Friedmance818272011-10-21 19:06:29 +0000853 unsigned LHSWidth = cast<VectorType>(LHS->getType())->getNumElements();
854
Chris Lattnerec97a902010-01-05 05:36:20 +0000855 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
856 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
857 if (LHS == RHS || isa<UndefValue>(LHS)) {
Eric Christopher51edc7b2010-08-17 22:55:27 +0000858 if (isa<UndefValue>(LHS) && LHS == RHS) {
859 // shuffle(undef,undef,mask) -> undef.
Nick Lewyckya2b77202013-05-31 00:59:42 +0000860 Value *Result = (VWidth == LHSWidth)
Eli Friedmance818272011-10-21 19:06:29 +0000861 ? LHS : UndefValue::get(SVI.getType());
Nick Lewyckya2b77202013-05-31 00:59:42 +0000862 return ReplaceInstUsesWith(SVI, Result);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000863 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000864
Chris Lattnerec97a902010-01-05 05:36:20 +0000865 // Remap any references to RHS to use LHS.
Chris Lattner0256be92012-01-27 03:08:05 +0000866 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +0000867 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +0000868 if (Mask[i] < 0) {
JF Bastiend52c9902015-02-25 22:30:51 +0000869 Elts.push_back(UndefValue::get(Int32Ty));
Chris Lattner0256be92012-01-27 03:08:05 +0000870 continue;
871 }
872
873 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
874 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
875 Mask[i] = -1; // Turn into undef.
JF Bastiend52c9902015-02-25 22:30:51 +0000876 Elts.push_back(UndefValue::get(Int32Ty));
Chris Lattner0256be92012-01-27 03:08:05 +0000877 } else {
878 Mask[i] = Mask[i] % e; // Force to LHS.
JF Bastiend52c9902015-02-25 22:30:51 +0000879 Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
Chris Lattnerec97a902010-01-05 05:36:20 +0000880 }
881 }
882 SVI.setOperand(0, SVI.getOperand(1));
883 SVI.setOperand(1, UndefValue::get(RHS->getType()));
884 SVI.setOperand(2, ConstantVector::get(Elts));
885 LHS = SVI.getOperand(0);
886 RHS = SVI.getOperand(1);
887 MadeChange = true;
888 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000889
Eli Friedmance818272011-10-21 19:06:29 +0000890 if (VWidth == LHSWidth) {
891 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Serge Pavlov9ef66a82014-05-11 08:46:12 +0000892 bool isLHSID, isRHSID;
893 RecognizeIdentityMask(Mask, isLHSID, isRHSID);
Eli Friedmance818272011-10-21 19:06:29 +0000894
895 // Eliminate identity shuffles.
896 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
897 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Eric Christopher51edc7b2010-08-17 22:55:27 +0000898 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000899
Nick Lewycky688d6682013-06-03 23:15:20 +0000900 if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000901 Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
902 return ReplaceInstUsesWith(SVI, V);
903 }
904
JF Bastiend52c9902015-02-25 22:30:51 +0000905 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
906 // a non-vector type. We can instead bitcast the original vector followed by
907 // an extract of the desired element:
908 //
909 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
910 // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
911 // %1 = bitcast <4 x i8> %sroa to i32
912 // Becomes:
913 // %bc = bitcast <16 x i8> %in to <4 x i32>
914 // %ext = extractelement <4 x i32> %bc, i32 0
915 //
916 // If the shuffle is extracting a contiguous range of values from the input
917 // vector then each use which is a bitcast of the extracted size can be
918 // replaced. This will work if the vector types are compatible, and the begin
919 // index is aligned to a value in the casted vector type. If the begin index
920 // isn't aligned then we can shuffle the original vector (keeping the same
921 // vector type) before extracting.
922 //
923 // This code will bail out if the target type is fundamentally incompatible
924 // with vectors of the source type.
925 //
926 // Example of <16 x i8>, target type i32:
927 // Index range [4,8): v-----------v Will work.
928 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
929 // <16 x i8>: | | | | | | | | | | | | | | | | |
930 // <4 x i32>: | | | | |
931 // +-----------+-----------+-----------+-----------+
932 // Index range [6,10): ^-----------^ Needs an extra shuffle.
933 // Target type i40: ^--------------^ Won't work, bail.
934 if (isShuffleExtractingFromLHS(SVI, Mask)) {
935 Value *V = LHS;
936 unsigned MaskElems = Mask.size();
937 unsigned BegIdx = Mask.front();
938 VectorType *SrcTy = cast<VectorType>(V->getType());
939 unsigned VecBitWidth = SrcTy->getBitWidth();
David Majnemer98cfe2b2015-04-03 20:18:40 +0000940 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
JF Bastiend52c9902015-02-25 22:30:51 +0000941 assert(SrcElemBitWidth && "vector elements must have a bitwidth");
942 unsigned SrcNumElems = SrcTy->getNumElements();
943 SmallVector<BitCastInst *, 8> BCs;
944 DenseMap<Type *, Value *> NewBCs;
945 for (User *U : SVI.users())
946 if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
947 if (!BC->use_empty())
948 // Only visit bitcasts that weren't previously handled.
949 BCs.push_back(BC);
950 for (BitCastInst *BC : BCs) {
951 Type *TgtTy = BC->getDestTy();
David Majnemer98cfe2b2015-04-03 20:18:40 +0000952 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
JF Bastiend52c9902015-02-25 22:30:51 +0000953 if (!TgtElemBitWidth)
954 continue;
955 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
956 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
957 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
958 if (!VecBitWidthsEqual)
959 continue;
960 if (!VectorType::isValidElementType(TgtTy))
961 continue;
962 VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
963 if (!BegIsAligned) {
964 // Shuffle the input so [0,NumElements) contains the output, and
965 // [NumElems,SrcNumElems) is undef.
966 SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
967 UndefValue::get(Int32Ty));
968 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
969 ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
970 V = Builder->CreateShuffleVector(V, UndefValue::get(V->getType()),
971 ConstantVector::get(ShuffleMask),
972 SVI.getName() + ".extract");
973 BegIdx = 0;
974 }
975 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
976 assert(SrcElemsPerTgtElem);
977 BegIdx /= SrcElemsPerTgtElem;
978 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
979 auto *NewBC =
980 BCAlreadyExists
981 ? NewBCs[CastSrcTy]
982 : Builder->CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
983 if (!BCAlreadyExists)
984 NewBCs[CastSrcTy] = NewBC;
985 auto *Ext = Builder->CreateExtractElement(
986 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
987 // The shufflevector isn't being replaced: the bitcast that used it
988 // is. InstCombine will visit the newly-created instructions.
989 ReplaceInstUsesWith(*BC, Ext);
990 MadeChange = true;
991 }
992 }
993
Eric Christopher51edc7b2010-08-17 22:55:27 +0000994 // If the LHS is a shufflevector itself, see if we can combine it with this
Eli Friedmance818272011-10-21 19:06:29 +0000995 // one without producing an unusual shuffle.
996 // Cases that might be simplified:
997 // 1.
998 // x1=shuffle(v1,v2,mask1)
999 // x=shuffle(x1,undef,mask)
1000 // ==>
1001 // x=shuffle(v1,undef,newMask)
1002 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1003 // 2.
1004 // x1=shuffle(v1,undef,mask1)
1005 // x=shuffle(x1,x2,mask)
1006 // where v1.size() == mask1.size()
1007 // ==>
1008 // x=shuffle(v1,x2,newMask)
1009 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1010 // 3.
1011 // x2=shuffle(v2,undef,mask2)
1012 // x=shuffle(x1,x2,mask)
1013 // where v2.size() == mask2.size()
1014 // ==>
1015 // x=shuffle(x1,v2,newMask)
1016 // newMask[i] = (mask[i] < x1.size())
1017 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1018 // 4.
1019 // x1=shuffle(v1,undef,mask1)
1020 // x2=shuffle(v2,undef,mask2)
1021 // x=shuffle(x1,x2,mask)
1022 // where v1.size() == v2.size()
1023 // ==>
1024 // x=shuffle(v1,v2,newMask)
1025 // newMask[i] = (mask[i] < x1.size())
1026 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1027 //
1028 // Here we are really conservative:
Eric Christopher51edc7b2010-08-17 22:55:27 +00001029 // we are absolutely afraid of producing a shuffle mask not in the input
1030 // program, because the code gen may not be smart enough to turn a merged
1031 // shuffle into two specific shuffles: it may produce worse code. As such,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001032 // we only merge two shuffles if the result is either a splat or one of the
1033 // input shuffle masks. In this case, merging the shuffles just removes
1034 // one instruction, which we know is safe. This is good for things like
Eli Friedmance818272011-10-21 19:06:29 +00001035 // turning: (splat(splat)) -> splat, or
1036 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1037 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1038 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1039 if (LHSShuffle)
1040 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
Craig Topperf40110f2014-04-25 05:29:35 +00001041 LHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001042 if (RHSShuffle)
1043 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +00001044 RHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001045 if (!LHSShuffle && !RHSShuffle)
Craig Topperf40110f2014-04-25 05:29:35 +00001046 return MadeChange ? &SVI : nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001047
Craig Topperf40110f2014-04-25 05:29:35 +00001048 Value* LHSOp0 = nullptr;
1049 Value* LHSOp1 = nullptr;
1050 Value* RHSOp0 = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001051 unsigned LHSOp0Width = 0;
1052 unsigned RHSOp0Width = 0;
1053 if (LHSShuffle) {
1054 LHSOp0 = LHSShuffle->getOperand(0);
1055 LHSOp1 = LHSShuffle->getOperand(1);
1056 LHSOp0Width = cast<VectorType>(LHSOp0->getType())->getNumElements();
1057 }
1058 if (RHSShuffle) {
1059 RHSOp0 = RHSShuffle->getOperand(0);
1060 RHSOp0Width = cast<VectorType>(RHSOp0->getType())->getNumElements();
1061 }
1062 Value* newLHS = LHS;
1063 Value* newRHS = RHS;
1064 if (LHSShuffle) {
1065 // case 1
Eric Christopher51edc7b2010-08-17 22:55:27 +00001066 if (isa<UndefValue>(RHS)) {
Eli Friedmance818272011-10-21 19:06:29 +00001067 newLHS = LHSOp0;
1068 newRHS = LHSOp1;
1069 }
1070 // case 2 or 4
1071 else if (LHSOp0Width == LHSWidth) {
1072 newLHS = LHSOp0;
1073 }
1074 }
1075 // case 3 or 4
1076 if (RHSShuffle && RHSOp0Width == LHSWidth) {
1077 newRHS = RHSOp0;
1078 }
1079 // case 4
1080 if (LHSOp0 == RHSOp0) {
1081 newLHS = LHSOp0;
Craig Topperf40110f2014-04-25 05:29:35 +00001082 newRHS = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001083 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001084
Eli Friedmance818272011-10-21 19:06:29 +00001085 if (newLHS == LHS && newRHS == RHS)
Craig Topperf40110f2014-04-25 05:29:35 +00001086 return MadeChange ? &SVI : nullptr;
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001087
Eli Friedmance818272011-10-21 19:06:29 +00001088 SmallVector<int, 16> LHSMask;
1089 SmallVector<int, 16> RHSMask;
Chris Lattner8326bd82012-01-26 00:42:34 +00001090 if (newLHS != LHS)
1091 LHSMask = LHSShuffle->getShuffleMask();
1092 if (RHSShuffle && newRHS != RHS)
1093 RHSMask = RHSShuffle->getShuffleMask();
1094
Eli Friedmance818272011-10-21 19:06:29 +00001095 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1096 SmallVector<int, 16> newMask;
1097 bool isSplat = true;
1098 int SplatElt = -1;
1099 // Create a new mask for the new ShuffleVectorInst so that the new
1100 // ShuffleVectorInst is equivalent to the original one.
1101 for (unsigned i = 0; i < VWidth; ++i) {
1102 int eltMask;
Craig Topper45d9f4b2013-01-18 05:30:07 +00001103 if (Mask[i] < 0) {
Eli Friedmance818272011-10-21 19:06:29 +00001104 // This element is an undef value.
1105 eltMask = -1;
1106 } else if (Mask[i] < (int)LHSWidth) {
1107 // This element is from left hand side vector operand.
Craig Topper2ea22b02013-01-18 05:09:16 +00001108 //
Eli Friedmance818272011-10-21 19:06:29 +00001109 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1110 // new mask value for the element.
1111 if (newLHS != LHS) {
1112 eltMask = LHSMask[Mask[i]];
1113 // If the value selected is an undef value, explicitly specify it
1114 // with a -1 mask value.
1115 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1116 eltMask = -1;
Craig Topper2ea22b02013-01-18 05:09:16 +00001117 } else
Eli Friedmance818272011-10-21 19:06:29 +00001118 eltMask = Mask[i];
1119 } else {
1120 // This element is from right hand side vector operand
1121 //
1122 // If the value selected is an undef value, explicitly specify it
1123 // with a -1 mask value. (case 1)
1124 if (isa<UndefValue>(RHS))
1125 eltMask = -1;
1126 // If RHS is going to be replaced (case 3 or 4), calculate the
1127 // new mask value for the element.
1128 else if (newRHS != RHS) {
1129 eltMask = RHSMask[Mask[i]-LHSWidth];
1130 // If the value selected is an undef value, explicitly specify it
1131 // with a -1 mask value.
1132 if (eltMask >= (int)RHSOp0Width) {
1133 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1134 && "should have been check above");
1135 eltMask = -1;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001136 }
Craig Topper2ea22b02013-01-18 05:09:16 +00001137 } else
Eli Friedmance818272011-10-21 19:06:29 +00001138 eltMask = Mask[i]-LHSWidth;
1139
1140 // If LHS's width is changed, shift the mask value accordingly.
1141 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any
Michael Gottesman02a11412012-10-16 21:29:38 +00001142 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1143 // If newRHS == newLHS, we want to remap any references from newRHS to
1144 // newLHS so that we can properly identify splats that may occur due to
Alp Tokercb402912014-01-24 17:20:08 +00001145 // obfuscation across the two vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001146 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001147 eltMask += newLHSWidth;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001148 }
Eli Friedmance818272011-10-21 19:06:29 +00001149
1150 // Check if this could still be a splat.
1151 if (eltMask >= 0) {
1152 if (SplatElt >= 0 && SplatElt != eltMask)
1153 isSplat = false;
1154 SplatElt = eltMask;
1155 }
1156
1157 newMask.push_back(eltMask);
1158 }
1159
1160 // If the result mask is equal to one of the original shuffle masks,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001161 // or is a splat, do the replacement.
1162 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
Eli Friedmance818272011-10-21 19:06:29 +00001163 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +00001164 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1165 if (newMask[i] < 0) {
1166 Elts.push_back(UndefValue::get(Int32Ty));
1167 } else {
1168 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1169 }
1170 }
Craig Topperf40110f2014-04-25 05:29:35 +00001171 if (!newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001172 newRHS = UndefValue::get(newLHS->getType());
1173 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001174 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001175
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001176 // If the result mask is an identity, replace uses of this instruction with
1177 // corresponding argument.
Serge Pavlovb575ee82014-05-13 06:07:21 +00001178 bool isLHSID, isRHSID;
1179 RecognizeIdentityMask(newMask, isLHSID, isRHSID);
1180 if (isLHSID && VWidth == LHSOp0Width) return ReplaceInstUsesWith(SVI, newLHS);
1181 if (isRHSID && VWidth == RHSOp0Width) return ReplaceInstUsesWith(SVI, newRHS);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001182
Craig Topperf40110f2014-04-25 05:29:35 +00001183 return MadeChange ? &SVI : nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +00001184}