blob: 6c99007475c12941cffe0b142656e27296ec3654 [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"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000016#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/ArrayRef.h"
JF Bastiend52c9902015-02-25 22:30:51 +000018#include "llvm/ADT/DenseMap.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000019#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/SmallVector.h"
David Majnemer599ca442015-07-13 01:15:53 +000021#include "llvm/Analysis/InstructionSimplify.h"
22#include "llvm/Analysis/VectorUtils.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000023#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/Constant.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/DerivedTypes.h"
27#include "llvm/IR/InstrTypes.h"
28#include "llvm/IR/Instruction.h"
29#include "llvm/IR/Instructions.h"
30#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000031#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000032#include "llvm/IR/Type.h"
33#include "llvm/IR/User.h"
34#include "llvm/IR/Value.h"
35#include "llvm/Support/Casting.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
38#include <cassert>
39#include <cstdint>
40#include <iterator>
41#include <utility>
42
Chris Lattnerec97a902010-01-05 05:36:20 +000043using namespace llvm;
Nadav Rotem7df85092013-01-15 23:43:14 +000044using namespace PatternMatch;
Chris Lattnerec97a902010-01-05 05:36:20 +000045
Chandler Carruth964daaa2014-04-22 02:55:47 +000046#define DEBUG_TYPE "instcombine"
47
Sanjay Patel6eccf482015-09-09 15:24:36 +000048/// Return true if the value is cheaper to scalarize than it is to leave as a
49/// vector operation. isConstant indicates whether we're extracting one known
50/// element. If false we're extracting a variable index.
Sanjay Patel431e1142015-11-17 17:24:08 +000051static bool cheapToScalarize(Value *V, bool isConstant) {
Chris Lattner8326bd82012-01-26 00:42:34 +000052 if (Constant *C = dyn_cast<Constant>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +000053 if (isConstant) return true;
Chris Lattner8326bd82012-01-26 00:42:34 +000054
55 // If all elts are the same, we can extract it and use any of the values.
Benjamin Kramer09b0f882014-01-24 19:02:37 +000056 if (Constant *Op0 = C->getAggregateElement(0U)) {
57 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e;
58 ++i)
59 if (C->getAggregateElement(i) != Op0)
60 return false;
61 return true;
62 }
Chris Lattnerec97a902010-01-05 05:36:20 +000063 }
64 Instruction *I = dyn_cast<Instruction>(V);
65 if (!I) return false;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000066
Chris Lattnerec97a902010-01-05 05:36:20 +000067 // Insert element gets simplified to the inserted element or is deleted if
68 // this is constant idx extract element and its a constant idx insertelt.
69 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
70 isa<ConstantInt>(I->getOperand(2)))
71 return true;
72 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
73 return true;
74 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
75 if (BO->hasOneUse() &&
Sanjay Patel431e1142015-11-17 17:24:08 +000076 (cheapToScalarize(BO->getOperand(0), isConstant) ||
77 cheapToScalarize(BO->getOperand(1), isConstant)))
Chris Lattnerec97a902010-01-05 05:36:20 +000078 return true;
79 if (CmpInst *CI = dyn_cast<CmpInst>(I))
80 if (CI->hasOneUse() &&
Sanjay Patel431e1142015-11-17 17:24:08 +000081 (cheapToScalarize(CI->getOperand(0), isConstant) ||
82 cheapToScalarize(CI->getOperand(1), isConstant)))
Chris Lattnerec97a902010-01-05 05:36:20 +000083 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000084
Chris Lattnerec97a902010-01-05 05:36:20 +000085 return false;
86}
87
Michael Kupersteina0c6ae02016-06-06 23:38:33 +000088// If we have a PHI node with a vector type that is only used to feed
Matt Arsenault38874732013-08-28 22:17:26 +000089// itself and be an operand of extractelement at a constant location,
90// try to replace the PHI of the vector type with a PHI of a scalar type.
Anat Shemer0c95efa2013-04-18 19:35:39 +000091Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
Michael Kupersteina0c6ae02016-06-06 23:38:33 +000092 SmallVector<Instruction *, 2> Extracts;
93 // The users we want the PHI to have are:
94 // 1) The EI ExtractElement (we already know this)
95 // 2) Possibly more ExtractElements with the same index.
96 // 3) Another operand, which will feed back into the PHI.
97 Instruction *PHIUser = nullptr;
98 for (auto U : PN->users()) {
99 if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
100 if (EI.getIndexOperand() == EU->getIndexOperand())
101 Extracts.push_back(EU);
102 else
103 return nullptr;
104 } else if (!PHIUser) {
105 PHIUser = cast<Instruction>(U);
106 } else {
107 return nullptr;
108 }
109 }
Anat Shemer0c95efa2013-04-18 19:35:39 +0000110
Michael Kupersteina0c6ae02016-06-06 23:38:33 +0000111 if (!PHIUser)
112 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000113
114 // Verify that this PHI user has one use, which is the PHI itself,
115 // and that it is a binary operation which is cheap to scalarize.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000116 // otherwise return nullptr.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000117 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
Sanjay Patel431e1142015-11-17 17:24:08 +0000118 !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true))
Craig Topperf40110f2014-04-25 05:29:35 +0000119 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000120
121 // Create a scalar PHI node that will replace the vector PHI node
122 // just before the current PHI node.
Joey Goulyb34294d2013-05-24 12:33:28 +0000123 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
124 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
Anat Shemer0c95efa2013-04-18 19:35:39 +0000125 // Scalarize each PHI operand.
Joey Goulyb34294d2013-05-24 12:33:28 +0000126 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
Anat Shemer0c95efa2013-04-18 19:35:39 +0000127 Value *PHIInVal = PN->getIncomingValue(i);
128 BasicBlock *inBB = PN->getIncomingBlock(i);
129 Value *Elt = EI.getIndexOperand();
130 // If the operand is the PHI induction variable:
131 if (PHIInVal == PHIUser) {
132 // Scalarize the binary operation. Its first operand is the
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000133 // scalar PHI, and the second operand is extracted from the other
Anat Shemer0c95efa2013-04-18 19:35:39 +0000134 // vector operand.
135 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
Joey Goulyb34294d2013-05-24 12:33:28 +0000136 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
Joey Gouly83699282013-05-24 12:29:54 +0000137 Value *Op = InsertNewInstWith(
138 ExtractElementInst::Create(B0->getOperand(opId), Elt,
139 B0->getOperand(opId)->getName() + ".Elt"),
140 *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000141 Value *newPHIUser = InsertNewInstWith(
Owen Anderson7ea02fc2016-03-01 19:35:52 +0000142 BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
143 scalarPHI, Op, B0), *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000144 scalarPHI->addIncoming(newPHIUser, inBB);
145 } else {
146 // Scalarize PHI input:
Joey Goulyb34294d2013-05-24 12:33:28 +0000147 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
Anat Shemer0c95efa2013-04-18 19:35:39 +0000148 // Insert the new instruction into the predecessor basic block.
149 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
150 BasicBlock::iterator InsertPos;
151 if (pos && !isa<PHINode>(pos)) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000152 InsertPos = ++pos->getIterator();
Anat Shemer0c95efa2013-04-18 19:35:39 +0000153 } else {
154 InsertPos = inBB->getFirstInsertionPt();
155 }
156
157 InsertNewInstWith(newEI, *InsertPos);
158
159 scalarPHI->addIncoming(newEI, inBB);
160 }
161 }
Michael Kupersteina0c6ae02016-06-06 23:38:33 +0000162
163 for (auto E : Extracts)
164 replaceInstUsesWith(*E, scalarPHI);
165
166 return &EI;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000167}
168
Chris Lattnerec97a902010-01-05 05:36:20 +0000169Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Daniel Berlin2c75c632017-04-26 20:56:07 +0000170 if (Value *V = SimplifyExtractElementInst(EI.getVectorOperand(),
Craig Toppera4205622017-06-09 03:21:29 +0000171 EI.getIndexOperand(),
172 SQ.getWithInstruction(&EI)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000173 return replaceInstUsesWith(EI, V);
David Majnemer599ca442015-07-13 01:15:53 +0000174
Chris Lattner8326bd82012-01-26 00:42:34 +0000175 // If vector val is constant with all elements the same, replace EI with
176 // that element. We handle a known element # below.
177 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0)))
Sanjay Patel431e1142015-11-17 17:24:08 +0000178 if (cheapToScalarize(C, false))
Sanjay Patel4b198802016-02-01 22:23:39 +0000179 return replaceInstUsesWith(EI, C->getAggregateElement(0U));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000180
Chris Lattnerec97a902010-01-05 05:36:20 +0000181 // If extracting a specified index from the vector, see if we can recursively
182 // find a previously computed scalar that was inserted into the vector.
183 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
184 unsigned IndexVal = IdxC->getZExtValue();
185 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000186
David Majnemer599ca442015-07-13 01:15:53 +0000187 // InstSimplify handles cases where the index is invalid.
188 assert(IndexVal < VectorWidth);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000189
Chris Lattnerec97a902010-01-05 05:36:20 +0000190 // This instruction only demands the single element from the input vector.
191 // If the input vector has a single use, simplify it based on this use
192 // property.
193 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
194 APInt UndefElts(VectorWidth, 0);
Chris Lattnerb22423c2010-02-08 23:56:03 +0000195 APInt DemandedMask(VectorWidth, 0);
Jay Foad25a5e4c2010-12-01 08:53:58 +0000196 DemandedMask.setBit(IndexVal);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000197 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask,
198 UndefElts)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000199 EI.setOperand(0, V);
200 return &EI;
201 }
202 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000203
Sanjay Patelb67076c2015-11-29 22:09:34 +0000204 // If this extractelement is directly using a bitcast from a vector of
Chris Lattnerec97a902010-01-05 05:36:20 +0000205 // the same number of elements, see if we can find the source element from
206 // it. In this case, we will end up needing to bitcast the scalars.
207 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
Chris Lattner8326bd82012-01-26 00:42:34 +0000208 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
Chris Lattnerec97a902010-01-05 05:36:20 +0000209 if (VT->getNumElements() == VectorWidth)
David Majnemer599ca442015-07-13 01:15:53 +0000210 if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal))
Chris Lattnerec97a902010-01-05 05:36:20 +0000211 return new BitCastInst(Elt, EI.getType());
212 }
Anat Shemer0c95efa2013-04-18 19:35:39 +0000213
214 // If there's a vector PHI feeding a scalar use through this extractelement
215 // instruction, try to scalarize the PHI.
216 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) {
Nick Lewycky881e9d62013-05-04 01:08:15 +0000217 Instruction *scalarPHI = scalarizePHI(EI, PN);
218 if (scalarPHI)
Joey Goulyb34294d2013-05-24 12:33:28 +0000219 return scalarPHI;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000220 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000221 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000222
Chris Lattnerec97a902010-01-05 05:36:20 +0000223 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
224 // Push extractelement into predecessor operation if legal and
Sanjay Patelb67076c2015-11-29 22:09:34 +0000225 // profitable to do so.
Chris Lattnerec97a902010-01-05 05:36:20 +0000226 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
227 if (I->hasOneUse() &&
Sanjay Patel431e1142015-11-17 17:24:08 +0000228 cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000229 Value *newEI0 =
Craig Topperbb4069e2017-07-07 23:16:26 +0000230 Builder.CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
231 EI.getName()+".lhs");
Chris Lattnerec97a902010-01-05 05:36:20 +0000232 Value *newEI1 =
Craig Topperbb4069e2017-07-07 23:16:26 +0000233 Builder.CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
234 EI.getName()+".rhs");
Owen Anderson7ea02fc2016-03-01 19:35:52 +0000235 return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(),
236 newEI0, newEI1, BO);
Chris Lattnerec97a902010-01-05 05:36:20 +0000237 }
238 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
239 // Extracting the inserted element?
240 if (IE->getOperand(2) == EI.getOperand(1))
Sanjay Patel4b198802016-02-01 22:23:39 +0000241 return replaceInstUsesWith(EI, IE->getOperand(1));
Chris Lattnerec97a902010-01-05 05:36:20 +0000242 // If the inserted and extracted elements are constants, they must not
243 // be the same value, extract from the pre-inserted value instead.
244 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
245 Worklist.AddValue(EI.getOperand(0));
246 EI.setOperand(0, IE->getOperand(0));
247 return &EI;
248 }
249 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
250 // If this is extracting an element from a shufflevector, figure out where
251 // it came from and extract from the appropriate input element instead.
252 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Eli Friedman303c81c2011-10-21 19:11:34 +0000253 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
Chris Lattnerec97a902010-01-05 05:36:20 +0000254 Value *Src;
255 unsigned LHSWidth =
Chris Lattner8326bd82012-01-26 00:42:34 +0000256 SVI->getOperand(0)->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000257
Bob Wilson11ee4562010-10-29 22:03:05 +0000258 if (SrcIdx < 0)
Sanjay Patel4b198802016-02-01 22:23:39 +0000259 return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Bob Wilson11ee4562010-10-29 22:03:05 +0000260 if (SrcIdx < (int)LHSWidth)
Chris Lattnerec97a902010-01-05 05:36:20 +0000261 Src = SVI->getOperand(0);
Bob Wilson11ee4562010-10-29 22:03:05 +0000262 else {
Chris Lattnerec97a902010-01-05 05:36:20 +0000263 SrcIdx -= LHSWidth;
264 Src = SVI->getOperand(1);
Chris Lattnerec97a902010-01-05 05:36:20 +0000265 }
Chris Lattner229907c2011-07-18 04:54:35 +0000266 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
Chris Lattnerec97a902010-01-05 05:36:20 +0000267 return ExtractElementInst::Create(Src,
Bob Wilson9d07f392010-10-29 22:03:07 +0000268 ConstantInt::get(Int32Ty,
Chris Lattnerec97a902010-01-05 05:36:20 +0000269 SrcIdx, false));
270 }
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000271 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Sanjay Patelb67076c2015-11-29 22:09:34 +0000272 // Canonicalize extractelement(cast) -> cast(extractelement).
273 // Bitcasts can change the number of vector elements, and they cost
274 // nothing.
Anat Shemer55703182013-04-18 19:56:44 +0000275 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000276 Value *EE = Builder.CreateExtractElement(CI->getOperand(0),
277 EI.getIndexOperand());
Anat Shemer10260a72013-04-22 20:51:10 +0000278 Worklist.AddValue(EE);
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000279 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
280 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000281 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000282 }
Craig Topperf40110f2014-04-25 05:29:35 +0000283 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000284}
285
Sanjay Patel6eccf482015-09-09 15:24:36 +0000286/// If V is a shuffle of values that ONLY returns elements from either LHS or
287/// RHS, return the shuffle mask and true. Otherwise, return false.
Sanjay Patel431e1142015-11-17 17:24:08 +0000288static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner0256be92012-01-27 03:08:05 +0000289 SmallVectorImpl<Constant*> &Mask) {
Tim Northoverfad27612014-03-07 10:24:44 +0000290 assert(LHS->getType() == RHS->getType() &&
Chris Lattnerec97a902010-01-05 05:36:20 +0000291 "Invalid CollectSingleShuffleElements");
Matt Arsenault8227b9f2013-09-06 00:37:24 +0000292 unsigned NumElts = V->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000293
Chris Lattnerec97a902010-01-05 05:36:20 +0000294 if (isa<UndefValue>(V)) {
295 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
296 return true;
297 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000298
Chris Lattnerec97a902010-01-05 05:36:20 +0000299 if (V == LHS) {
300 for (unsigned i = 0; i != NumElts; ++i)
301 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
302 return true;
303 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000304
Chris Lattnerec97a902010-01-05 05:36:20 +0000305 if (V == RHS) {
306 for (unsigned i = 0; i != NumElts; ++i)
307 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
308 i+NumElts));
309 return true;
310 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000311
Chris Lattnerec97a902010-01-05 05:36:20 +0000312 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
313 // If this is an insert of an extract from some other vector, include it.
314 Value *VecOp = IEI->getOperand(0);
315 Value *ScalarOp = IEI->getOperand(1);
316 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000317
Chris Lattnerec97a902010-01-05 05:36:20 +0000318 if (!isa<ConstantInt>(IdxOp))
319 return false;
320 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000321
Chris Lattnerec97a902010-01-05 05:36:20 +0000322 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000323 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000324 // transitively ok.
Sanjay Patel431e1142015-11-17 17:24:08 +0000325 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000326 // If so, update the mask to reflect the inserted undef.
327 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
328 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000329 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000330 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
Tim Northoverfad27612014-03-07 10:24:44 +0000331 if (isa<ConstantInt>(EI->getOperand(1))) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000332 unsigned ExtractedIdx =
333 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Tim Northoverfad27612014-03-07 10:24:44 +0000334 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000335
Chris Lattnerec97a902010-01-05 05:36:20 +0000336 // This must be extracting from either LHS or RHS.
337 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000338 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000339 // transitively ok.
Sanjay Patel431e1142015-11-17 17:24:08 +0000340 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000341 // If so, update the mask to reflect the inserted value.
342 if (EI->getOperand(0) == LHS) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000343 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000344 ConstantInt::get(Type::getInt32Ty(V->getContext()),
345 ExtractedIdx);
346 } else {
347 assert(EI->getOperand(0) == RHS);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000348 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000349 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000350 ExtractedIdx + NumLHSElts);
Chris Lattnerec97a902010-01-05 05:36:20 +0000351 }
352 return true;
353 }
354 }
355 }
356 }
357 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000358
Chris Lattnerec97a902010-01-05 05:36:20 +0000359 return false;
360}
361
Sanjay Patelae945e72015-12-24 21:17:56 +0000362/// If we have insertion into a vector that is wider than the vector that we
363/// are extracting from, try to widen the source vector to allow a single
364/// shufflevector to replace one or more insert/extract pairs.
365static void replaceExtractElements(InsertElementInst *InsElt,
366 ExtractElementInst *ExtElt,
367 InstCombiner &IC) {
368 VectorType *InsVecType = InsElt->getType();
369 VectorType *ExtVecType = ExtElt->getVectorOperandType();
370 unsigned NumInsElts = InsVecType->getVectorNumElements();
371 unsigned NumExtElts = ExtVecType->getVectorNumElements();
372
373 // The inserted-to vector must be wider than the extracted-from vector.
374 if (InsVecType->getElementType() != ExtVecType->getElementType() ||
375 NumExtElts >= NumInsElts)
376 return;
377
378 // Create a shuffle mask to widen the extended-from vector using undefined
379 // values. The mask selects all of the values of the original vector followed
380 // by as many undefined values as needed to create a vector of the same length
381 // as the inserted-to vector.
382 SmallVector<Constant *, 16> ExtendMask;
383 IntegerType *IntType = Type::getInt32Ty(InsElt->getContext());
384 for (unsigned i = 0; i < NumExtElts; ++i)
385 ExtendMask.push_back(ConstantInt::get(IntType, i));
386 for (unsigned i = NumExtElts; i < NumInsElts; ++i)
387 ExtendMask.push_back(UndefValue::get(IntType));
388
389 Value *ExtVecOp = ExtElt->getVectorOperand();
Sanjay Patel66fff732016-01-29 20:21:02 +0000390 auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
391 BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
392 ? ExtVecOpInst->getParent()
393 : ExtElt->getParent();
394
395 // TODO: This restriction matches the basic block check below when creating
396 // new extractelement instructions. If that limitation is removed, this one
397 // could also be removed. But for now, we just bail out to ensure that we
398 // will replace the extractelement instruction that is feeding our
399 // insertelement instruction. This allows the insertelement to then be
400 // replaced by a shufflevector. If the insertelement is not replaced, we can
401 // induce infinite looping because there's an optimization for extractelement
402 // that will delete our widening shuffle. This would trigger another attempt
403 // here to create that shuffle, and we spin forever.
404 if (InsertionBlock != InsElt->getParent())
405 return;
406
Sanjay Patel4e1b5a52016-11-10 00:15:14 +0000407 // TODO: This restriction matches the check in visitInsertElementInst() and
408 // prevents an infinite loop caused by not turning the extract/insert pair
409 // into a shuffle. We really should not need either check, but we're lacking
410 // folds for shufflevectors because we're afraid to generate shuffle masks
411 // that the backend can't handle.
412 if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
413 return;
414
Sanjay Patelae945e72015-12-24 21:17:56 +0000415 auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
416 ConstantVector::get(ExtendMask));
417
Sanjay Patela1c53472016-01-05 19:09:47 +0000418 // Insert the new shuffle after the vector operand of the extract is defined
Sanjay Pateld72a4582016-01-08 01:39:16 +0000419 // (as long as it's not a PHI) or at the start of the basic block of the
420 // extract, so any subsequent extracts in the same basic block can use it.
421 // TODO: Insert before the earliest ExtractElementInst that is replaced.
Sanjay Pateld72a4582016-01-08 01:39:16 +0000422 if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
Sanjay Patela1c53472016-01-05 19:09:47 +0000423 WideVec->insertAfter(ExtVecOpInst);
Sanjay Pateld72a4582016-01-08 01:39:16 +0000424 else
Sanjay Patela1c53472016-01-05 19:09:47 +0000425 IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
Sanjay Patela1c53472016-01-05 19:09:47 +0000426
427 // Replace extracts from the original narrow vector with extracts from the new
428 // wide vector.
Sanjay Patelae945e72015-12-24 21:17:56 +0000429 for (User *U : ExtVecOp->users()) {
Sanjay Patela1c53472016-01-05 19:09:47 +0000430 ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
Sanjay Pateld72a4582016-01-08 01:39:16 +0000431 if (!OldExt || OldExt->getParent() != WideVec->getParent())
Sanjay Patela1c53472016-01-05 19:09:47 +0000432 continue;
433 auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
Sven van Haastregt78819e02017-06-05 09:18:10 +0000434 NewExt->insertAfter(OldExt);
Sanjay Patel4b198802016-02-01 22:23:39 +0000435 IC.replaceInstUsesWith(*OldExt, NewExt);
Sanjay Patelae945e72015-12-24 21:17:56 +0000436 }
437}
Tim Northoverfad27612014-03-07 10:24:44 +0000438
439/// We are building a shuffle to create V, which is a sequence of insertelement,
440/// extractelement pairs. If PermittedRHS is set, then we must either use it or
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000441/// not rely on the second vector source. Return a std::pair containing the
Tim Northoverfad27612014-03-07 10:24:44 +0000442/// left and right vectors of the proposed shuffle (or 0), and set the Mask
443/// parameter as required.
444///
445/// Note: we intentionally don't try to fold earlier shuffles since they have
446/// often been chosen carefully to be efficiently implementable on the target.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000447using ShuffleOps = std::pair<Value *, Value *>;
Tim Northoverfad27612014-03-07 10:24:44 +0000448
Sanjay Patel431e1142015-11-17 17:24:08 +0000449static ShuffleOps collectShuffleElements(Value *V,
Tim Northoverfad27612014-03-07 10:24:44 +0000450 SmallVectorImpl<Constant *> &Mask,
Sanjay Patelae945e72015-12-24 21:17:56 +0000451 Value *PermittedRHS,
452 InstCombiner &IC) {
Tim Northoverfad27612014-03-07 10:24:44 +0000453 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
Craig Topper17b55682016-12-29 07:03:18 +0000454 unsigned NumElts = V->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000455
Chris Lattnerec97a902010-01-05 05:36:20 +0000456 if (isa<UndefValue>(V)) {
457 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Tim Northoverfad27612014-03-07 10:24:44 +0000458 return std::make_pair(
459 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000460 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000461
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000462 if (isa<ConstantAggregateZero>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000463 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Tim Northoverfad27612014-03-07 10:24:44 +0000464 return std::make_pair(V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000465 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000466
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000467 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000468 // If this is an insert of an extract from some other vector, include it.
469 Value *VecOp = IEI->getOperand(0);
470 Value *ScalarOp = IEI->getOperand(1);
471 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000472
Chris Lattnerec97a902010-01-05 05:36:20 +0000473 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000474 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000475 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000476 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000477 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000478
Chris Lattnerec97a902010-01-05 05:36:20 +0000479 // Either the extracted from or inserted into vector must be RHSVec,
480 // otherwise we'd end up with a shuffle of three inputs.
Craig Topperf40110f2014-04-25 05:29:35 +0000481 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
Tim Northoverfad27612014-03-07 10:24:44 +0000482 Value *RHS = EI->getOperand(0);
Sanjay Patelae945e72015-12-24 21:17:56 +0000483 ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
Craig Toppere73658d2014-04-28 04:05:08 +0000484 assert(LR.second == nullptr || LR.second == RHS);
Tim Northoverfad27612014-03-07 10:24:44 +0000485
486 if (LR.first->getType() != RHS->getType()) {
Sanjay Patelae945e72015-12-24 21:17:56 +0000487 // Although we are giving up for now, see if we can create extracts
488 // that match the inserts for another round of combining.
489 replaceExtractElements(IEI, EI, IC);
490
Tim Northoverfad27612014-03-07 10:24:44 +0000491 // We tried our best, but we can't find anything compatible with RHS
492 // further up the chain. Return a trivial shuffle.
493 for (unsigned i = 0; i < NumElts; ++i)
494 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
495 return std::make_pair(V, nullptr);
496 }
497
498 unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000499 Mask[InsertedIdx % NumElts] =
Bob Wilson67a6f322010-10-29 22:20:45 +0000500 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000501 NumLHSElts+ExtractedIdx);
502 return std::make_pair(LR.first, RHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000503 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000504
Tim Northoverfad27612014-03-07 10:24:44 +0000505 if (VecOp == PermittedRHS) {
506 // We've gone as far as we can: anything on the other side of the
507 // extractelement will already have been converted into a shuffle.
508 unsigned NumLHSElts =
509 EI->getOperand(0)->getType()->getVectorNumElements();
510 for (unsigned i = 0; i != NumElts; ++i)
511 Mask.push_back(ConstantInt::get(
512 Type::getInt32Ty(V->getContext()),
513 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
514 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000515 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000516
Chris Lattnerec97a902010-01-05 05:36:20 +0000517 // If this insertelement is a chain that comes from exactly these two
518 // vectors, return the vector and the effective shuffle.
Tim Northoverfad27612014-03-07 10:24:44 +0000519 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
Sanjay Patel431e1142015-11-17 17:24:08 +0000520 collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
Tim Northoverfad27612014-03-07 10:24:44 +0000521 Mask))
522 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000523 }
524 }
525 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000526
Sanjay Patelb67076c2015-11-29 22:09:34 +0000527 // Otherwise, we can't do anything fancy. Return an identity vector.
Chris Lattnerec97a902010-01-05 05:36:20 +0000528 for (unsigned i = 0; i != NumElts; ++i)
529 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Tim Northoverfad27612014-03-07 10:24:44 +0000530 return std::make_pair(V, nullptr);
Chris Lattnerec97a902010-01-05 05:36:20 +0000531}
532
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000533/// Try to find redundant insertvalue instructions, like the following ones:
534/// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
535/// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
536/// Here the second instruction inserts values at the same indices, as the
537/// first one, making the first one redundant.
538/// It should be transformed to:
539/// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
540Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
541 bool IsRedundant = false;
542 ArrayRef<unsigned int> FirstIndices = I.getIndices();
543
544 // If there is a chain of insertvalue instructions (each of them except the
545 // last one has only one use and it's another insertvalue insn from this
546 // chain), check if any of the 'children' uses the same indices as the first
547 // instruction. In this case, the first one is redundant.
548 Value *V = &I;
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000549 unsigned Depth = 0;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000550 while (V->hasOneUse() && Depth < 10) {
551 User *U = V->user_back();
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000552 auto UserInsInst = dyn_cast<InsertValueInst>(U);
553 if (!UserInsInst || U->getOperand(0) != V)
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000554 break;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000555 if (UserInsInst->getIndices() == FirstIndices) {
556 IsRedundant = true;
557 break;
558 }
559 V = UserInsInst;
560 Depth++;
561 }
562
563 if (IsRedundant)
Sanjay Patel4b198802016-02-01 22:23:39 +0000564 return replaceInstUsesWith(I, I.getOperand(0));
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000565 return nullptr;
566}
567
Sanjay Patel521f19f2016-09-02 17:05:43 +0000568static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) {
569 int MaskSize = Shuf.getMask()->getType()->getVectorNumElements();
570 int VecSize = Shuf.getOperand(0)->getType()->getVectorNumElements();
571
572 // A vector select does not change the size of the operands.
573 if (MaskSize != VecSize)
574 return false;
575
576 // Each mask element must be undefined or choose a vector element from one of
577 // the source operands without crossing vector lanes.
578 for (int i = 0; i != MaskSize; ++i) {
579 int Elt = Shuf.getMaskValue(i);
580 if (Elt != -1 && Elt != i && Elt != i + VecSize)
581 return false;
582 }
583
584 return true;
585}
586
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000587// Turn a chain of inserts that splats a value into a canonical insert + shuffle
588// splat. That is:
589// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
590// shufflevector(insertelt(X, %k, 0), undef, zero)
591static Instruction *foldInsSequenceIntoBroadcast(InsertElementInst &InsElt) {
592 // We are interested in the last insert in a chain. So, if this insert
593 // has a single user, and that user is an insert, bail.
594 if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
595 return nullptr;
596
597 VectorType *VT = cast<VectorType>(InsElt.getType());
598 int NumElements = VT->getNumElements();
599
600 // Do not try to do this for a one-element vector, since that's a nop,
601 // and will cause an inf-loop.
602 if (NumElements == 1)
603 return nullptr;
604
605 Value *SplatVal = InsElt.getOperand(1);
606 InsertElementInst *CurrIE = &InsElt;
607 SmallVector<bool, 16> ElementPresent(NumElements, false);
Florian Hahnb992fee2017-08-30 10:54:21 +0000608 InsertElementInst *FirstIE = nullptr;
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000609
610 // Walk the chain backwards, keeping track of which indices we inserted into,
611 // until we hit something that isn't an insert of the splatted value.
612 while (CurrIE) {
Sanjay Patel863d4942017-11-27 18:19:32 +0000613 auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000614 if (!Idx || CurrIE->getOperand(1) != SplatVal)
615 return nullptr;
616
Sanjay Patel863d4942017-11-27 18:19:32 +0000617 auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
Florian Hahnb992fee2017-08-30 10:54:21 +0000618 // Check none of the intermediate steps have any additional uses, except
619 // for the root insertelement instruction, which can be re-used, if it
620 // inserts at position 0.
621 if (CurrIE != &InsElt &&
622 (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero())))
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000623 return nullptr;
624
625 ElementPresent[Idx->getZExtValue()] = true;
Florian Hahnb992fee2017-08-30 10:54:21 +0000626 FirstIE = CurrIE;
627 CurrIE = NextIE;
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000628 }
629
630 // Make sure we've seen an insert into every element.
631 if (llvm::any_of(ElementPresent, [](bool Present) { return !Present; }))
632 return nullptr;
633
634 // All right, create the insert + shuffle.
Florian Hahnb992fee2017-08-30 10:54:21 +0000635 Instruction *InsertFirst;
636 if (cast<ConstantInt>(FirstIE->getOperand(2))->isZero())
637 InsertFirst = FirstIE;
638 else
639 InsertFirst = InsertElementInst::Create(
640 UndefValue::get(VT), SplatVal,
641 ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 0),
642 "", &InsElt);
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000643
644 Constant *ZeroMask = ConstantAggregateZero::get(
645 VectorType::get(Type::getInt32Ty(InsElt.getContext()), NumElements));
646
647 return new ShuffleVectorInst(InsertFirst, UndefValue::get(VT), ZeroMask);
648}
649
Sanjay Patel2f602ce2017-03-22 17:10:44 +0000650/// If we have an insertelement instruction feeding into another insertelement
651/// and the 2nd is inserting a constant into the vector, canonicalize that
652/// constant insertion before the insertion of a variable:
653///
654/// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
655/// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
656///
657/// This has the potential of eliminating the 2nd insertelement instruction
658/// via constant folding of the scalar constant into a vector constant.
659static Instruction *hoistInsEltConst(InsertElementInst &InsElt2,
660 InstCombiner::BuilderTy &Builder) {
661 auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
662 if (!InsElt1 || !InsElt1->hasOneUse())
663 return nullptr;
664
665 Value *X, *Y;
666 Constant *ScalarC;
667 ConstantInt *IdxC1, *IdxC2;
668 if (match(InsElt1->getOperand(0), m_Value(X)) &&
669 match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
670 match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
671 match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
672 match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
673 Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
674 return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
675 }
676
677 return nullptr;
678}
679
Alexey Bataevfee90782016-09-23 09:14:08 +0000680/// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
681/// --> shufflevector X, CVec', Mask'
Sanjay Patel521f19f2016-09-02 17:05:43 +0000682static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) {
Alexey Bataevfee90782016-09-23 09:14:08 +0000683 auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
684 // Bail out if the parent has more than one use. In that case, we'd be
Sanjay Patel521f19f2016-09-02 17:05:43 +0000685 // replacing the insertelt with a shuffle, and that's not a clear win.
Alexey Bataevfee90782016-09-23 09:14:08 +0000686 if (!Inst || !Inst->hasOneUse())
Sanjay Patel521f19f2016-09-02 17:05:43 +0000687 return nullptr;
Alexey Bataevfee90782016-09-23 09:14:08 +0000688 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
689 // The shuffle must have a constant vector operand. The insertelt must have
690 // a constant scalar being inserted at a constant position in the vector.
691 Constant *ShufConstVec, *InsEltScalar;
692 uint64_t InsEltIndex;
693 if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
694 !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
695 !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
696 return nullptr;
Sanjay Patel521f19f2016-09-02 17:05:43 +0000697
Alexey Bataevfee90782016-09-23 09:14:08 +0000698 // Adding an element to an arbitrary shuffle could be expensive, but a
699 // shuffle that selects elements from vectors without crossing lanes is
700 // assumed cheap.
701 // If we're just adding a constant into that shuffle, it will still be
702 // cheap.
703 if (!isShuffleEquivalentToSelect(*Shuf))
704 return nullptr;
Sanjay Patel521f19f2016-09-02 17:05:43 +0000705
Alexey Bataevfee90782016-09-23 09:14:08 +0000706 // From the above 'select' check, we know that the mask has the same number
707 // of elements as the vector input operands. We also know that each constant
708 // input element is used in its lane and can not be used more than once by
709 // the shuffle. Therefore, replace the constant in the shuffle's constant
710 // vector with the insertelt constant. Replace the constant in the shuffle's
711 // mask vector with the insertelt index plus the length of the vector
712 // (because the constant vector operand of a shuffle is always the 2nd
713 // operand).
714 Constant *Mask = Shuf->getMask();
715 unsigned NumElts = Mask->getType()->getVectorNumElements();
716 SmallVector<Constant *, 16> NewShufElts(NumElts);
717 SmallVector<Constant *, 16> NewMaskElts(NumElts);
718 for (unsigned I = 0; I != NumElts; ++I) {
719 if (I == InsEltIndex) {
720 NewShufElts[I] = InsEltScalar;
721 Type *Int32Ty = Type::getInt32Ty(Shuf->getContext());
722 NewMaskElts[I] = ConstantInt::get(Int32Ty, InsEltIndex + NumElts);
723 } else {
724 // Copy over the existing values.
725 NewShufElts[I] = ShufConstVec->getAggregateElement(I);
726 NewMaskElts[I] = Mask->getAggregateElement(I);
727 }
Sanjay Patel521f19f2016-09-02 17:05:43 +0000728 }
Sanjay Patel521f19f2016-09-02 17:05:43 +0000729
Alexey Bataevfee90782016-09-23 09:14:08 +0000730 // Create new operands for a shuffle that includes the constant of the
731 // original insertelt. The old shuffle will be dead now.
732 return new ShuffleVectorInst(Shuf->getOperand(0),
733 ConstantVector::get(NewShufElts),
734 ConstantVector::get(NewMaskElts));
735 } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
736 // Transform sequences of insertelements ops with constant data/indexes into
737 // a single shuffle op.
738 unsigned NumElts = InsElt.getType()->getNumElements();
739
740 uint64_t InsertIdx[2];
741 Constant *Val[2];
742 if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
743 !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
744 !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
745 !match(IEI->getOperand(1), m_Constant(Val[1])))
746 return nullptr;
747 SmallVector<Constant *, 16> Values(NumElts);
748 SmallVector<Constant *, 16> Mask(NumElts);
749 auto ValI = std::begin(Val);
750 // Generate new constant vector and mask.
751 // We have 2 values/masks from the insertelements instructions. Insert them
752 // into new value/mask vectors.
753 for (uint64_t I : InsertIdx) {
754 if (!Values[I]) {
755 assert(!Mask[I]);
756 Values[I] = *ValI;
757 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()),
758 NumElts + I);
759 }
760 ++ValI;
761 }
762 // Remaining values are filled with 'undef' values.
763 for (unsigned I = 0; I < NumElts; ++I) {
764 if (!Values[I]) {
765 assert(!Mask[I]);
766 Values[I] = UndefValue::get(InsElt.getType()->getElementType());
767 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), I);
768 }
769 }
770 // Create new operands for a shuffle that includes the constant of the
771 // original insertelt.
772 return new ShuffleVectorInst(IEI->getOperand(0),
773 ConstantVector::get(Values),
774 ConstantVector::get(Mask));
775 }
776 return nullptr;
Sanjay Patel521f19f2016-09-02 17:05:43 +0000777}
778
Chris Lattnerec97a902010-01-05 05:36:20 +0000779Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
780 Value *VecOp = IE.getOperand(0);
781 Value *ScalarOp = IE.getOperand(1);
782 Value *IdxOp = IE.getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000783
Chris Lattnerec97a902010-01-05 05:36:20 +0000784 // Inserting an undef or into an undefined place, remove this.
785 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
Sanjay Patel4b198802016-02-01 22:23:39 +0000786 replaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000787
788 // If the inserted element was extracted from some other vector, and if the
Chris Lattnerec97a902010-01-05 05:36:20 +0000789 // indexes are constant, try to turn this into a shufflevector operation.
790 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000791 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
792 unsigned NumInsertVectorElts = IE.getType()->getNumElements();
793 unsigned NumExtractVectorElts =
794 EI->getOperand(0)->getType()->getVectorNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +0000795 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000796 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000797 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000798
Tim Northoverfad27612014-03-07 10:24:44 +0000799 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract.
Sanjay Patel4b198802016-02-01 22:23:39 +0000800 return replaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000801
Tim Northoverfad27612014-03-07 10:24:44 +0000802 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert.
Sanjay Patel4b198802016-02-01 22:23:39 +0000803 return replaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000804
Chris Lattnerec97a902010-01-05 05:36:20 +0000805 // If we are extracting a value from a vector, then inserting it right
806 // back into the same place, just use the input vector.
807 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
Sanjay Patel4b198802016-02-01 22:23:39 +0000808 return replaceInstUsesWith(IE, VecOp);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000809
Chris Lattnerec97a902010-01-05 05:36:20 +0000810 // If this insertelement isn't used by some other insertelement, turn it
811 // (and any insertelements it points to), into one big shuffle.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000812 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) {
Chris Lattner0256be92012-01-27 03:08:05 +0000813 SmallVector<Constant*, 16> Mask;
Sanjay Patelae945e72015-12-24 21:17:56 +0000814 ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
Tim Northoverfad27612014-03-07 10:24:44 +0000815
816 // The proposed shuffle may be trivial, in which case we shouldn't
817 // perform the combine.
818 if (LR.first != &IE && LR.second != &IE) {
819 // We now have a shuffle of LHS, RHS, Mask.
Craig Topperf40110f2014-04-25 05:29:35 +0000820 if (LR.second == nullptr)
821 LR.second = UndefValue::get(LR.first->getType());
Tim Northoverfad27612014-03-07 10:24:44 +0000822 return new ShuffleVectorInst(LR.first, LR.second,
823 ConstantVector::get(Mask));
824 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000825 }
826 }
827 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000828
Craig Topper17b55682016-12-29 07:03:18 +0000829 unsigned VWidth = VecOp->getType()->getVectorNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +0000830 APInt UndefElts(VWidth, 0);
831 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +0000832 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
833 if (V != &IE)
Sanjay Patel4b198802016-02-01 22:23:39 +0000834 return replaceInstUsesWith(IE, V);
Chris Lattnerec97a902010-01-05 05:36:20 +0000835 return &IE;
Eli Friedmanef200db2011-02-19 22:42:40 +0000836 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000837
Sanjay Patel521f19f2016-09-02 17:05:43 +0000838 if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE))
839 return Shuf;
840
Craig Topperbb4069e2017-07-07 23:16:26 +0000841 if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder))
Sanjay Patel2f602ce2017-03-22 17:10:44 +0000842 return NewInsElt;
843
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000844 // Turn a sequence of inserts that broadcasts a scalar into a single
845 // insert + shufflevector.
846 if (Instruction *Broadcast = foldInsSequenceIntoBroadcast(IE))
847 return Broadcast;
848
Craig Topperf40110f2014-04-25 05:29:35 +0000849 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000850}
851
Nick Lewyckya2b77202013-05-31 00:59:42 +0000852/// Return true if we can evaluate the specified expression tree if the vector
853/// elements were shuffled in a different order.
854static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask,
Nick Lewycky3f715e22013-06-01 20:51:31 +0000855 unsigned Depth = 5) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000856 // We can always reorder the elements of a constant.
857 if (isa<Constant>(V))
858 return true;
859
860 // We won't reorder vector arguments. No IPO here.
861 Instruction *I = dyn_cast<Instruction>(V);
862 if (!I) return false;
863
864 // Two users may expect different orders of the elements. Don't try it.
865 if (!I->hasOneUse())
866 return false;
867
868 if (Depth == 0) return false;
869
870 switch (I->getOpcode()) {
871 case Instruction::Add:
872 case Instruction::FAdd:
873 case Instruction::Sub:
874 case Instruction::FSub:
875 case Instruction::Mul:
876 case Instruction::FMul:
877 case Instruction::UDiv:
878 case Instruction::SDiv:
879 case Instruction::FDiv:
880 case Instruction::URem:
881 case Instruction::SRem:
882 case Instruction::FRem:
883 case Instruction::Shl:
884 case Instruction::LShr:
885 case Instruction::AShr:
886 case Instruction::And:
887 case Instruction::Or:
888 case Instruction::Xor:
889 case Instruction::ICmp:
890 case Instruction::FCmp:
891 case Instruction::Trunc:
892 case Instruction::ZExt:
893 case Instruction::SExt:
894 case Instruction::FPToUI:
895 case Instruction::FPToSI:
896 case Instruction::UIToFP:
897 case Instruction::SIToFP:
898 case Instruction::FPTrunc:
899 case Instruction::FPExt:
900 case Instruction::GetElementPtr: {
Sanjay Patel4e28753142015-11-16 22:16:52 +0000901 for (Value *Operand : I->operands()) {
902 if (!CanEvaluateShuffled(Operand, Mask, Depth-1))
Nick Lewyckya2b77202013-05-31 00:59:42 +0000903 return false;
904 }
905 return true;
906 }
907 case Instruction::InsertElement: {
908 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
909 if (!CI) return false;
910 int ElementNumber = CI->getLimitedValue();
911
912 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
913 // can't put an element into multiple indices.
914 bool SeenOnce = false;
915 for (int i = 0, e = Mask.size(); i != e; ++i) {
916 if (Mask[i] == ElementNumber) {
917 if (SeenOnce)
918 return false;
919 SeenOnce = true;
920 }
921 }
922 return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1);
923 }
924 }
925 return false;
926}
927
928/// Rebuild a new instruction just like 'I' but with the new operands given.
929/// In the event of type mismatch, the type of the operands is correct.
Sanjay Patel431e1142015-11-17 17:24:08 +0000930static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
Nick Lewyckya2b77202013-05-31 00:59:42 +0000931 // We don't want to use the IRBuilder here because we want the replacement
932 // instructions to appear next to 'I', not the builder's insertion point.
933 switch (I->getOpcode()) {
934 case Instruction::Add:
935 case Instruction::FAdd:
936 case Instruction::Sub:
937 case Instruction::FSub:
938 case Instruction::Mul:
939 case Instruction::FMul:
940 case Instruction::UDiv:
941 case Instruction::SDiv:
942 case Instruction::FDiv:
943 case Instruction::URem:
944 case Instruction::SRem:
945 case Instruction::FRem:
946 case Instruction::Shl:
947 case Instruction::LShr:
948 case Instruction::AShr:
949 case Instruction::And:
950 case Instruction::Or:
951 case Instruction::Xor: {
952 BinaryOperator *BO = cast<BinaryOperator>(I);
953 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
954 BinaryOperator *New =
955 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
956 NewOps[0], NewOps[1], "", BO);
957 if (isa<OverflowingBinaryOperator>(BO)) {
958 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
959 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
960 }
961 if (isa<PossiblyExactOperator>(BO)) {
962 New->setIsExact(BO->isExact());
963 }
Owen Anderson48b842e2014-01-18 00:48:14 +0000964 if (isa<FPMathOperator>(BO))
965 New->copyFastMathFlags(I);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000966 return New;
967 }
968 case Instruction::ICmp:
969 assert(NewOps.size() == 2 && "icmp with #ops != 2");
970 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
971 NewOps[0], NewOps[1]);
972 case Instruction::FCmp:
973 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
974 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
975 NewOps[0], NewOps[1]);
976 case Instruction::Trunc:
977 case Instruction::ZExt:
978 case Instruction::SExt:
979 case Instruction::FPToUI:
980 case Instruction::FPToSI:
981 case Instruction::UIToFP:
982 case Instruction::SIToFP:
983 case Instruction::FPTrunc:
984 case Instruction::FPExt: {
985 // It's possible that the mask has a different number of elements from
986 // the original cast. We recompute the destination type to match the mask.
987 Type *DestTy =
988 VectorType::get(I->getType()->getScalarType(),
989 NewOps[0]->getType()->getVectorNumElements());
990 assert(NewOps.size() == 1 && "cast with #ops != 1");
991 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
992 "", I);
993 }
994 case Instruction::GetElementPtr: {
995 Value *Ptr = NewOps[0];
996 ArrayRef<Value*> Idx = NewOps.slice(1);
David Blaikie22319eb2015-03-14 19:24:04 +0000997 GetElementPtrInst *GEP = GetElementPtrInst::Create(
998 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
Nick Lewyckya2b77202013-05-31 00:59:42 +0000999 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
1000 return GEP;
1001 }
1002 }
1003 llvm_unreachable("failed to rebuild vector instructions");
1004}
1005
1006Value *
1007InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
1008 // Mask.size() does not need to be equal to the number of vector elements.
1009
1010 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
Sanjay Patelce36b032017-10-09 17:54:46 +00001011 Type *EltTy = V->getType()->getScalarType();
1012 if (isa<UndefValue>(V))
1013 return UndefValue::get(VectorType::get(EltTy, Mask.size()));
1014
1015 if (isa<ConstantAggregateZero>(V))
1016 return ConstantAggregateZero::get(VectorType::get(EltTy, Mask.size()));
1017
Nick Lewyckya2b77202013-05-31 00:59:42 +00001018 if (Constant *C = dyn_cast<Constant>(V)) {
1019 SmallVector<Constant *, 16> MaskValues;
1020 for (int i = 0, e = Mask.size(); i != e; ++i) {
1021 if (Mask[i] == -1)
Craig Topperbb4069e2017-07-07 23:16:26 +00001022 MaskValues.push_back(UndefValue::get(Builder.getInt32Ty()));
Nick Lewyckya2b77202013-05-31 00:59:42 +00001023 else
Craig Topperbb4069e2017-07-07 23:16:26 +00001024 MaskValues.push_back(Builder.getInt32(Mask[i]));
Nick Lewyckya2b77202013-05-31 00:59:42 +00001025 }
1026 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
1027 ConstantVector::get(MaskValues));
1028 }
1029
1030 Instruction *I = cast<Instruction>(V);
1031 switch (I->getOpcode()) {
1032 case Instruction::Add:
1033 case Instruction::FAdd:
1034 case Instruction::Sub:
1035 case Instruction::FSub:
1036 case Instruction::Mul:
1037 case Instruction::FMul:
1038 case Instruction::UDiv:
1039 case Instruction::SDiv:
1040 case Instruction::FDiv:
1041 case Instruction::URem:
1042 case Instruction::SRem:
1043 case Instruction::FRem:
1044 case Instruction::Shl:
1045 case Instruction::LShr:
1046 case Instruction::AShr:
1047 case Instruction::And:
1048 case Instruction::Or:
1049 case Instruction::Xor:
1050 case Instruction::ICmp:
1051 case Instruction::FCmp:
1052 case Instruction::Trunc:
1053 case Instruction::ZExt:
1054 case Instruction::SExt:
1055 case Instruction::FPToUI:
1056 case Instruction::FPToSI:
1057 case Instruction::UIToFP:
1058 case Instruction::SIToFP:
1059 case Instruction::FPTrunc:
1060 case Instruction::FPExt:
1061 case Instruction::Select:
1062 case Instruction::GetElementPtr: {
1063 SmallVector<Value*, 8> NewOps;
1064 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
1065 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
1066 Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask);
1067 NewOps.push_back(V);
1068 NeedsRebuild |= (V != I->getOperand(i));
1069 }
1070 if (NeedsRebuild) {
Sanjay Patel431e1142015-11-17 17:24:08 +00001071 return buildNew(I, NewOps);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001072 }
1073 return I;
1074 }
1075 case Instruction::InsertElement: {
1076 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
Nick Lewyckya2b77202013-05-31 00:59:42 +00001077
1078 // The insertelement was inserting at Element. Figure out which element
1079 // that becomes after shuffling. The answer is guaranteed to be unique
1080 // by CanEvaluateShuffled.
Nick Lewycky3f715e22013-06-01 20:51:31 +00001081 bool Found = false;
Nick Lewyckya2b77202013-05-31 00:59:42 +00001082 int Index = 0;
Nick Lewycky3f715e22013-06-01 20:51:31 +00001083 for (int e = Mask.size(); Index != e; ++Index) {
1084 if (Mask[Index] == Element) {
1085 Found = true;
Nick Lewyckya2b77202013-05-31 00:59:42 +00001086 break;
Nick Lewycky3f715e22013-06-01 20:51:31 +00001087 }
1088 }
Nick Lewyckya2b77202013-05-31 00:59:42 +00001089
Hao Liu26abebb2014-01-08 03:06:15 +00001090 // If element is not in Mask, no need to handle the operand 1 (element to
1091 // be inserted). Just evaluate values in operand 0 according to Mask.
Nick Lewycky3f715e22013-06-01 20:51:31 +00001092 if (!Found)
Hao Liu26abebb2014-01-08 03:06:15 +00001093 return EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
Joey Goulya3250f22013-07-12 23:08:06 +00001094
Nick Lewyckya2b77202013-05-31 00:59:42 +00001095 Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask);
1096 return InsertElementInst::Create(V, I->getOperand(1),
Craig Topperbb4069e2017-07-07 23:16:26 +00001097 Builder.getInt32(Index), "", I);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001098 }
1099 }
1100 llvm_unreachable("failed to reorder elements of vector instruction!");
1101}
Chris Lattnerec97a902010-01-05 05:36:20 +00001102
Sanjay Patel431e1142015-11-17 17:24:08 +00001103static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask,
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001104 bool &isLHSID, bool &isRHSID) {
1105 isLHSID = isRHSID = true;
1106
1107 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
1108 if (Mask[i] < 0) continue; // Ignore undef values.
1109 // Is this an identity shuffle of the LHS value?
1110 isLHSID &= (Mask[i] == (int)i);
1111
1112 // Is this an identity shuffle of the RHS value?
1113 isRHSID &= (Mask[i]-e == i);
1114 }
1115}
1116
JF Bastiend52c9902015-02-25 22:30:51 +00001117// Returns true if the shuffle is extracting a contiguous range of values from
1118// LHS, for example:
1119// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1120// Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
1121// Shuffles to: |EE|FF|GG|HH|
1122// +--+--+--+--+
1123static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
1124 SmallVector<int, 16> &Mask) {
Craig Topper17b55682016-12-29 07:03:18 +00001125 unsigned LHSElems = SVI.getOperand(0)->getType()->getVectorNumElements();
JF Bastiend52c9902015-02-25 22:30:51 +00001126 unsigned MaskElems = Mask.size();
1127 unsigned BegIdx = Mask.front();
1128 unsigned EndIdx = Mask.back();
1129 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
1130 return false;
1131 for (unsigned I = 0; I != MaskElems; ++I)
1132 if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
1133 return false;
1134 return true;
1135}
1136
Chris Lattnerec97a902010-01-05 05:36:20 +00001137Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
1138 Value *LHS = SVI.getOperand(0);
1139 Value *RHS = SVI.getOperand(1);
Chris Lattner8326bd82012-01-26 00:42:34 +00001140 SmallVector<int, 16> Mask = SVI.getShuffleMask();
JF Bastiend52c9902015-02-25 22:30:51 +00001141 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001142
Craig Toppera4205622017-06-09 03:21:29 +00001143 if (auto *V = SimplifyShuffleVectorInst(
1144 LHS, RHS, SVI.getMask(), SVI.getType(), SQ.getWithInstruction(&SVI)))
Zvi Rackover82bf48d2017-04-04 04:47:57 +00001145 return replaceInstUsesWith(SVI, V);
1146
Chris Lattnerec97a902010-01-05 05:36:20 +00001147 bool MadeChange = false;
Craig Topper17b55682016-12-29 07:03:18 +00001148 unsigned VWidth = SVI.getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001149
Chris Lattnerec97a902010-01-05 05:36:20 +00001150 APInt UndefElts(VWidth, 0);
1151 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +00001152 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
1153 if (V != &SVI)
Sanjay Patel4b198802016-02-01 22:23:39 +00001154 return replaceInstUsesWith(SVI, V);
Sanjay Patele6b48a12017-08-31 15:57:17 +00001155 return &SVI;
Chris Lattnerec97a902010-01-05 05:36:20 +00001156 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001157
Craig Topper17b55682016-12-29 07:03:18 +00001158 unsigned LHSWidth = LHS->getType()->getVectorNumElements();
Eli Friedmance818272011-10-21 19:06:29 +00001159
Chris Lattnerec97a902010-01-05 05:36:20 +00001160 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
1161 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
1162 if (LHS == RHS || isa<UndefValue>(LHS)) {
Eric Christopher51edc7b2010-08-17 22:55:27 +00001163 if (isa<UndefValue>(LHS) && LHS == RHS) {
1164 // shuffle(undef,undef,mask) -> undef.
Nick Lewyckya2b77202013-05-31 00:59:42 +00001165 Value *Result = (VWidth == LHSWidth)
Eli Friedmance818272011-10-21 19:06:29 +00001166 ? LHS : UndefValue::get(SVI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +00001167 return replaceInstUsesWith(SVI, Result);
Eric Christopher51edc7b2010-08-17 22:55:27 +00001168 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001169
Chris Lattnerec97a902010-01-05 05:36:20 +00001170 // Remap any references to RHS to use LHS.
Chris Lattner0256be92012-01-27 03:08:05 +00001171 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +00001172 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) {
Chris Lattner0256be92012-01-27 03:08:05 +00001173 if (Mask[i] < 0) {
JF Bastiend52c9902015-02-25 22:30:51 +00001174 Elts.push_back(UndefValue::get(Int32Ty));
Chris Lattner0256be92012-01-27 03:08:05 +00001175 continue;
1176 }
1177
1178 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) ||
1179 (Mask[i] < (int)e && isa<UndefValue>(LHS))) {
1180 Mask[i] = -1; // Turn into undef.
JF Bastiend52c9902015-02-25 22:30:51 +00001181 Elts.push_back(UndefValue::get(Int32Ty));
Chris Lattner0256be92012-01-27 03:08:05 +00001182 } else {
1183 Mask[i] = Mask[i] % e; // Force to LHS.
JF Bastiend52c9902015-02-25 22:30:51 +00001184 Elts.push_back(ConstantInt::get(Int32Ty, Mask[i]));
Chris Lattnerec97a902010-01-05 05:36:20 +00001185 }
1186 }
1187 SVI.setOperand(0, SVI.getOperand(1));
1188 SVI.setOperand(1, UndefValue::get(RHS->getType()));
1189 SVI.setOperand(2, ConstantVector::get(Elts));
1190 LHS = SVI.getOperand(0);
1191 RHS = SVI.getOperand(1);
1192 MadeChange = true;
1193 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001194
Eli Friedmance818272011-10-21 19:06:29 +00001195 if (VWidth == LHSWidth) {
1196 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001197 bool isLHSID, isRHSID;
Sanjay Patel431e1142015-11-17 17:24:08 +00001198 recognizeIdentityMask(Mask, isLHSID, isRHSID);
Eli Friedmance818272011-10-21 19:06:29 +00001199
1200 // Eliminate identity shuffles.
Sanjay Patel4b198802016-02-01 22:23:39 +00001201 if (isLHSID) return replaceInstUsesWith(SVI, LHS);
1202 if (isRHSID) return replaceInstUsesWith(SVI, RHS);
Eric Christopher51edc7b2010-08-17 22:55:27 +00001203 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001204
Nick Lewycky688d6682013-06-03 23:15:20 +00001205 if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) {
Nick Lewyckya2b77202013-05-31 00:59:42 +00001206 Value *V = EvaluateInDifferentElementOrder(LHS, Mask);
Sanjay Patel4b198802016-02-01 22:23:39 +00001207 return replaceInstUsesWith(SVI, V);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001208 }
1209
JF Bastiend52c9902015-02-25 22:30:51 +00001210 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
1211 // a non-vector type. We can instead bitcast the original vector followed by
1212 // an extract of the desired element:
1213 //
1214 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
1215 // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
1216 // %1 = bitcast <4 x i8> %sroa to i32
1217 // Becomes:
1218 // %bc = bitcast <16 x i8> %in to <4 x i32>
1219 // %ext = extractelement <4 x i32> %bc, i32 0
1220 //
1221 // If the shuffle is extracting a contiguous range of values from the input
1222 // vector then each use which is a bitcast of the extracted size can be
1223 // replaced. This will work if the vector types are compatible, and the begin
1224 // index is aligned to a value in the casted vector type. If the begin index
1225 // isn't aligned then we can shuffle the original vector (keeping the same
1226 // vector type) before extracting.
1227 //
1228 // This code will bail out if the target type is fundamentally incompatible
1229 // with vectors of the source type.
1230 //
1231 // Example of <16 x i8>, target type i32:
1232 // Index range [4,8): v-----------v Will work.
1233 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1234 // <16 x i8>: | | | | | | | | | | | | | | | | |
1235 // <4 x i32>: | | | | |
1236 // +-----------+-----------+-----------+-----------+
1237 // Index range [6,10): ^-----------^ Needs an extra shuffle.
1238 // Target type i40: ^--------------^ Won't work, bail.
1239 if (isShuffleExtractingFromLHS(SVI, Mask)) {
1240 Value *V = LHS;
1241 unsigned MaskElems = Mask.size();
JF Bastiend52c9902015-02-25 22:30:51 +00001242 VectorType *SrcTy = cast<VectorType>(V->getType());
1243 unsigned VecBitWidth = SrcTy->getBitWidth();
David Majnemer98cfe2b2015-04-03 20:18:40 +00001244 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
JF Bastiend52c9902015-02-25 22:30:51 +00001245 assert(SrcElemBitWidth && "vector elements must have a bitwidth");
1246 unsigned SrcNumElems = SrcTy->getNumElements();
1247 SmallVector<BitCastInst *, 8> BCs;
1248 DenseMap<Type *, Value *> NewBCs;
1249 for (User *U : SVI.users())
1250 if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
1251 if (!BC->use_empty())
1252 // Only visit bitcasts that weren't previously handled.
1253 BCs.push_back(BC);
1254 for (BitCastInst *BC : BCs) {
Eugene Leviant958fcd72017-02-17 07:36:03 +00001255 unsigned BegIdx = Mask.front();
JF Bastiend52c9902015-02-25 22:30:51 +00001256 Type *TgtTy = BC->getDestTy();
David Majnemer98cfe2b2015-04-03 20:18:40 +00001257 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
JF Bastiend52c9902015-02-25 22:30:51 +00001258 if (!TgtElemBitWidth)
1259 continue;
1260 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
1261 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
1262 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
1263 if (!VecBitWidthsEqual)
1264 continue;
1265 if (!VectorType::isValidElementType(TgtTy))
1266 continue;
1267 VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
1268 if (!BegIsAligned) {
1269 // Shuffle the input so [0,NumElements) contains the output, and
1270 // [NumElems,SrcNumElems) is undef.
1271 SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
1272 UndefValue::get(Int32Ty));
1273 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
1274 ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
Craig Topperbb4069e2017-07-07 23:16:26 +00001275 V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
1276 ConstantVector::get(ShuffleMask),
1277 SVI.getName() + ".extract");
JF Bastiend52c9902015-02-25 22:30:51 +00001278 BegIdx = 0;
1279 }
1280 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
1281 assert(SrcElemsPerTgtElem);
1282 BegIdx /= SrcElemsPerTgtElem;
1283 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
1284 auto *NewBC =
1285 BCAlreadyExists
1286 ? NewBCs[CastSrcTy]
Craig Topperbb4069e2017-07-07 23:16:26 +00001287 : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
JF Bastiend52c9902015-02-25 22:30:51 +00001288 if (!BCAlreadyExists)
1289 NewBCs[CastSrcTy] = NewBC;
Craig Topperbb4069e2017-07-07 23:16:26 +00001290 auto *Ext = Builder.CreateExtractElement(
JF Bastiend52c9902015-02-25 22:30:51 +00001291 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
1292 // The shufflevector isn't being replaced: the bitcast that used it
1293 // is. InstCombine will visit the newly-created instructions.
Sanjay Patel4b198802016-02-01 22:23:39 +00001294 replaceInstUsesWith(*BC, Ext);
JF Bastiend52c9902015-02-25 22:30:51 +00001295 MadeChange = true;
1296 }
1297 }
1298
Eric Christopher51edc7b2010-08-17 22:55:27 +00001299 // If the LHS is a shufflevector itself, see if we can combine it with this
Eli Friedmance818272011-10-21 19:06:29 +00001300 // one without producing an unusual shuffle.
1301 // Cases that might be simplified:
1302 // 1.
1303 // x1=shuffle(v1,v2,mask1)
1304 // x=shuffle(x1,undef,mask)
1305 // ==>
1306 // x=shuffle(v1,undef,newMask)
1307 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
1308 // 2.
1309 // x1=shuffle(v1,undef,mask1)
1310 // x=shuffle(x1,x2,mask)
1311 // where v1.size() == mask1.size()
1312 // ==>
1313 // x=shuffle(v1,x2,newMask)
1314 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
1315 // 3.
1316 // x2=shuffle(v2,undef,mask2)
1317 // x=shuffle(x1,x2,mask)
1318 // where v2.size() == mask2.size()
1319 // ==>
1320 // x=shuffle(x1,v2,newMask)
1321 // newMask[i] = (mask[i] < x1.size())
1322 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
1323 // 4.
1324 // x1=shuffle(v1,undef,mask1)
1325 // x2=shuffle(v2,undef,mask2)
1326 // x=shuffle(x1,x2,mask)
1327 // where v1.size() == v2.size()
1328 // ==>
1329 // x=shuffle(v1,v2,newMask)
1330 // newMask[i] = (mask[i] < x1.size())
1331 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
1332 //
1333 // Here we are really conservative:
Eric Christopher51edc7b2010-08-17 22:55:27 +00001334 // we are absolutely afraid of producing a shuffle mask not in the input
1335 // program, because the code gen may not be smart enough to turn a merged
1336 // shuffle into two specific shuffles: it may produce worse code. As such,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001337 // we only merge two shuffles if the result is either a splat or one of the
1338 // input shuffle masks. In this case, merging the shuffles just removes
1339 // one instruction, which we know is safe. This is good for things like
Eli Friedmance818272011-10-21 19:06:29 +00001340 // turning: (splat(splat)) -> splat, or
1341 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
1342 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
1343 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
1344 if (LHSShuffle)
1345 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
Craig Topperf40110f2014-04-25 05:29:35 +00001346 LHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001347 if (RHSShuffle)
1348 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +00001349 RHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001350 if (!LHSShuffle && !RHSShuffle)
Craig Topperf40110f2014-04-25 05:29:35 +00001351 return MadeChange ? &SVI : nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001352
Craig Topperf40110f2014-04-25 05:29:35 +00001353 Value* LHSOp0 = nullptr;
1354 Value* LHSOp1 = nullptr;
1355 Value* RHSOp0 = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001356 unsigned LHSOp0Width = 0;
1357 unsigned RHSOp0Width = 0;
1358 if (LHSShuffle) {
1359 LHSOp0 = LHSShuffle->getOperand(0);
1360 LHSOp1 = LHSShuffle->getOperand(1);
Craig Topper17b55682016-12-29 07:03:18 +00001361 LHSOp0Width = LHSOp0->getType()->getVectorNumElements();
Eli Friedmance818272011-10-21 19:06:29 +00001362 }
1363 if (RHSShuffle) {
1364 RHSOp0 = RHSShuffle->getOperand(0);
Craig Topper17b55682016-12-29 07:03:18 +00001365 RHSOp0Width = RHSOp0->getType()->getVectorNumElements();
Eli Friedmance818272011-10-21 19:06:29 +00001366 }
1367 Value* newLHS = LHS;
1368 Value* newRHS = RHS;
1369 if (LHSShuffle) {
1370 // case 1
Eric Christopher51edc7b2010-08-17 22:55:27 +00001371 if (isa<UndefValue>(RHS)) {
Eli Friedmance818272011-10-21 19:06:29 +00001372 newLHS = LHSOp0;
1373 newRHS = LHSOp1;
1374 }
1375 // case 2 or 4
1376 else if (LHSOp0Width == LHSWidth) {
1377 newLHS = LHSOp0;
1378 }
1379 }
1380 // case 3 or 4
1381 if (RHSShuffle && RHSOp0Width == LHSWidth) {
1382 newRHS = RHSOp0;
1383 }
1384 // case 4
1385 if (LHSOp0 == RHSOp0) {
1386 newLHS = LHSOp0;
Craig Topperf40110f2014-04-25 05:29:35 +00001387 newRHS = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00001388 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001389
Eli Friedmance818272011-10-21 19:06:29 +00001390 if (newLHS == LHS && newRHS == RHS)
Craig Topperf40110f2014-04-25 05:29:35 +00001391 return MadeChange ? &SVI : nullptr;
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001392
Eli Friedmance818272011-10-21 19:06:29 +00001393 SmallVector<int, 16> LHSMask;
1394 SmallVector<int, 16> RHSMask;
Chris Lattner8326bd82012-01-26 00:42:34 +00001395 if (newLHS != LHS)
1396 LHSMask = LHSShuffle->getShuffleMask();
1397 if (RHSShuffle && newRHS != RHS)
1398 RHSMask = RHSShuffle->getShuffleMask();
1399
Eli Friedmance818272011-10-21 19:06:29 +00001400 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
1401 SmallVector<int, 16> newMask;
1402 bool isSplat = true;
1403 int SplatElt = -1;
1404 // Create a new mask for the new ShuffleVectorInst so that the new
1405 // ShuffleVectorInst is equivalent to the original one.
1406 for (unsigned i = 0; i < VWidth; ++i) {
1407 int eltMask;
Craig Topper45d9f4b2013-01-18 05:30:07 +00001408 if (Mask[i] < 0) {
Eli Friedmance818272011-10-21 19:06:29 +00001409 // This element is an undef value.
1410 eltMask = -1;
1411 } else if (Mask[i] < (int)LHSWidth) {
1412 // This element is from left hand side vector operand.
Craig Topper2ea22b02013-01-18 05:09:16 +00001413 //
Eli Friedmance818272011-10-21 19:06:29 +00001414 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
1415 // new mask value for the element.
1416 if (newLHS != LHS) {
1417 eltMask = LHSMask[Mask[i]];
1418 // If the value selected is an undef value, explicitly specify it
1419 // with a -1 mask value.
1420 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
1421 eltMask = -1;
Craig Topper2ea22b02013-01-18 05:09:16 +00001422 } else
Eli Friedmance818272011-10-21 19:06:29 +00001423 eltMask = Mask[i];
1424 } else {
1425 // This element is from right hand side vector operand
1426 //
1427 // If the value selected is an undef value, explicitly specify it
1428 // with a -1 mask value. (case 1)
1429 if (isa<UndefValue>(RHS))
1430 eltMask = -1;
1431 // If RHS is going to be replaced (case 3 or 4), calculate the
1432 // new mask value for the element.
1433 else if (newRHS != RHS) {
1434 eltMask = RHSMask[Mask[i]-LHSWidth];
1435 // If the value selected is an undef value, explicitly specify it
1436 // with a -1 mask value.
1437 if (eltMask >= (int)RHSOp0Width) {
1438 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
1439 && "should have been check above");
1440 eltMask = -1;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001441 }
Craig Topper2ea22b02013-01-18 05:09:16 +00001442 } else
Eli Friedmance818272011-10-21 19:06:29 +00001443 eltMask = Mask[i]-LHSWidth;
1444
1445 // If LHS's width is changed, shift the mask value accordingly.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00001446 // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any
Michael Gottesman02a11412012-10-16 21:29:38 +00001447 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
1448 // If newRHS == newLHS, we want to remap any references from newRHS to
1449 // newLHS so that we can properly identify splats that may occur due to
Alp Tokercb402912014-01-24 17:20:08 +00001450 // obfuscation across the two vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00001451 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001452 eltMask += newLHSWidth;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001453 }
Eli Friedmance818272011-10-21 19:06:29 +00001454
1455 // Check if this could still be a splat.
1456 if (eltMask >= 0) {
1457 if (SplatElt >= 0 && SplatElt != eltMask)
1458 isSplat = false;
1459 SplatElt = eltMask;
1460 }
1461
1462 newMask.push_back(eltMask);
1463 }
1464
1465 // If the result mask is equal to one of the original shuffle masks,
Jim Grosbachd11584a2013-05-01 00:25:27 +00001466 // or is a splat, do the replacement.
1467 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
Eli Friedmance818272011-10-21 19:06:29 +00001468 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +00001469 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
1470 if (newMask[i] < 0) {
1471 Elts.push_back(UndefValue::get(Int32Ty));
1472 } else {
1473 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
1474 }
1475 }
Craig Topperf40110f2014-04-25 05:29:35 +00001476 if (!newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00001477 newRHS = UndefValue::get(newLHS->getType());
1478 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00001479 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001480
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001481 // If the result mask is an identity, replace uses of this instruction with
1482 // corresponding argument.
Serge Pavlovb575ee82014-05-13 06:07:21 +00001483 bool isLHSID, isRHSID;
Sanjay Patel431e1142015-11-17 17:24:08 +00001484 recognizeIdentityMask(newMask, isLHSID, isRHSID);
Sanjay Patel4b198802016-02-01 22:23:39 +00001485 if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS);
1486 if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS);
Serge Pavlov9ef66a82014-05-11 08:46:12 +00001487
Craig Topperf40110f2014-04-25 05:29:35 +00001488 return MadeChange ? &SVI : nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +00001489}