blob: a5f41e43f9ebc194404d4c2bd843335dd778abe7 [file] [log] [blame]
Chris Lattnerec97a902010-01-05 05:36:20 +00001//===- InstCombineVectorOps.cpp -------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnerec97a902010-01-05 05:36:20 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements instcombine for ExtractElement, InsertElement and
10// ShuffleVector.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000015#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
JF Bastiend52c9902015-02-25 22:30:51 +000017#include "llvm/ADT/DenseMap.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000018#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallVector.h"
David Majnemer599ca442015-07-13 01:15:53 +000020#include "llvm/Analysis/InstructionSimplify.h"
21#include "llvm/Analysis/VectorUtils.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000022#include "llvm/IR/BasicBlock.h"
23#include "llvm/IR/Constant.h"
24#include "llvm/IR/Constants.h"
25#include "llvm/IR/DerivedTypes.h"
26#include "llvm/IR/InstrTypes.h"
27#include "llvm/IR/Instruction.h"
28#include "llvm/IR/Instructions.h"
29#include "llvm/IR/Operator.h"
Chandler Carruth820a9082014-03-04 11:08:18 +000030#include "llvm/IR/PatternMatch.h"
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +000031#include "llvm/IR/Type.h"
32#include "llvm/IR/User.h"
33#include "llvm/IR/Value.h"
34#include "llvm/Support/Casting.h"
35#include "llvm/Support/ErrorHandling.h"
36#include "llvm/Transforms/InstCombine/InstCombineWorklist.h"
37#include <cassert>
38#include <cstdint>
39#include <iterator>
40#include <utility>
41
Chris Lattnerec97a902010-01-05 05:36:20 +000042using namespace llvm;
Nadav Rotem7df85092013-01-15 23:43:14 +000043using namespace PatternMatch;
Chris Lattnerec97a902010-01-05 05:36:20 +000044
Chandler Carruth964daaa2014-04-22 02:55:47 +000045#define DEBUG_TYPE "instcombine"
46
Sanjay Patel6eccf482015-09-09 15:24:36 +000047/// Return true if the value is cheaper to scalarize than it is to leave as a
Sanjay Patele51d5bd2018-12-18 19:07:38 +000048/// vector operation. IsConstantExtractIndex indicates whether we are extracting
49/// one known element from a vector constant.
50///
51/// FIXME: It's possible to create more instructions than previously existed.
52static bool cheapToScalarize(Value *V, bool IsConstantExtractIndex) {
53 // If we can pick a scalar constant value out of a vector, that is free.
54 if (auto *C = dyn_cast<Constant>(V))
55 return IsConstantExtractIndex || C->getSplatValue();
Chris Lattner8326bd82012-01-26 00:42:34 +000056
Sanjay Patele51d5bd2018-12-18 19:07:38 +000057 // An insertelement to the same constant index as our extract will simplify
58 // to the scalar inserted element. An insertelement to a different constant
59 // index is irrelevant to our extract.
60 if (match(V, m_InsertElement(m_Value(), m_Value(), m_ConstantInt())))
61 return IsConstantExtractIndex;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000062
Sanjay Patele51d5bd2018-12-18 19:07:38 +000063 if (match(V, m_OneUse(m_Load(m_Value()))))
Chris Lattnerec97a902010-01-05 05:36:20 +000064 return true;
Sanjay Patele51d5bd2018-12-18 19:07:38 +000065
66 Value *V0, *V1;
67 if (match(V, m_OneUse(m_BinOp(m_Value(V0), m_Value(V1)))))
68 if (cheapToScalarize(V0, IsConstantExtractIndex) ||
69 cheapToScalarize(V1, IsConstantExtractIndex))
Chris Lattnerec97a902010-01-05 05:36:20 +000070 return true;
Sanjay Patele51d5bd2018-12-18 19:07:38 +000071
72 CmpInst::Predicate UnusedPred;
73 if (match(V, m_OneUse(m_Cmp(UnusedPred, m_Value(V0), m_Value(V1)))))
74 if (cheapToScalarize(V0, IsConstantExtractIndex) ||
75 cheapToScalarize(V1, IsConstantExtractIndex))
Chris Lattnerec97a902010-01-05 05:36:20 +000076 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +000077
Chris Lattnerec97a902010-01-05 05:36:20 +000078 return false;
79}
80
Michael Kupersteina0c6ae02016-06-06 23:38:33 +000081// If we have a PHI node with a vector type that is only used to feed
Matt Arsenault38874732013-08-28 22:17:26 +000082// itself and be an operand of extractelement at a constant location,
83// try to replace the PHI of the vector type with a PHI of a scalar type.
Anat Shemer0c95efa2013-04-18 19:35:39 +000084Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) {
Michael Kupersteina0c6ae02016-06-06 23:38:33 +000085 SmallVector<Instruction *, 2> Extracts;
86 // The users we want the PHI to have are:
87 // 1) The EI ExtractElement (we already know this)
88 // 2) Possibly more ExtractElements with the same index.
89 // 3) Another operand, which will feed back into the PHI.
90 Instruction *PHIUser = nullptr;
91 for (auto U : PN->users()) {
92 if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
93 if (EI.getIndexOperand() == EU->getIndexOperand())
94 Extracts.push_back(EU);
95 else
96 return nullptr;
97 } else if (!PHIUser) {
98 PHIUser = cast<Instruction>(U);
99 } else {
100 return nullptr;
101 }
102 }
Anat Shemer0c95efa2013-04-18 19:35:39 +0000103
Michael Kupersteina0c6ae02016-06-06 23:38:33 +0000104 if (!PHIUser)
105 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000106
107 // Verify that this PHI user has one use, which is the PHI itself,
108 // and that it is a binary operation which is cheap to scalarize.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000109 // otherwise return nullptr.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000110 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
Sanjay Patel431e1142015-11-17 17:24:08 +0000111 !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true))
Craig Topperf40110f2014-04-25 05:29:35 +0000112 return nullptr;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000113
114 // Create a scalar PHI node that will replace the vector PHI node
115 // just before the current PHI node.
Joey Goulyb34294d2013-05-24 12:33:28 +0000116 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
117 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
Anat Shemer0c95efa2013-04-18 19:35:39 +0000118 // Scalarize each PHI operand.
Joey Goulyb34294d2013-05-24 12:33:28 +0000119 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
Anat Shemer0c95efa2013-04-18 19:35:39 +0000120 Value *PHIInVal = PN->getIncomingValue(i);
121 BasicBlock *inBB = PN->getIncomingBlock(i);
122 Value *Elt = EI.getIndexOperand();
123 // If the operand is the PHI induction variable:
124 if (PHIInVal == PHIUser) {
125 // Scalarize the binary operation. Its first operand is the
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000126 // scalar PHI, and the second operand is extracted from the other
Anat Shemer0c95efa2013-04-18 19:35:39 +0000127 // vector operand.
128 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
Joey Goulyb34294d2013-05-24 12:33:28 +0000129 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
Joey Gouly83699282013-05-24 12:29:54 +0000130 Value *Op = InsertNewInstWith(
131 ExtractElementInst::Create(B0->getOperand(opId), Elt,
132 B0->getOperand(opId)->getName() + ".Elt"),
133 *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000134 Value *newPHIUser = InsertNewInstWith(
Owen Anderson7ea02fc2016-03-01 19:35:52 +0000135 BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
136 scalarPHI, Op, B0), *B0);
Anat Shemer0c95efa2013-04-18 19:35:39 +0000137 scalarPHI->addIncoming(newPHIUser, inBB);
138 } else {
139 // Scalarize PHI input:
Joey Goulyb34294d2013-05-24 12:33:28 +0000140 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
Anat Shemer0c95efa2013-04-18 19:35:39 +0000141 // Insert the new instruction into the predecessor basic block.
142 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
143 BasicBlock::iterator InsertPos;
144 if (pos && !isa<PHINode>(pos)) {
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000145 InsertPos = ++pos->getIterator();
Anat Shemer0c95efa2013-04-18 19:35:39 +0000146 } else {
147 InsertPos = inBB->getFirstInsertionPt();
148 }
149
150 InsertNewInstWith(newEI, *InsertPos);
151
152 scalarPHI->addIncoming(newEI, inBB);
153 }
154 }
Michael Kupersteina0c6ae02016-06-06 23:38:33 +0000155
156 for (auto E : Extracts)
157 replaceInstUsesWith(*E, scalarPHI);
158
159 return &EI;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000160}
161
Sanjay Patel4674c772018-09-24 20:41:22 +0000162static Instruction *foldBitcastExtElt(ExtractElementInst &Ext,
Sanjay Patel31b07192018-10-01 14:40:00 +0000163 InstCombiner::BuilderTy &Builder,
164 bool IsBigEndian) {
Sanjay Patel4674c772018-09-24 20:41:22 +0000165 Value *X;
166 uint64_t ExtIndexC;
167 if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) ||
168 !X->getType()->isVectorTy() ||
169 !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC)))
170 return nullptr;
171
172 // If this extractelement is using a bitcast from a vector of the same number
173 // of elements, see if we can find the source element from the source vector:
174 // extelt (bitcast VecX), IndexC --> bitcast X[IndexC]
175 Type *SrcTy = X->getType();
176 Type *DestTy = Ext.getType();
177 unsigned NumSrcElts = SrcTy->getVectorNumElements();
178 unsigned NumElts = Ext.getVectorOperandType()->getNumElements();
179 if (NumSrcElts == NumElts)
180 if (Value *Elt = findScalarElement(X, ExtIndexC))
181 return new BitCastInst(Elt, DestTy);
182
Sanjay Patel31b07192018-10-01 14:40:00 +0000183 // If the source elements are wider than the destination, try to shift and
184 // truncate a subset of scalar bits of an insert op.
Sanjay Patel3746e112018-10-04 16:25:05 +0000185 if (NumSrcElts < NumElts) {
Sanjay Patel31b07192018-10-01 14:40:00 +0000186 Value *Scalar;
187 uint64_t InsIndexC;
188 if (!match(X, m_InsertElement(m_Value(), m_Value(Scalar),
189 m_ConstantInt(InsIndexC))))
190 return nullptr;
191
192 // The extract must be from the subset of vector elements that we inserted
193 // into. Example: if we inserted element 1 of a <2 x i64> and we are
194 // extracting an i16 (narrowing ratio = 4), then this extract must be from 1
195 // of elements 4-7 of the bitcasted vector.
196 unsigned NarrowingRatio = NumElts / NumSrcElts;
197 if (ExtIndexC / NarrowingRatio != InsIndexC)
198 return nullptr;
199
200 // We are extracting part of the original scalar. How that scalar is
201 // inserted into the vector depends on the endian-ness. Example:
202 // Vector Byte Elt Index: 0 1 2 3 4 5 6 7
203 // +--+--+--+--+--+--+--+--+
204 // inselt <2 x i32> V, <i32> S, 1: |V0|V1|V2|V3|S0|S1|S2|S3|
205 // extelt <4 x i16> V', 3: | |S2|S3|
206 // +--+--+--+--+--+--+--+--+
207 // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value.
208 // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value.
209 // In this example, we must right-shift little-endian. Big-endian is just a
210 // truncate.
211 unsigned Chunk = ExtIndexC % NarrowingRatio;
212 if (IsBigEndian)
213 Chunk = NarrowingRatio - 1 - Chunk;
Sanjay Patel3746e112018-10-04 16:25:05 +0000214
215 // Bail out if this is an FP vector to FP vector sequence. That would take
216 // more instructions than we started with unless there is no shift, and it
217 // may not be handled as well in the backend.
218 bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy();
219 bool NeedDestBitcast = DestTy->isFloatingPointTy();
220 if (NeedSrcBitcast && NeedDestBitcast)
221 return nullptr;
222
223 unsigned SrcWidth = SrcTy->getScalarSizeInBits();
224 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
225 unsigned ShAmt = Chunk * DestWidth;
226
227 // TODO: This limitation is more strict than necessary. We could sum the
228 // number of new instructions and subtract the number eliminated to know if
229 // we can proceed.
230 if (!X->hasOneUse() || !Ext.getVectorOperand()->hasOneUse())
231 if (NeedSrcBitcast || NeedDestBitcast)
232 return nullptr;
233
234 if (NeedSrcBitcast) {
235 Type *SrcIntTy = IntegerType::getIntNTy(Scalar->getContext(), SrcWidth);
236 Scalar = Builder.CreateBitCast(Scalar, SrcIntTy);
237 }
238
Sanjay Patel31b07192018-10-01 14:40:00 +0000239 if (ShAmt) {
240 // Bail out if we could end with more instructions than we started with.
241 if (!Ext.getVectorOperand()->hasOneUse())
242 return nullptr;
243 Scalar = Builder.CreateLShr(Scalar, ShAmt);
244 }
Sanjay Patel3746e112018-10-04 16:25:05 +0000245
246 if (NeedDestBitcast) {
247 Type *DestIntTy = IntegerType::getIntNTy(Scalar->getContext(), DestWidth);
248 return new BitCastInst(Builder.CreateTrunc(Scalar, DestIntTy), DestTy);
249 }
Sanjay Patel31b07192018-10-01 14:40:00 +0000250 return new TruncInst(Scalar, DestTy);
251 }
252
Sanjay Patel4674c772018-09-24 20:41:22 +0000253 return nullptr;
254}
255
Piotr Sobczaka861c9a2019-10-21 08:12:47 +0000256/// Find elements of V demanded by UserInstr.
257static APInt findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr) {
258 unsigned VWidth = V->getType()->getVectorNumElements();
259
260 // Conservatively assume that all elements are needed.
261 APInt UsedElts(APInt::getAllOnesValue(VWidth));
262
263 switch (UserInstr->getOpcode()) {
264 case Instruction::ExtractElement: {
265 ExtractElementInst *EEI = cast<ExtractElementInst>(UserInstr);
266 assert(EEI->getVectorOperand() == V);
267 ConstantInt *EEIIndexC = dyn_cast<ConstantInt>(EEI->getIndexOperand());
268 if (EEIIndexC && EEIIndexC->getValue().ult(VWidth)) {
269 UsedElts = APInt::getOneBitSet(VWidth, EEIIndexC->getZExtValue());
270 }
271 break;
272 }
273 case Instruction::ShuffleVector: {
274 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(UserInstr);
275 unsigned MaskNumElts = UserInstr->getType()->getVectorNumElements();
276
277 UsedElts = APInt(VWidth, 0);
278 for (unsigned i = 0; i < MaskNumElts; i++) {
279 unsigned MaskVal = Shuffle->getMaskValue(i);
280 if (MaskVal == -1u || MaskVal >= 2 * VWidth)
281 continue;
282 if (Shuffle->getOperand(0) == V && (MaskVal < VWidth))
283 UsedElts.setBit(MaskVal);
284 if (Shuffle->getOperand(1) == V &&
285 ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth)))
286 UsedElts.setBit(MaskVal - VWidth);
287 }
288 break;
289 }
290 default:
291 break;
292 }
293 return UsedElts;
294}
295
296/// Find union of elements of V demanded by all its users.
297/// If it is known by querying findDemandedEltsBySingleUser that
298/// no user demands an element of V, then the corresponding bit
299/// remains unset in the returned value.
300static APInt findDemandedEltsByAllUsers(Value *V) {
301 unsigned VWidth = V->getType()->getVectorNumElements();
302
303 APInt UnionUsedElts(VWidth, 0);
304 for (const Use &U : V->uses()) {
305 if (Instruction *I = dyn_cast<Instruction>(U.getUser())) {
306 UnionUsedElts |= findDemandedEltsBySingleUser(V, I);
307 } else {
308 UnionUsedElts = APInt::getAllOnesValue(VWidth);
309 break;
310 }
311
312 if (UnionUsedElts.isAllOnesValue())
313 break;
314 }
315
316 return UnionUsedElts;
317}
318
Chris Lattnerec97a902010-01-05 05:36:20 +0000319Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000320 Value *SrcVec = EI.getVectorOperand();
321 Value *Index = EI.getIndexOperand();
322 if (Value *V = SimplifyExtractElementInst(SrcVec, Index,
Craig Toppera4205622017-06-09 03:21:29 +0000323 SQ.getWithInstruction(&EI)))
Sanjay Patel4b198802016-02-01 22:23:39 +0000324 return replaceInstUsesWith(EI, V);
David Majnemer599ca442015-07-13 01:15:53 +0000325
Chris Lattnerec97a902010-01-05 05:36:20 +0000326 // If extracting a specified index from the vector, see if we can recursively
327 // find a previously computed scalar that was inserted into the vector.
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000328 auto *IndexC = dyn_cast<ConstantInt>(Index);
329 if (IndexC) {
Sanjay Patel7a526262018-09-24 16:39:03 +0000330 unsigned NumElts = EI.getVectorOperandType()->getNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000331
Simon Pilgrime7d032f2017-12-27 12:00:18 +0000332 // InstSimplify should handle cases where the index is invalid.
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000333 if (!IndexC->getValue().ule(NumElts))
Simon Pilgrime7d032f2017-12-27 12:00:18 +0000334 return nullptr;
335
Chris Lattnerec97a902010-01-05 05:36:20 +0000336 // This instruction only demands the single element from the input vector.
Piotr Sobczaka861c9a2019-10-21 08:12:47 +0000337 if (NumElts != 1) {
338 // If the input vector has a single use, simplify it based on this use
339 // property.
340 if (SrcVec->hasOneUse()) {
341 APInt UndefElts(NumElts, 0);
342 APInt DemandedElts(NumElts, 0);
343 DemandedElts.setBit(IndexC->getZExtValue());
344 if (Value *V =
345 SimplifyDemandedVectorElts(SrcVec, DemandedElts, UndefElts)) {
346 EI.setOperand(0, V);
347 return &EI;
348 }
349 } else {
350 // If the input vector has multiple uses, simplify it based on a union
351 // of all elements used.
352 APInt DemandedElts = findDemandedEltsByAllUsers(SrcVec);
353 if (!DemandedElts.isAllOnesValue()) {
354 APInt UndefElts(NumElts, 0);
355 if (Value *V = SimplifyDemandedVectorElts(
356 SrcVec, DemandedElts, UndefElts, 0 /* Depth */,
357 true /* AllowMultipleUsers */)) {
358 if (V != SrcVec) {
359 SrcVec->replaceAllUsesWith(V);
360 return &EI;
361 }
362 }
363 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000364 }
365 }
Sanjay Patel31b07192018-10-01 14:40:00 +0000366 if (Instruction *I = foldBitcastExtElt(EI, Builder, DL.isBigEndian()))
Sanjay Patel4674c772018-09-24 20:41:22 +0000367 return I;
Anat Shemer0c95efa2013-04-18 19:35:39 +0000368
369 // If there's a vector PHI feeding a scalar use through this extractelement
370 // instruction, try to scalarize the PHI.
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000371 if (auto *Phi = dyn_cast<PHINode>(SrcVec))
372 if (Instruction *ScalarPHI = scalarizePHI(EI, Phi))
373 return ScalarPHI;
Chris Lattnerec97a902010-01-05 05:36:20 +0000374 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000375
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000376 BinaryOperator *BO;
377 if (match(SrcVec, m_BinOp(BO)) && cheapToScalarize(SrcVec, IndexC)) {
378 // extelt (binop X, Y), Index --> binop (extelt X, Index), (extelt Y, Index)
379 Value *X = BO->getOperand(0), *Y = BO->getOperand(1);
380 Value *E0 = Builder.CreateExtractElement(X, Index);
381 Value *E1 = Builder.CreateExtractElement(Y, Index);
382 return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), E0, E1, BO);
383 }
384
Matt Arsenault9ccde612018-12-10 21:50:54 +0000385 Value *X, *Y;
386 CmpInst::Predicate Pred;
387 if (match(SrcVec, m_Cmp(Pred, m_Value(X), m_Value(Y))) &&
388 cheapToScalarize(SrcVec, IndexC)) {
389 // extelt (cmp X, Y), Index --> cmp (extelt X, Index), (extelt Y, Index)
390 Value *E0 = Builder.CreateExtractElement(X, Index);
391 Value *E1 = Builder.CreateExtractElement(Y, Index);
392 return CmpInst::Create(cast<CmpInst>(SrcVec)->getOpcode(), Pred, E0, E1);
393 }
394
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000395 if (auto *I = dyn_cast<Instruction>(SrcVec)) {
396 if (auto *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000397 // Extracting the inserted element?
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000398 if (IE->getOperand(2) == Index)
Sanjay Patel4b198802016-02-01 22:23:39 +0000399 return replaceInstUsesWith(EI, IE->getOperand(1));
Chris Lattnerec97a902010-01-05 05:36:20 +0000400 // If the inserted and extracted elements are constants, they must not
401 // be the same value, extract from the pre-inserted value instead.
Nikita Popov878cb382020-01-31 22:23:33 +0100402 if (isa<Constant>(IE->getOperand(2)) && IndexC)
403 return replaceOperand(EI, 0, IE->getOperand(0));
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000404 } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000405 // If this is extracting an element from a shufflevector, figure out where
406 // it came from and extract from the appropriate input element instead.
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000407 if (auto *Elt = dyn_cast<ConstantInt>(Index)) {
Eli Friedman303c81c2011-10-21 19:11:34 +0000408 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue());
Chris Lattnerec97a902010-01-05 05:36:20 +0000409 Value *Src;
410 unsigned LHSWidth =
Chris Lattner8326bd82012-01-26 00:42:34 +0000411 SVI->getOperand(0)->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000412
Bob Wilson11ee4562010-10-29 22:03:05 +0000413 if (SrcIdx < 0)
Sanjay Patel4b198802016-02-01 22:23:39 +0000414 return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Bob Wilson11ee4562010-10-29 22:03:05 +0000415 if (SrcIdx < (int)LHSWidth)
Chris Lattnerec97a902010-01-05 05:36:20 +0000416 Src = SVI->getOperand(0);
Bob Wilson11ee4562010-10-29 22:03:05 +0000417 else {
Chris Lattnerec97a902010-01-05 05:36:20 +0000418 SrcIdx -= LHSWidth;
419 Src = SVI->getOperand(1);
Chris Lattnerec97a902010-01-05 05:36:20 +0000420 }
Chris Lattner229907c2011-07-18 04:54:35 +0000421 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
Chris Lattnerec97a902010-01-05 05:36:20 +0000422 return ExtractElementInst::Create(Src,
Bob Wilson9d07f392010-10-29 22:03:07 +0000423 ConstantInt::get(Int32Ty,
Chris Lattnerec97a902010-01-05 05:36:20 +0000424 SrcIdx, false));
425 }
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000426 } else if (auto *CI = dyn_cast<CastInst>(I)) {
Sanjay Patelb67076c2015-11-29 22:09:34 +0000427 // Canonicalize extractelement(cast) -> cast(extractelement).
428 // Bitcasts can change the number of vector elements, and they cost
429 // nothing.
Anat Shemer55703182013-04-18 19:56:44 +0000430 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
Sanjay Patel47b3b4b2018-12-05 21:57:51 +0000431 Value *EE = Builder.CreateExtractElement(CI->getOperand(0), Index);
Nadav Rotemd74b72b2011-03-31 22:57:29 +0000432 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
433 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000434 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000435 }
Craig Topperf40110f2014-04-25 05:29:35 +0000436 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +0000437}
438
Sanjay Patel6eccf482015-09-09 15:24:36 +0000439/// If V is a shuffle of values that ONLY returns elements from either LHS or
440/// RHS, return the shuffle mask and true. Otherwise, return false.
Sanjay Patel431e1142015-11-17 17:24:08 +0000441static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Chris Lattner0256be92012-01-27 03:08:05 +0000442 SmallVectorImpl<Constant*> &Mask) {
Tim Northoverfad27612014-03-07 10:24:44 +0000443 assert(LHS->getType() == RHS->getType() &&
Chris Lattnerec97a902010-01-05 05:36:20 +0000444 "Invalid CollectSingleShuffleElements");
Matt Arsenault8227b9f2013-09-06 00:37:24 +0000445 unsigned NumElts = V->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000446
Chris Lattnerec97a902010-01-05 05:36:20 +0000447 if (isa<UndefValue>(V)) {
448 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
449 return true;
450 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000451
Chris Lattnerec97a902010-01-05 05:36:20 +0000452 if (V == LHS) {
453 for (unsigned i = 0; i != NumElts; ++i)
454 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
455 return true;
456 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000457
Chris Lattnerec97a902010-01-05 05:36:20 +0000458 if (V == RHS) {
459 for (unsigned i = 0; i != NumElts; ++i)
460 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()),
461 i+NumElts));
462 return true;
463 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000464
Chris Lattnerec97a902010-01-05 05:36:20 +0000465 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
466 // If this is an insert of an extract from some other vector, include it.
467 Value *VecOp = IEI->getOperand(0);
468 Value *ScalarOp = IEI->getOperand(1);
469 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000470
Chris Lattnerec97a902010-01-05 05:36:20 +0000471 if (!isa<ConstantInt>(IdxOp))
472 return false;
473 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000474
Chris Lattnerec97a902010-01-05 05:36:20 +0000475 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000476 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000477 // transitively ok.
Sanjay Patel431e1142015-11-17 17:24:08 +0000478 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000479 // If so, update the mask to reflect the inserted undef.
480 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext()));
481 return true;
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000482 }
Chris Lattnerec97a902010-01-05 05:36:20 +0000483 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
Tim Northoverfad27612014-03-07 10:24:44 +0000484 if (isa<ConstantInt>(EI->getOperand(1))) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000485 unsigned ExtractedIdx =
486 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Tim Northoverfad27612014-03-07 10:24:44 +0000487 unsigned NumLHSElts = LHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000488
Chris Lattnerec97a902010-01-05 05:36:20 +0000489 // This must be extracting from either LHS or RHS.
490 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000491 // We can handle this if the vector we are inserting into is
Chris Lattnerec97a902010-01-05 05:36:20 +0000492 // transitively ok.
Sanjay Patel431e1142015-11-17 17:24:08 +0000493 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000494 // If so, update the mask to reflect the inserted value.
495 if (EI->getOperand(0) == LHS) {
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000496 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000497 ConstantInt::get(Type::getInt32Ty(V->getContext()),
498 ExtractedIdx);
499 } else {
500 assert(EI->getOperand(0) == RHS);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000501 Mask[InsertedIdx % NumElts] =
Chris Lattnerec97a902010-01-05 05:36:20 +0000502 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000503 ExtractedIdx + NumLHSElts);
Chris Lattnerec97a902010-01-05 05:36:20 +0000504 }
505 return true;
506 }
507 }
508 }
509 }
510 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000511
Chris Lattnerec97a902010-01-05 05:36:20 +0000512 return false;
513}
514
Sanjay Patelae945e72015-12-24 21:17:56 +0000515/// If we have insertion into a vector that is wider than the vector that we
516/// are extracting from, try to widen the source vector to allow a single
517/// shufflevector to replace one or more insert/extract pairs.
518static void replaceExtractElements(InsertElementInst *InsElt,
519 ExtractElementInst *ExtElt,
520 InstCombiner &IC) {
521 VectorType *InsVecType = InsElt->getType();
522 VectorType *ExtVecType = ExtElt->getVectorOperandType();
523 unsigned NumInsElts = InsVecType->getVectorNumElements();
524 unsigned NumExtElts = ExtVecType->getVectorNumElements();
525
526 // The inserted-to vector must be wider than the extracted-from vector.
527 if (InsVecType->getElementType() != ExtVecType->getElementType() ||
528 NumExtElts >= NumInsElts)
529 return;
530
531 // Create a shuffle mask to widen the extended-from vector using undefined
532 // values. The mask selects all of the values of the original vector followed
533 // by as many undefined values as needed to create a vector of the same length
534 // as the inserted-to vector.
535 SmallVector<Constant *, 16> ExtendMask;
536 IntegerType *IntType = Type::getInt32Ty(InsElt->getContext());
537 for (unsigned i = 0; i < NumExtElts; ++i)
538 ExtendMask.push_back(ConstantInt::get(IntType, i));
539 for (unsigned i = NumExtElts; i < NumInsElts; ++i)
540 ExtendMask.push_back(UndefValue::get(IntType));
541
542 Value *ExtVecOp = ExtElt->getVectorOperand();
Sanjay Patel66fff732016-01-29 20:21:02 +0000543 auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
544 BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
545 ? ExtVecOpInst->getParent()
546 : ExtElt->getParent();
547
548 // TODO: This restriction matches the basic block check below when creating
549 // new extractelement instructions. If that limitation is removed, this one
550 // could also be removed. But for now, we just bail out to ensure that we
551 // will replace the extractelement instruction that is feeding our
552 // insertelement instruction. This allows the insertelement to then be
553 // replaced by a shufflevector. If the insertelement is not replaced, we can
554 // induce infinite looping because there's an optimization for extractelement
555 // that will delete our widening shuffle. This would trigger another attempt
556 // here to create that shuffle, and we spin forever.
557 if (InsertionBlock != InsElt->getParent())
558 return;
559
Sanjay Patel4e1b5a52016-11-10 00:15:14 +0000560 // TODO: This restriction matches the check in visitInsertElementInst() and
561 // prevents an infinite loop caused by not turning the extract/insert pair
562 // into a shuffle. We really should not need either check, but we're lacking
563 // folds for shufflevectors because we're afraid to generate shuffle masks
564 // that the backend can't handle.
565 if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
566 return;
567
Sanjay Patelae945e72015-12-24 21:17:56 +0000568 auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType),
569 ConstantVector::get(ExtendMask));
570
Sanjay Patela1c53472016-01-05 19:09:47 +0000571 // Insert the new shuffle after the vector operand of the extract is defined
Sanjay Pateld72a4582016-01-08 01:39:16 +0000572 // (as long as it's not a PHI) or at the start of the basic block of the
573 // extract, so any subsequent extracts in the same basic block can use it.
574 // TODO: Insert before the earliest ExtractElementInst that is replaced.
Sanjay Pateld72a4582016-01-08 01:39:16 +0000575 if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
Sanjay Patela1c53472016-01-05 19:09:47 +0000576 WideVec->insertAfter(ExtVecOpInst);
Sanjay Pateld72a4582016-01-08 01:39:16 +0000577 else
Sanjay Patela1c53472016-01-05 19:09:47 +0000578 IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
Sanjay Patela1c53472016-01-05 19:09:47 +0000579
580 // Replace extracts from the original narrow vector with extracts from the new
581 // wide vector.
Sanjay Patelae945e72015-12-24 21:17:56 +0000582 for (User *U : ExtVecOp->users()) {
Sanjay Patela1c53472016-01-05 19:09:47 +0000583 ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
Sanjay Pateld72a4582016-01-08 01:39:16 +0000584 if (!OldExt || OldExt->getParent() != WideVec->getParent())
Sanjay Patela1c53472016-01-05 19:09:47 +0000585 continue;
586 auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
Sven van Haastregt78819e02017-06-05 09:18:10 +0000587 NewExt->insertAfter(OldExt);
Sanjay Patel4b198802016-02-01 22:23:39 +0000588 IC.replaceInstUsesWith(*OldExt, NewExt);
Sanjay Patelae945e72015-12-24 21:17:56 +0000589 }
590}
Tim Northoverfad27612014-03-07 10:24:44 +0000591
592/// We are building a shuffle to create V, which is a sequence of insertelement,
593/// extractelement pairs. If PermittedRHS is set, then we must either use it or
Sanjay Patel70af1fd2014-07-07 22:13:58 +0000594/// not rely on the second vector source. Return a std::pair containing the
Tim Northoverfad27612014-03-07 10:24:44 +0000595/// left and right vectors of the proposed shuffle (or 0), and set the Mask
596/// parameter as required.
597///
598/// Note: we intentionally don't try to fold earlier shuffles since they have
599/// often been chosen carefully to be efficiently implementable on the target.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +0000600using ShuffleOps = std::pair<Value *, Value *>;
Tim Northoverfad27612014-03-07 10:24:44 +0000601
Sanjay Patel431e1142015-11-17 17:24:08 +0000602static ShuffleOps collectShuffleElements(Value *V,
Tim Northoverfad27612014-03-07 10:24:44 +0000603 SmallVectorImpl<Constant *> &Mask,
Sanjay Patelae945e72015-12-24 21:17:56 +0000604 Value *PermittedRHS,
605 InstCombiner &IC) {
Tim Northoverfad27612014-03-07 10:24:44 +0000606 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
Craig Topper17b55682016-12-29 07:03:18 +0000607 unsigned NumElts = V->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000608
Chris Lattnerec97a902010-01-05 05:36:20 +0000609 if (isa<UndefValue>(V)) {
610 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext())));
Tim Northoverfad27612014-03-07 10:24:44 +0000611 return std::make_pair(
612 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000613 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000614
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000615 if (isa<ConstantAggregateZero>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000616 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0));
Tim Northoverfad27612014-03-07 10:24:44 +0000617 return std::make_pair(V, nullptr);
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000618 }
Craig Topper2ea22b02013-01-18 05:09:16 +0000619
Chris Lattnera0d01ff2012-01-24 14:31:22 +0000620 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000621 // If this is an insert of an extract from some other vector, include it.
622 Value *VecOp = IEI->getOperand(0);
623 Value *ScalarOp = IEI->getOperand(1);
624 Value *IdxOp = IEI->getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000625
Chris Lattnerec97a902010-01-05 05:36:20 +0000626 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
Tim Northoverfad27612014-03-07 10:24:44 +0000627 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
Chris Lattnerec97a902010-01-05 05:36:20 +0000628 unsigned ExtractedIdx =
Bob Wilson67a6f322010-10-29 22:20:45 +0000629 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattnerec97a902010-01-05 05:36:20 +0000630 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000631
Chris Lattnerec97a902010-01-05 05:36:20 +0000632 // Either the extracted from or inserted into vector must be RHSVec,
633 // otherwise we'd end up with a shuffle of three inputs.
Craig Topperf40110f2014-04-25 05:29:35 +0000634 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
Tim Northoverfad27612014-03-07 10:24:44 +0000635 Value *RHS = EI->getOperand(0);
Sanjay Patelae945e72015-12-24 21:17:56 +0000636 ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
Craig Toppere73658d2014-04-28 04:05:08 +0000637 assert(LR.second == nullptr || LR.second == RHS);
Tim Northoverfad27612014-03-07 10:24:44 +0000638
639 if (LR.first->getType() != RHS->getType()) {
Sanjay Patelae945e72015-12-24 21:17:56 +0000640 // Although we are giving up for now, see if we can create extracts
641 // that match the inserts for another round of combining.
642 replaceExtractElements(IEI, EI, IC);
643
Tim Northoverfad27612014-03-07 10:24:44 +0000644 // We tried our best, but we can't find anything compatible with RHS
645 // further up the chain. Return a trivial shuffle.
646 for (unsigned i = 0; i < NumElts; ++i)
647 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i);
648 return std::make_pair(V, nullptr);
649 }
650
651 unsigned NumLHSElts = RHS->getType()->getVectorNumElements();
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000652 Mask[InsertedIdx % NumElts] =
Bob Wilson67a6f322010-10-29 22:20:45 +0000653 ConstantInt::get(Type::getInt32Ty(V->getContext()),
Tim Northoverfad27612014-03-07 10:24:44 +0000654 NumLHSElts+ExtractedIdx);
655 return std::make_pair(LR.first, RHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000656 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000657
Tim Northoverfad27612014-03-07 10:24:44 +0000658 if (VecOp == PermittedRHS) {
659 // We've gone as far as we can: anything on the other side of the
660 // extractelement will already have been converted into a shuffle.
661 unsigned NumLHSElts =
662 EI->getOperand(0)->getType()->getVectorNumElements();
663 for (unsigned i = 0; i != NumElts; ++i)
664 Mask.push_back(ConstantInt::get(
665 Type::getInt32Ty(V->getContext()),
666 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i));
667 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000668 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000669
Chris Lattnerec97a902010-01-05 05:36:20 +0000670 // If this insertelement is a chain that comes from exactly these two
671 // vectors, return the vector and the effective shuffle.
Tim Northoverfad27612014-03-07 10:24:44 +0000672 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
Sanjay Patel431e1142015-11-17 17:24:08 +0000673 collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
Tim Northoverfad27612014-03-07 10:24:44 +0000674 Mask))
675 return std::make_pair(EI->getOperand(0), PermittedRHS);
Chris Lattnerec97a902010-01-05 05:36:20 +0000676 }
677 }
678 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +0000679
Sanjay Patelb67076c2015-11-29 22:09:34 +0000680 // Otherwise, we can't do anything fancy. Return an identity vector.
Chris Lattnerec97a902010-01-05 05:36:20 +0000681 for (unsigned i = 0; i != NumElts; ++i)
682 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i));
Tim Northoverfad27612014-03-07 10:24:44 +0000683 return std::make_pair(V, nullptr);
Chris Lattnerec97a902010-01-05 05:36:20 +0000684}
685
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000686/// Try to find redundant insertvalue instructions, like the following ones:
687/// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
688/// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
689/// Here the second instruction inserts values at the same indices, as the
690/// first one, making the first one redundant.
691/// It should be transformed to:
692/// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
693Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) {
694 bool IsRedundant = false;
695 ArrayRef<unsigned int> FirstIndices = I.getIndices();
696
697 // If there is a chain of insertvalue instructions (each of them except the
698 // last one has only one use and it's another insertvalue insn from this
699 // chain), check if any of the 'children' uses the same indices as the first
700 // instruction. In this case, the first one is redundant.
701 Value *V = &I;
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000702 unsigned Depth = 0;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000703 while (V->hasOneUse() && Depth < 10) {
704 User *U = V->user_back();
Michael Zolotukhin292d3ca2014-05-08 19:50:24 +0000705 auto UserInsInst = dyn_cast<InsertValueInst>(U);
706 if (!UserInsInst || U->getOperand(0) != V)
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000707 break;
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000708 if (UserInsInst->getIndices() == FirstIndices) {
709 IsRedundant = true;
710 break;
711 }
712 V = UserInsInst;
713 Depth++;
714 }
715
716 if (IsRedundant)
Sanjay Patel4b198802016-02-01 22:23:39 +0000717 return replaceInstUsesWith(I, I.getOperand(0));
Michael Zolotukhin7d6293a2014-05-07 14:30:18 +0000718 return nullptr;
719}
720
Sanjay Patel521f19f2016-09-02 17:05:43 +0000721static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) {
722 int MaskSize = Shuf.getMask()->getType()->getVectorNumElements();
723 int VecSize = Shuf.getOperand(0)->getType()->getVectorNumElements();
724
725 // A vector select does not change the size of the operands.
726 if (MaskSize != VecSize)
727 return false;
728
729 // Each mask element must be undefined or choose a vector element from one of
730 // the source operands without crossing vector lanes.
731 for (int i = 0; i != MaskSize; ++i) {
732 int Elt = Shuf.getMaskValue(i);
733 if (Elt != -1 && Elt != i && Elt != i + VecSize)
734 return false;
735 }
736
737 return true;
738}
739
Sanjay Patel71ad2272019-06-26 15:52:59 +0000740/// Turn a chain of inserts that splats a value into an insert + shuffle:
741/// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
742/// shufflevector(insertelt(X, %k, 0), undef, zero)
743static Instruction *foldInsSequenceIntoSplat(InsertElementInst &InsElt) {
744 // We are interested in the last insert in a chain. So if this insert has a
745 // single user and that user is an insert, bail.
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000746 if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
747 return nullptr;
748
Sanjay Patel71ad2272019-06-26 15:52:59 +0000749 auto *VecTy = cast<VectorType>(InsElt.getType());
750 unsigned NumElements = VecTy->getNumElements();
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000751
752 // Do not try to do this for a one-element vector, since that's a nop,
753 // and will cause an inf-loop.
754 if (NumElements == 1)
755 return nullptr;
756
757 Value *SplatVal = InsElt.getOperand(1);
Fangrui Songf78650a2018-07-30 19:41:25 +0000758 InsertElementInst *CurrIE = &InsElt;
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000759 SmallVector<bool, 16> ElementPresent(NumElements, false);
Florian Hahnb992fee2017-08-30 10:54:21 +0000760 InsertElementInst *FirstIE = nullptr;
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000761
762 // Walk the chain backwards, keeping track of which indices we inserted into,
763 // until we hit something that isn't an insert of the splatted value.
764 while (CurrIE) {
Sanjay Patel863d4942017-11-27 18:19:32 +0000765 auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000766 if (!Idx || CurrIE->getOperand(1) != SplatVal)
767 return nullptr;
768
Sanjay Patel863d4942017-11-27 18:19:32 +0000769 auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
Florian Hahnb992fee2017-08-30 10:54:21 +0000770 // Check none of the intermediate steps have any additional uses, except
771 // for the root insertelement instruction, which can be re-used, if it
772 // inserts at position 0.
773 if (CurrIE != &InsElt &&
774 (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero())))
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000775 return nullptr;
776
777 ElementPresent[Idx->getZExtValue()] = true;
Florian Hahnb992fee2017-08-30 10:54:21 +0000778 FirstIE = CurrIE;
779 CurrIE = NextIE;
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000780 }
781
Sanjay Patel75b5edf2019-07-04 16:45:34 +0000782 // If this is just a single insertelement (not a sequence), we are done.
783 if (FirstIE == &InsElt)
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000784 return nullptr;
785
Sanjay Patel75b5edf2019-07-04 16:45:34 +0000786 // If we are not inserting into an undef vector, make sure we've seen an
787 // insert into every element.
788 // TODO: If the base vector is not undef, it might be better to create a splat
789 // and then a select-shuffle (blend) with the base vector.
790 if (!isa<UndefValue>(FirstIE->getOperand(0)))
791 if (any_of(ElementPresent, [](bool Present) { return !Present; }))
792 return nullptr;
793
Sanjay Patel71ad2272019-06-26 15:52:59 +0000794 // Create the insert + shuffle.
795 Type *Int32Ty = Type::getInt32Ty(InsElt.getContext());
796 UndefValue *UndefVec = UndefValue::get(VecTy);
797 Constant *Zero = ConstantInt::get(Int32Ty, 0);
798 if (!cast<ConstantInt>(FirstIE->getOperand(2))->isZero())
799 FirstIE = InsertElementInst::Create(UndefVec, SplatVal, Zero, "", &InsElt);
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000800
Sanjay Patel75b5edf2019-07-04 16:45:34 +0000801 // Splat from element 0, but replace absent elements with undef in the mask.
802 SmallVector<Constant *, 16> Mask(NumElements, Zero);
803 for (unsigned i = 0; i != NumElements; ++i)
804 if (!ElementPresent[i])
805 Mask[i] = UndefValue::get(Int32Ty);
806
807 return new ShuffleVectorInst(FirstIE, UndefVec, ConstantVector::get(Mask));
Michael Kupersteincd7ad712016-12-28 00:18:08 +0000808}
809
Sanjay Patel3dee1132019-07-08 19:48:52 +0000810/// Try to fold an insert element into an existing splat shuffle by changing
811/// the shuffle's mask to include the index of this insert element.
812static Instruction *foldInsEltIntoSplat(InsertElementInst &InsElt) {
813 // Check if the vector operand of this insert is a canonical splat shuffle.
814 auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
815 if (!Shuf || !Shuf->isZeroEltSplat())
816 return nullptr;
817
818 // Check for a constant insertion index.
819 uint64_t IdxC;
820 if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
821 return nullptr;
822
823 // Check if the splat shuffle's input is the same as this insert's scalar op.
824 Value *X = InsElt.getOperand(1);
825 Value *Op0 = Shuf->getOperand(0);
826 if (!match(Op0, m_InsertElement(m_Undef(), m_Specific(X), m_ZeroInt())))
827 return nullptr;
828
829 // Replace the shuffle mask element at the index of this insert with a zero.
830 // For example:
831 // inselt (shuf (inselt undef, X, 0), undef, <0,undef,0,undef>), X, 1
832 // --> shuf (inselt undef, X, 0), undef, <0,0,0,undef>
833 unsigned NumMaskElts = Shuf->getType()->getVectorNumElements();
834 SmallVector<Constant *, 16> NewMaskVec(NumMaskElts);
835 Type *I32Ty = IntegerType::getInt32Ty(Shuf->getContext());
836 Constant *Zero = ConstantInt::getNullValue(I32Ty);
837 for (unsigned i = 0; i != NumMaskElts; ++i)
838 NewMaskVec[i] = i == IdxC ? Zero : Shuf->getMask()->getAggregateElement(i);
839
840 Constant *NewMask = ConstantVector::get(NewMaskVec);
841 return new ShuffleVectorInst(Op0, UndefValue::get(Op0->getType()), NewMask);
842}
843
Sanjay Patelaff5bee2019-09-08 19:03:01 +0000844/// Try to fold an extract+insert element into an existing identity shuffle by
845/// changing the shuffle's mask to include the index of this insert element.
846static Instruction *foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt) {
847 // Check if the vector operand of this insert is an identity shuffle.
848 auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
849 if (!Shuf || !isa<UndefValue>(Shuf->getOperand(1)) ||
850 !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding()))
851 return nullptr;
852
853 // Check for a constant insertion index.
854 uint64_t IdxC;
855 if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
856 return nullptr;
857
858 // Check if this insert's scalar op is extracted from the identity shuffle's
859 // input vector.
860 Value *Scalar = InsElt.getOperand(1);
861 Value *X = Shuf->getOperand(0);
862 if (!match(Scalar, m_ExtractElement(m_Specific(X), m_SpecificInt(IdxC))))
863 return nullptr;
864
865 // Replace the shuffle mask element at the index of this extract+insert with
866 // that same index value.
867 // For example:
868 // inselt (shuf X, IdMask), (extelt X, IdxC), IdxC --> shuf X, IdMask'
869 unsigned NumMaskElts = Shuf->getType()->getVectorNumElements();
870 SmallVector<Constant *, 16> NewMaskVec(NumMaskElts);
871 Type *I32Ty = IntegerType::getInt32Ty(Shuf->getContext());
872 Constant *NewMaskEltC = ConstantInt::get(I32Ty, IdxC);
873 Constant *OldMask = Shuf->getMask();
874 for (unsigned i = 0; i != NumMaskElts; ++i) {
875 if (i != IdxC) {
876 // All mask elements besides the inserted element remain the same.
877 NewMaskVec[i] = OldMask->getAggregateElement(i);
878 } else if (OldMask->getAggregateElement(i) == NewMaskEltC) {
879 // If the mask element was already set, there's nothing to do
880 // (demanded elements analysis may unset it later).
881 return nullptr;
882 } else {
883 assert(isa<UndefValue>(OldMask->getAggregateElement(i)) &&
884 "Unexpected shuffle mask element for identity shuffle");
885 NewMaskVec[i] = NewMaskEltC;
886 }
887 }
888
889 Constant *NewMask = ConstantVector::get(NewMaskVec);
890 return new ShuffleVectorInst(X, Shuf->getOperand(1), NewMask);
891}
892
Sanjay Patel2f602ce2017-03-22 17:10:44 +0000893/// If we have an insertelement instruction feeding into another insertelement
894/// and the 2nd is inserting a constant into the vector, canonicalize that
895/// constant insertion before the insertion of a variable:
896///
897/// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
898/// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
899///
900/// This has the potential of eliminating the 2nd insertelement instruction
901/// via constant folding of the scalar constant into a vector constant.
902static Instruction *hoistInsEltConst(InsertElementInst &InsElt2,
903 InstCombiner::BuilderTy &Builder) {
904 auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
905 if (!InsElt1 || !InsElt1->hasOneUse())
906 return nullptr;
907
908 Value *X, *Y;
909 Constant *ScalarC;
910 ConstantInt *IdxC1, *IdxC2;
911 if (match(InsElt1->getOperand(0), m_Value(X)) &&
912 match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
913 match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
914 match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
915 match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
916 Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
917 return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
918 }
919
920 return nullptr;
921}
922
Alexey Bataevfee90782016-09-23 09:14:08 +0000923/// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
924/// --> shufflevector X, CVec', Mask'
Sanjay Patel521f19f2016-09-02 17:05:43 +0000925static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) {
Alexey Bataevfee90782016-09-23 09:14:08 +0000926 auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
927 // Bail out if the parent has more than one use. In that case, we'd be
Sanjay Patel521f19f2016-09-02 17:05:43 +0000928 // replacing the insertelt with a shuffle, and that's not a clear win.
Alexey Bataevfee90782016-09-23 09:14:08 +0000929 if (!Inst || !Inst->hasOneUse())
Sanjay Patel521f19f2016-09-02 17:05:43 +0000930 return nullptr;
Alexey Bataevfee90782016-09-23 09:14:08 +0000931 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
932 // The shuffle must have a constant vector operand. The insertelt must have
933 // a constant scalar being inserted at a constant position in the vector.
934 Constant *ShufConstVec, *InsEltScalar;
935 uint64_t InsEltIndex;
936 if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
937 !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
938 !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
939 return nullptr;
Sanjay Patel521f19f2016-09-02 17:05:43 +0000940
Alexey Bataevfee90782016-09-23 09:14:08 +0000941 // Adding an element to an arbitrary shuffle could be expensive, but a
942 // shuffle that selects elements from vectors without crossing lanes is
943 // assumed cheap.
944 // If we're just adding a constant into that shuffle, it will still be
945 // cheap.
946 if (!isShuffleEquivalentToSelect(*Shuf))
947 return nullptr;
Sanjay Patel521f19f2016-09-02 17:05:43 +0000948
Alexey Bataevfee90782016-09-23 09:14:08 +0000949 // From the above 'select' check, we know that the mask has the same number
950 // of elements as the vector input operands. We also know that each constant
951 // input element is used in its lane and can not be used more than once by
952 // the shuffle. Therefore, replace the constant in the shuffle's constant
953 // vector with the insertelt constant. Replace the constant in the shuffle's
954 // mask vector with the insertelt index plus the length of the vector
955 // (because the constant vector operand of a shuffle is always the 2nd
956 // operand).
957 Constant *Mask = Shuf->getMask();
958 unsigned NumElts = Mask->getType()->getVectorNumElements();
959 SmallVector<Constant *, 16> NewShufElts(NumElts);
960 SmallVector<Constant *, 16> NewMaskElts(NumElts);
961 for (unsigned I = 0; I != NumElts; ++I) {
962 if (I == InsEltIndex) {
963 NewShufElts[I] = InsEltScalar;
964 Type *Int32Ty = Type::getInt32Ty(Shuf->getContext());
965 NewMaskElts[I] = ConstantInt::get(Int32Ty, InsEltIndex + NumElts);
966 } else {
967 // Copy over the existing values.
968 NewShufElts[I] = ShufConstVec->getAggregateElement(I);
969 NewMaskElts[I] = Mask->getAggregateElement(I);
970 }
Sanjay Patel521f19f2016-09-02 17:05:43 +0000971 }
Sanjay Patel521f19f2016-09-02 17:05:43 +0000972
Alexey Bataevfee90782016-09-23 09:14:08 +0000973 // Create new operands for a shuffle that includes the constant of the
974 // original insertelt. The old shuffle will be dead now.
975 return new ShuffleVectorInst(Shuf->getOperand(0),
976 ConstantVector::get(NewShufElts),
977 ConstantVector::get(NewMaskElts));
978 } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
979 // Transform sequences of insertelements ops with constant data/indexes into
980 // a single shuffle op.
981 unsigned NumElts = InsElt.getType()->getNumElements();
982
983 uint64_t InsertIdx[2];
984 Constant *Val[2];
985 if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
986 !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
987 !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
988 !match(IEI->getOperand(1), m_Constant(Val[1])))
989 return nullptr;
990 SmallVector<Constant *, 16> Values(NumElts);
991 SmallVector<Constant *, 16> Mask(NumElts);
992 auto ValI = std::begin(Val);
993 // Generate new constant vector and mask.
994 // We have 2 values/masks from the insertelements instructions. Insert them
995 // into new value/mask vectors.
996 for (uint64_t I : InsertIdx) {
997 if (!Values[I]) {
998 assert(!Mask[I]);
999 Values[I] = *ValI;
1000 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()),
1001 NumElts + I);
1002 }
1003 ++ValI;
1004 }
1005 // Remaining values are filled with 'undef' values.
1006 for (unsigned I = 0; I < NumElts; ++I) {
1007 if (!Values[I]) {
1008 assert(!Mask[I]);
1009 Values[I] = UndefValue::get(InsElt.getType()->getElementType());
1010 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), I);
1011 }
1012 }
1013 // Create new operands for a shuffle that includes the constant of the
1014 // original insertelt.
1015 return new ShuffleVectorInst(IEI->getOperand(0),
1016 ConstantVector::get(Values),
1017 ConstantVector::get(Mask));
1018 }
1019 return nullptr;
Sanjay Patel521f19f2016-09-02 17:05:43 +00001020}
1021
Chris Lattnerec97a902010-01-05 05:36:20 +00001022Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
1023 Value *VecOp = IE.getOperand(0);
1024 Value *ScalarOp = IE.getOperand(1);
1025 Value *IdxOp = IE.getOperand(2);
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001026
Igor Laevskye0edb662017-12-13 11:21:18 +00001027 if (auto *V = SimplifyInsertElementInst(
1028 VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE)))
1029 return replaceInstUsesWith(IE, V);
1030
Sanjay Patel926e4772019-05-17 18:06:12 +00001031 // If the vector and scalar are both bitcast from the same element type, do
1032 // the insert in that source type followed by bitcast.
1033 Value *VecSrc, *ScalarSrc;
1034 if (match(VecOp, m_BitCast(m_Value(VecSrc))) &&
1035 match(ScalarOp, m_BitCast(m_Value(ScalarSrc))) &&
1036 (VecOp->hasOneUse() || ScalarOp->hasOneUse()) &&
1037 VecSrc->getType()->isVectorTy() && !ScalarSrc->getType()->isVectorTy() &&
1038 VecSrc->getType()->getVectorElementType() == ScalarSrc->getType()) {
1039 // inselt (bitcast VecSrc), (bitcast ScalarSrc), IdxOp -->
1040 // bitcast (inselt VecSrc, ScalarSrc, IdxOp)
1041 Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp);
1042 return new BitCastInst(NewInsElt, IE.getType());
1043 }
1044
Sanjay Patel0522b0d2018-10-20 17:15:57 +00001045 // If the inserted element was extracted from some other vector and both
Sanjay Patel93179632019-05-26 14:03:50 +00001046 // indexes are valid constants, try to turn this into a shuffle.
Sanjay Patel0522b0d2018-10-20 17:15:57 +00001047 uint64_t InsertedIdx, ExtractedIdx;
1048 Value *ExtVecOp;
1049 if (match(IdxOp, m_ConstantInt(InsertedIdx)) &&
1050 match(ScalarOp, m_ExtractElement(m_Value(ExtVecOp),
Sanjay Patel93179632019-05-26 14:03:50 +00001051 m_ConstantInt(ExtractedIdx))) &&
1052 ExtractedIdx < ExtVecOp->getType()->getVectorNumElements()) {
Sanjay Patel0522b0d2018-10-20 17:15:57 +00001053 // TODO: Looking at the user(s) to determine if this insert is a
1054 // fold-to-shuffle opportunity does not match the usual instcombine
1055 // constraints. We should decide if the transform is worthy based only
1056 // on this instruction and its operands, but that may not work currently.
1057 //
1058 // Here, we are trying to avoid creating shuffles before reaching
1059 // the end of a chain of extract-insert pairs. This is complicated because
1060 // we do not generally form arbitrary shuffle masks in instcombine
1061 // (because those may codegen poorly), but collectShuffleElements() does
1062 // exactly that.
1063 //
1064 // The rules for determining what is an acceptable target-independent
1065 // shuffle mask are fuzzy because they evolve based on the backend's
1066 // capabilities and real-world impact.
1067 auto isShuffleRootCandidate = [](InsertElementInst &Insert) {
1068 if (!Insert.hasOneUse())
1069 return true;
1070 auto *InsertUser = dyn_cast<InsertElementInst>(Insert.user_back());
1071 if (!InsertUser)
1072 return true;
1073 return false;
1074 };
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001075
Sanjay Patel0522b0d2018-10-20 17:15:57 +00001076 // Try to form a shuffle from a chain of extract-insert ops.
1077 if (isShuffleRootCandidate(IE)) {
1078 SmallVector<Constant*, 16> Mask;
1079 ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
Sanjay Patel729c4362018-10-20 16:25:55 +00001080
Sanjay Patel0522b0d2018-10-20 17:15:57 +00001081 // The proposed shuffle may be trivial, in which case we shouldn't
1082 // perform the combine.
1083 if (LR.first != &IE && LR.second != &IE) {
1084 // We now have a shuffle of LHS, RHS, Mask.
1085 if (LR.second == nullptr)
1086 LR.second = UndefValue::get(LR.first->getType());
1087 return new ShuffleVectorInst(LR.first, LR.second,
1088 ConstantVector::get(Mask));
Chris Lattnerec97a902010-01-05 05:36:20 +00001089 }
1090 }
1091 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001092
Craig Topper17b55682016-12-29 07:03:18 +00001093 unsigned VWidth = VecOp->getType()->getVectorNumElements();
Chris Lattnerec97a902010-01-05 05:36:20 +00001094 APInt UndefElts(VWidth, 0);
1095 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
Eli Friedmanef200db2011-02-19 22:42:40 +00001096 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
1097 if (V != &IE)
Sanjay Patel4b198802016-02-01 22:23:39 +00001098 return replaceInstUsesWith(IE, V);
Chris Lattnerec97a902010-01-05 05:36:20 +00001099 return &IE;
Eli Friedmanef200db2011-02-19 22:42:40 +00001100 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001101
Sanjay Patel521f19f2016-09-02 17:05:43 +00001102 if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE))
1103 return Shuf;
1104
Craig Topperbb4069e2017-07-07 23:16:26 +00001105 if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder))
Sanjay Patel2f602ce2017-03-22 17:10:44 +00001106 return NewInsElt;
1107
Sanjay Patel71ad2272019-06-26 15:52:59 +00001108 if (Instruction *Broadcast = foldInsSequenceIntoSplat(IE))
Michael Kupersteincd7ad712016-12-28 00:18:08 +00001109 return Broadcast;
1110
Sanjay Patel3dee1132019-07-08 19:48:52 +00001111 if (Instruction *Splat = foldInsEltIntoSplat(IE))
1112 return Splat;
1113
Sanjay Patelaff5bee2019-09-08 19:03:01 +00001114 if (Instruction *IdentityShuf = foldInsEltIntoIdentityShuffle(IE))
1115 return IdentityShuf;
1116
Craig Topperf40110f2014-04-25 05:29:35 +00001117 return nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +00001118}
1119
Nick Lewyckya2b77202013-05-31 00:59:42 +00001120/// Return true if we can evaluate the specified expression tree if the vector
1121/// elements were shuffled in a different order.
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001122static bool canEvaluateShuffled(Value *V, ArrayRef<int> Mask,
Nick Lewycky3f715e22013-06-01 20:51:31 +00001123 unsigned Depth = 5) {
Nick Lewyckya2b77202013-05-31 00:59:42 +00001124 // We can always reorder the elements of a constant.
1125 if (isa<Constant>(V))
1126 return true;
1127
1128 // We won't reorder vector arguments. No IPO here.
1129 Instruction *I = dyn_cast<Instruction>(V);
1130 if (!I) return false;
1131
1132 // Two users may expect different orders of the elements. Don't try it.
1133 if (!I->hasOneUse())
1134 return false;
1135
1136 if (Depth == 0) return false;
1137
1138 switch (I->getOpcode()) {
Bjorn Pettersson64562522019-10-18 07:42:02 +00001139 case Instruction::UDiv:
1140 case Instruction::SDiv:
1141 case Instruction::URem:
1142 case Instruction::SRem:
1143 // Propagating an undefined shuffle mask element to integer div/rem is not
1144 // allowed because those opcodes can create immediate undefined behavior
1145 // from an undefined element in an operand.
1146 if (llvm::any_of(Mask, [](int M){ return M == -1; }))
1147 return false;
1148 LLVM_FALLTHROUGH;
Nick Lewyckya2b77202013-05-31 00:59:42 +00001149 case Instruction::Add:
1150 case Instruction::FAdd:
1151 case Instruction::Sub:
1152 case Instruction::FSub:
1153 case Instruction::Mul:
1154 case Instruction::FMul:
Nick Lewyckya2b77202013-05-31 00:59:42 +00001155 case Instruction::FDiv:
Nick Lewyckya2b77202013-05-31 00:59:42 +00001156 case Instruction::FRem:
1157 case Instruction::Shl:
1158 case Instruction::LShr:
1159 case Instruction::AShr:
1160 case Instruction::And:
1161 case Instruction::Or:
1162 case Instruction::Xor:
1163 case Instruction::ICmp:
1164 case Instruction::FCmp:
1165 case Instruction::Trunc:
1166 case Instruction::ZExt:
1167 case Instruction::SExt:
1168 case Instruction::FPToUI:
1169 case Instruction::FPToSI:
1170 case Instruction::UIToFP:
1171 case Instruction::SIToFP:
1172 case Instruction::FPTrunc:
1173 case Instruction::FPExt:
1174 case Instruction::GetElementPtr: {
Sanjay Patel26c119a2018-09-30 13:50:42 +00001175 // Bail out if we would create longer vector ops. We could allow creating
Bjorn Pettersson64562522019-10-18 07:42:02 +00001176 // longer vector ops, but that may result in more expensive codegen.
Sanjay Patel26c119a2018-09-30 13:50:42 +00001177 Type *ITy = I->getType();
1178 if (ITy->isVectorTy() && Mask.size() > ITy->getVectorNumElements())
1179 return false;
Sanjay Patel4e28753142015-11-16 22:16:52 +00001180 for (Value *Operand : I->operands()) {
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001181 if (!canEvaluateShuffled(Operand, Mask, Depth - 1))
Nick Lewyckya2b77202013-05-31 00:59:42 +00001182 return false;
1183 }
1184 return true;
1185 }
1186 case Instruction::InsertElement: {
1187 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
1188 if (!CI) return false;
1189 int ElementNumber = CI->getLimitedValue();
1190
1191 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
1192 // can't put an element into multiple indices.
1193 bool SeenOnce = false;
1194 for (int i = 0, e = Mask.size(); i != e; ++i) {
1195 if (Mask[i] == ElementNumber) {
1196 if (SeenOnce)
1197 return false;
1198 SeenOnce = true;
1199 }
1200 }
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001201 return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001202 }
1203 }
1204 return false;
1205}
1206
1207/// Rebuild a new instruction just like 'I' but with the new operands given.
1208/// In the event of type mismatch, the type of the operands is correct.
Sanjay Patel431e1142015-11-17 17:24:08 +00001209static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
Nick Lewyckya2b77202013-05-31 00:59:42 +00001210 // We don't want to use the IRBuilder here because we want the replacement
1211 // instructions to appear next to 'I', not the builder's insertion point.
1212 switch (I->getOpcode()) {
1213 case Instruction::Add:
1214 case Instruction::FAdd:
1215 case Instruction::Sub:
1216 case Instruction::FSub:
1217 case Instruction::Mul:
1218 case Instruction::FMul:
1219 case Instruction::UDiv:
1220 case Instruction::SDiv:
1221 case Instruction::FDiv:
1222 case Instruction::URem:
1223 case Instruction::SRem:
1224 case Instruction::FRem:
1225 case Instruction::Shl:
1226 case Instruction::LShr:
1227 case Instruction::AShr:
1228 case Instruction::And:
1229 case Instruction::Or:
1230 case Instruction::Xor: {
1231 BinaryOperator *BO = cast<BinaryOperator>(I);
1232 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
1233 BinaryOperator *New =
1234 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
1235 NewOps[0], NewOps[1], "", BO);
1236 if (isa<OverflowingBinaryOperator>(BO)) {
1237 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
1238 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
1239 }
1240 if (isa<PossiblyExactOperator>(BO)) {
1241 New->setIsExact(BO->isExact());
1242 }
Owen Anderson48b842e2014-01-18 00:48:14 +00001243 if (isa<FPMathOperator>(BO))
1244 New->copyFastMathFlags(I);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001245 return New;
1246 }
1247 case Instruction::ICmp:
1248 assert(NewOps.size() == 2 && "icmp with #ops != 2");
1249 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
1250 NewOps[0], NewOps[1]);
1251 case Instruction::FCmp:
1252 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
1253 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
1254 NewOps[0], NewOps[1]);
1255 case Instruction::Trunc:
1256 case Instruction::ZExt:
1257 case Instruction::SExt:
1258 case Instruction::FPToUI:
1259 case Instruction::FPToSI:
1260 case Instruction::UIToFP:
1261 case Instruction::SIToFP:
1262 case Instruction::FPTrunc:
1263 case Instruction::FPExt: {
1264 // It's possible that the mask has a different number of elements from
1265 // the original cast. We recompute the destination type to match the mask.
1266 Type *DestTy =
1267 VectorType::get(I->getType()->getScalarType(),
1268 NewOps[0]->getType()->getVectorNumElements());
1269 assert(NewOps.size() == 1 && "cast with #ops != 1");
1270 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
1271 "", I);
1272 }
1273 case Instruction::GetElementPtr: {
1274 Value *Ptr = NewOps[0];
1275 ArrayRef<Value*> Idx = NewOps.slice(1);
David Blaikie22319eb2015-03-14 19:24:04 +00001276 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1277 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001278 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
1279 return GEP;
1280 }
1281 }
1282 llvm_unreachable("failed to rebuild vector instructions");
1283}
1284
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001285static Value *evaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
Nick Lewyckya2b77202013-05-31 00:59:42 +00001286 // Mask.size() does not need to be equal to the number of vector elements.
1287
1288 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
Sanjay Patelce36b032017-10-09 17:54:46 +00001289 Type *EltTy = V->getType()->getScalarType();
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001290 Type *I32Ty = IntegerType::getInt32Ty(V->getContext());
Sanjay Patelce36b032017-10-09 17:54:46 +00001291 if (isa<UndefValue>(V))
1292 return UndefValue::get(VectorType::get(EltTy, Mask.size()));
1293
1294 if (isa<ConstantAggregateZero>(V))
1295 return ConstantAggregateZero::get(VectorType::get(EltTy, Mask.size()));
1296
Nick Lewyckya2b77202013-05-31 00:59:42 +00001297 if (Constant *C = dyn_cast<Constant>(V)) {
1298 SmallVector<Constant *, 16> MaskValues;
1299 for (int i = 0, e = Mask.size(); i != e; ++i) {
1300 if (Mask[i] == -1)
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001301 MaskValues.push_back(UndefValue::get(I32Ty));
Nick Lewyckya2b77202013-05-31 00:59:42 +00001302 else
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001303 MaskValues.push_back(ConstantInt::get(I32Ty, Mask[i]));
Nick Lewyckya2b77202013-05-31 00:59:42 +00001304 }
1305 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()),
1306 ConstantVector::get(MaskValues));
1307 }
1308
1309 Instruction *I = cast<Instruction>(V);
1310 switch (I->getOpcode()) {
1311 case Instruction::Add:
1312 case Instruction::FAdd:
1313 case Instruction::Sub:
1314 case Instruction::FSub:
1315 case Instruction::Mul:
1316 case Instruction::FMul:
1317 case Instruction::UDiv:
1318 case Instruction::SDiv:
1319 case Instruction::FDiv:
1320 case Instruction::URem:
1321 case Instruction::SRem:
1322 case Instruction::FRem:
1323 case Instruction::Shl:
1324 case Instruction::LShr:
1325 case Instruction::AShr:
1326 case Instruction::And:
1327 case Instruction::Or:
1328 case Instruction::Xor:
1329 case Instruction::ICmp:
1330 case Instruction::FCmp:
1331 case Instruction::Trunc:
1332 case Instruction::ZExt:
1333 case Instruction::SExt:
1334 case Instruction::FPToUI:
1335 case Instruction::FPToSI:
1336 case Instruction::UIToFP:
1337 case Instruction::SIToFP:
1338 case Instruction::FPTrunc:
1339 case Instruction::FPExt:
1340 case Instruction::Select:
1341 case Instruction::GetElementPtr: {
1342 SmallVector<Value*, 8> NewOps;
1343 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements());
1344 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
Mikael Holmen150a7ec2019-04-01 14:10:10 +00001345 Value *V;
1346 // Recursively call evaluateInDifferentElementOrder on vector arguments
1347 // as well. E.g. GetElementPtr may have scalar operands even if the
1348 // return value is a vector, so we need to examine the operand type.
1349 if (I->getOperand(i)->getType()->isVectorTy())
1350 V = evaluateInDifferentElementOrder(I->getOperand(i), Mask);
1351 else
1352 V = I->getOperand(i);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001353 NewOps.push_back(V);
1354 NeedsRebuild |= (V != I->getOperand(i));
1355 }
1356 if (NeedsRebuild) {
Sanjay Patel431e1142015-11-17 17:24:08 +00001357 return buildNew(I, NewOps);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001358 }
1359 return I;
1360 }
1361 case Instruction::InsertElement: {
1362 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
Nick Lewyckya2b77202013-05-31 00:59:42 +00001363
1364 // The insertelement was inserting at Element. Figure out which element
1365 // that becomes after shuffling. The answer is guaranteed to be unique
1366 // by CanEvaluateShuffled.
Nick Lewycky3f715e22013-06-01 20:51:31 +00001367 bool Found = false;
Nick Lewyckya2b77202013-05-31 00:59:42 +00001368 int Index = 0;
Nick Lewycky3f715e22013-06-01 20:51:31 +00001369 for (int e = Mask.size(); Index != e; ++Index) {
1370 if (Mask[Index] == Element) {
1371 Found = true;
Nick Lewyckya2b77202013-05-31 00:59:42 +00001372 break;
Nick Lewycky3f715e22013-06-01 20:51:31 +00001373 }
1374 }
Nick Lewyckya2b77202013-05-31 00:59:42 +00001375
Hao Liu26abebb2014-01-08 03:06:15 +00001376 // If element is not in Mask, no need to handle the operand 1 (element to
1377 // be inserted). Just evaluate values in operand 0 according to Mask.
Nick Lewycky3f715e22013-06-01 20:51:31 +00001378 if (!Found)
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001379 return evaluateInDifferentElementOrder(I->getOperand(0), Mask);
Joey Goulya3250f22013-07-12 23:08:06 +00001380
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001381 Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001382 return InsertElementInst::Create(V, I->getOperand(1),
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001383 ConstantInt::get(I32Ty, Index), "", I);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001384 }
1385 }
1386 llvm_unreachable("failed to reorder elements of vector instruction!");
1387}
Chris Lattnerec97a902010-01-05 05:36:20 +00001388
JF Bastiend52c9902015-02-25 22:30:51 +00001389// Returns true if the shuffle is extracting a contiguous range of values from
1390// LHS, for example:
1391// +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1392// Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
1393// Shuffles to: |EE|FF|GG|HH|
1394// +--+--+--+--+
1395static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
1396 SmallVector<int, 16> &Mask) {
Craig Topper17b55682016-12-29 07:03:18 +00001397 unsigned LHSElems = SVI.getOperand(0)->getType()->getVectorNumElements();
JF Bastiend52c9902015-02-25 22:30:51 +00001398 unsigned MaskElems = Mask.size();
1399 unsigned BegIdx = Mask.front();
1400 unsigned EndIdx = Mask.back();
1401 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
1402 return false;
1403 for (unsigned I = 0; I != MaskElems; ++I)
1404 if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
1405 return false;
1406 return true;
1407}
1408
Sanjay Patelb999d742018-07-02 17:42:29 +00001409/// These are the ingredients in an alternate form binary operator as described
1410/// below.
1411struct BinopElts {
1412 BinaryOperator::BinaryOps Opcode;
1413 Value *Op0;
1414 Value *Op1;
1415 BinopElts(BinaryOperator::BinaryOps Opc = (BinaryOperator::BinaryOps)0,
1416 Value *V0 = nullptr, Value *V1 = nullptr) :
1417 Opcode(Opc), Op0(V0), Op1(V1) {}
1418 operator bool() const { return Opcode != 0; }
1419};
1420
1421/// Binops may be transformed into binops with different opcodes and operands.
1422/// Reverse the usual canonicalization to enable folds with the non-canonical
1423/// form of the binop. If a transform is possible, return the elements of the
1424/// new binop. If not, return invalid elements.
1425static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL) {
1426 Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1);
1427 Type *Ty = BO->getType();
1428 switch (BO->getOpcode()) {
1429 case Instruction::Shl: {
1430 // shl X, C --> mul X, (1 << C)
1431 Constant *C;
1432 if (match(BO1, m_Constant(C))) {
1433 Constant *ShlOne = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C);
1434 return { Instruction::Mul, BO0, ShlOne };
1435 }
1436 break;
1437 }
1438 case Instruction::Or: {
1439 // or X, C --> add X, C (when X and C have no common bits set)
1440 const APInt *C;
1441 if (match(BO1, m_APInt(C)) && MaskedValueIsZero(BO0, *C, DL))
1442 return { Instruction::Add, BO0, BO1 };
1443 break;
1444 }
1445 default:
1446 break;
1447 }
1448 return {};
1449}
1450
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001451static Instruction *foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf) {
1452 assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
1453
1454 // Are we shuffling together some value and that same value after it has been
1455 // modified by a binop with a constant?
1456 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
1457 Constant *C;
1458 bool Op0IsBinop;
1459 if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C))))
1460 Op0IsBinop = true;
1461 else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C))))
1462 Op0IsBinop = false;
1463 else
1464 return nullptr;
1465
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001466 // The identity constant for a binop leaves a variable operand unchanged. For
1467 // a vector, this is a splat of something like 0, -1, or 1.
1468 // If there's no identity constant for this binop, we're done.
Sanjay Patel509a1e72018-07-10 15:12:31 +00001469 auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1);
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001470 BinaryOperator::BinaryOps BOpcode = BO->getOpcode();
Sanjay Patel509a1e72018-07-10 15:12:31 +00001471 Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true);
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001472 if (!IdC)
1473 return nullptr;
1474
1475 // Shuffle identity constants into the lanes that return the original value.
1476 // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4}
1477 // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4}
1478 // The existing binop constant vector remains in the same operand position.
1479 Constant *Mask = Shuf.getMask();
1480 Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) :
1481 ConstantExpr::getShuffleVector(IdC, C, Mask);
1482
Sanjay Patel509a1e72018-07-10 15:12:31 +00001483 bool MightCreatePoisonOrUB =
1484 Mask->containsUndefElement() &&
1485 (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode));
1486 if (MightCreatePoisonOrUB)
1487 NewC = getSafeVectorConstantForBinop(BOpcode, NewC, true);
1488
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001489 // shuf (bop X, C), X, M --> bop X, C'
1490 // shuf X, (bop X, C), M --> bop X, C'
Sanjay Patel509a1e72018-07-10 15:12:31 +00001491 Value *X = Op0IsBinop ? Op1 : Op0;
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001492 Instruction *NewBO = BinaryOperator::Create(BOpcode, X, NewC);
1493 NewBO->copyIRFlags(BO);
Sanjay Patel33331062018-07-10 14:27:55 +00001494
1495 // An undef shuffle mask element may propagate as an undef constant element in
1496 // the new binop. That would produce poison where the original code might not.
Sanjay Patel509a1e72018-07-10 15:12:31 +00001497 // If we already made a safe constant, then there's no danger.
1498 if (Mask->containsUndefElement() && !MightCreatePoisonOrUB)
Sanjay Patel33331062018-07-10 14:27:55 +00001499 NewBO->dropPoisonGeneratingFlags();
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001500 return NewBO;
1501}
1502
Sanjay Patel0b591032019-07-08 16:26:48 +00001503/// If we have an insert of a scalar to a non-zero element of an undefined
1504/// vector and then shuffle that value, that's the same as inserting to the zero
1505/// element and shuffling. Splatting from the zero element is recognized as the
1506/// canonical form of splat.
1507static Instruction *canonicalizeInsertSplat(ShuffleVectorInst &Shuf,
1508 InstCombiner::BuilderTy &Builder) {
1509 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
1510 Constant *Mask = Shuf.getMask();
1511 Value *X;
1512 uint64_t IndexC;
1513
1514 // Match a shuffle that is a splat to a non-zero element.
1515 if (!match(Op0, m_OneUse(m_InsertElement(m_Undef(), m_Value(X),
1516 m_ConstantInt(IndexC)))) ||
1517 !match(Op1, m_Undef()) || match(Mask, m_ZeroInt()) || IndexC == 0)
1518 return nullptr;
1519
1520 // Insert into element 0 of an undef vector.
1521 UndefValue *UndefVec = UndefValue::get(Shuf.getType());
1522 Constant *Zero = Builder.getInt32(0);
1523 Value *NewIns = Builder.CreateInsertElement(UndefVec, X, Zero);
1524
1525 // Splat from element 0. Any mask element that is undefined remains undefined.
1526 // For example:
1527 // shuf (inselt undef, X, 2), undef, <2,2,undef>
1528 // --> shuf (inselt undef, X, 0), undef, <0,0,undef>
1529 unsigned NumMaskElts = Shuf.getType()->getVectorNumElements();
1530 SmallVector<Constant *, 16> NewMask(NumMaskElts, Zero);
1531 for (unsigned i = 0; i != NumMaskElts; ++i)
1532 if (isa<UndefValue>(Mask->getAggregateElement(i)))
1533 NewMask[i] = Mask->getAggregateElement(i);
1534
1535 return new ShuffleVectorInst(NewIns, UndefVec, ConstantVector::get(NewMask));
1536}
1537
Sanjay Patelb999d742018-07-02 17:42:29 +00001538/// Try to fold shuffles that are the equivalent of a vector select.
Sanjay Patelda667532018-06-29 13:44:06 +00001539static Instruction *foldSelectShuffle(ShuffleVectorInst &Shuf,
Sanjay Patelb999d742018-07-02 17:42:29 +00001540 InstCombiner::BuilderTy &Builder,
1541 const DataLayout &DL) {
Sanjay Patela76b7002018-06-21 20:15:09 +00001542 if (!Shuf.isSelect())
1543 return nullptr;
1544
Sanjay Patele85d2e42019-11-25 11:55:57 -05001545 // Canonicalize to choose from operand 0 first unless operand 1 is undefined.
1546 // Commuting undef to operand 0 conflicts with another canonicalization.
Sanjay Patelb276dd12019-03-31 15:01:30 +00001547 unsigned NumElts = Shuf.getType()->getVectorNumElements();
Sanjay Patele85d2e42019-11-25 11:55:57 -05001548 if (!isa<UndefValue>(Shuf.getOperand(1)) &&
1549 Shuf.getMaskValue(0) >= (int)NumElts) {
Sanjay Patelb33938d2019-04-08 13:28:29 +00001550 // TODO: Can we assert that both operands of a shuffle-select are not undef
1551 // (otherwise, it would have been folded by instsimplify?
Sanjay Patelb276dd12019-03-31 15:01:30 +00001552 Shuf.commute();
1553 return &Shuf;
1554 }
1555
Sanjay Patel3074b9e2018-07-03 13:44:22 +00001556 if (Instruction *I = foldSelectShuffleWith1Binop(Shuf))
1557 return I;
1558
Sanjay Patela76b7002018-06-21 20:15:09 +00001559 BinaryOperator *B0, *B1;
1560 if (!match(Shuf.getOperand(0), m_BinOp(B0)) ||
1561 !match(Shuf.getOperand(1), m_BinOp(B1)))
1562 return nullptr;
1563
Sanjay Patelda667532018-06-29 13:44:06 +00001564 Value *X, *Y;
Sanjay Patela76b7002018-06-21 20:15:09 +00001565 Constant *C0, *C1;
Sanjay Patela52963b2018-06-22 12:46:16 +00001566 bool ConstantsAreOp1;
1567 if (match(B0, m_BinOp(m_Value(X), m_Constant(C0))) &&
Sanjay Patelda667532018-06-29 13:44:06 +00001568 match(B1, m_BinOp(m_Value(Y), m_Constant(C1))))
Sanjay Patela52963b2018-06-22 12:46:16 +00001569 ConstantsAreOp1 = true;
1570 else if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) &&
Sanjay Patelda667532018-06-29 13:44:06 +00001571 match(B1, m_BinOp(m_Constant(C1), m_Value(Y))))
Sanjay Patela52963b2018-06-22 12:46:16 +00001572 ConstantsAreOp1 = false;
1573 else
Sanjay Patela76b7002018-06-21 20:15:09 +00001574 return nullptr;
1575
Sanjay Patel57bda362018-06-28 17:48:04 +00001576 // We need matching binops to fold the lanes together.
1577 BinaryOperator::BinaryOps Opc0 = B0->getOpcode();
1578 BinaryOperator::BinaryOps Opc1 = B1->getOpcode();
1579 bool DropNSW = false;
1580 if (ConstantsAreOp1 && Opc0 != Opc1) {
Sanjay Patel57bda362018-06-28 17:48:04 +00001581 // TODO: We drop "nsw" if shift is converted into multiply because it may
1582 // not be correct when the shift amount is BitWidth - 1. We could examine
1583 // each vector element to determine if it is safe to keep that flag.
Sanjay Patelb999d742018-07-02 17:42:29 +00001584 if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl)
Sanjay Patel57bda362018-06-28 17:48:04 +00001585 DropNSW = true;
Sanjay Patelb999d742018-07-02 17:42:29 +00001586 if (BinopElts AltB0 = getAlternateBinop(B0, DL)) {
1587 assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop");
1588 Opc0 = AltB0.Opcode;
1589 C0 = cast<Constant>(AltB0.Op1);
1590 } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) {
1591 assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop");
1592 Opc1 = AltB1.Opcode;
1593 C1 = cast<Constant>(AltB1.Op1);
Sanjay Patel57bda362018-06-28 17:48:04 +00001594 }
1595 }
1596
1597 if (Opc0 != Opc1)
Sanjay Patel4784e152018-06-21 23:56:59 +00001598 return nullptr;
1599
Sanjay Patel57bda362018-06-28 17:48:04 +00001600 // The opcodes must be the same. Use a new name to make that clear.
1601 BinaryOperator::BinaryOps BOpc = Opc0;
1602
Sanjay Patel06ea4202018-07-10 13:33:26 +00001603 // Select the constant elements needed for the single binop.
1604 Constant *Mask = Shuf.getMask();
1605 Constant *NewC = ConstantExpr::getShuffleVector(C0, C1, Mask);
1606
Sanjay Patel5bd36642018-07-09 13:21:46 +00001607 // We are moving a binop after a shuffle. When a shuffle has an undefined
1608 // mask element, the result is undefined, but it is not poison or undefined
1609 // behavior. That is not necessarily true for div/rem/shift.
Sanjay Patel5bd36642018-07-09 13:21:46 +00001610 bool MightCreatePoisonOrUB =
1611 Mask->containsUndefElement() &&
1612 (Instruction::isIntDivRem(BOpc) || Instruction::isShift(BOpc));
Sanjay Patel06ea4202018-07-10 13:33:26 +00001613 if (MightCreatePoisonOrUB)
1614 NewC = getSafeVectorConstantForBinop(BOpc, NewC, ConstantsAreOp1);
Sanjay Patel5bd36642018-07-09 13:21:46 +00001615
Sanjay Patelda667532018-06-29 13:44:06 +00001616 Value *V;
1617 if (X == Y) {
1618 // Remove a binop and the shuffle by rearranging the constant:
1619 // shuffle (op V, C0), (op V, C1), M --> op V, C'
1620 // shuffle (op C0, V), (op C1, V), M --> op C', V
1621 V = X;
Sanjay Patel5bd36642018-07-09 13:21:46 +00001622 } else {
Sanjay Patelda667532018-06-29 13:44:06 +00001623 // If there are 2 different variable operands, we must create a new shuffle
1624 // (select) first, so check uses to ensure that we don't end up with more
1625 // instructions than we started with.
Sanjay Patel5bd36642018-07-09 13:21:46 +00001626 if (!B0->hasOneUse() && !B1->hasOneUse())
1627 return nullptr;
1628
Sanjay Patel06ea4202018-07-10 13:33:26 +00001629 // If we use the original shuffle mask and op1 is *variable*, we would be
1630 // putting an undef into operand 1 of div/rem/shift. This is either UB or
1631 // poison. We do not have to guard against UB when *constants* are op1
1632 // because safe constants guarantee that we do not overflow sdiv/srem (and
1633 // there's no danger for other opcodes).
1634 // TODO: To allow this case, create a new shuffle mask with no undefs.
1635 if (MightCreatePoisonOrUB && !ConstantsAreOp1)
Sanjay Patel5bd36642018-07-09 13:21:46 +00001636 return nullptr;
1637
Sanjay Patelda667532018-06-29 13:44:06 +00001638 // Note: In general, we do not create new shuffles in InstCombine because we
1639 // do not know if a target can lower an arbitrary shuffle optimally. In this
1640 // case, the shuffle uses the existing mask, so there is no additional risk.
Sanjay Patelda667532018-06-29 13:44:06 +00001641
1642 // Select the variable vectors first, then perform the binop:
1643 // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C'
1644 // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M)
Sanjay Patel5bd36642018-07-09 13:21:46 +00001645 V = Builder.CreateShuffleVector(X, Y, Mask);
Sanjay Patelda667532018-06-29 13:44:06 +00001646 }
1647
Sanjay Patelda667532018-06-29 13:44:06 +00001648 Instruction *NewBO = ConstantsAreOp1 ? BinaryOperator::Create(BOpc, V, NewC) :
1649 BinaryOperator::Create(BOpc, NewC, V);
Sanjay Patela76b7002018-06-21 20:15:09 +00001650
Sanjay Patel5bd36642018-07-09 13:21:46 +00001651 // Flags are intersected from the 2 source binops. But there are 2 exceptions:
1652 // 1. If we changed an opcode, poison conditions might have changed.
1653 // 2. If the shuffle had undef mask elements, the new binop might have undefs
Sanjay Patelc8d9d812018-07-10 16:09:49 +00001654 // where the original code did not. But if we already made a safe constant,
1655 // then there's no danger.
Sanjay Patela76b7002018-06-21 20:15:09 +00001656 NewBO->copyIRFlags(B0);
1657 NewBO->andIRFlags(B1);
Sanjay Patel57bda362018-06-28 17:48:04 +00001658 if (DropNSW)
1659 NewBO->setHasNoSignedWrap(false);
Sanjay Patelc8d9d812018-07-10 16:09:49 +00001660 if (Mask->containsUndefElement() && !MightCreatePoisonOrUB)
Sanjay Patel5bd36642018-07-09 13:21:46 +00001661 NewBO->dropPoisonGeneratingFlags();
Sanjay Patela76b7002018-06-21 20:15:09 +00001662 return NewBO;
1663}
1664
Sanjay Patelc1416b62018-09-07 21:03:34 +00001665/// Match a shuffle-select-shuffle pattern where the shuffles are widening and
1666/// narrowing (concatenating with undef and extracting back to the original
1667/// length). This allows replacing the wide select with a narrow select.
Sanjay Patel88194df2018-10-09 15:29:26 +00001668static Instruction *narrowVectorSelect(ShuffleVectorInst &Shuf,
1669 InstCombiner::BuilderTy &Builder) {
Sanjay Patelc1416b62018-09-07 21:03:34 +00001670 // This must be a narrowing identity shuffle. It extracts the 1st N elements
1671 // of the 1st vector operand of a shuffle.
1672 if (!match(Shuf.getOperand(1), m_Undef()) || !Shuf.isIdentityWithExtract())
1673 return nullptr;
1674
1675 // The vector being shuffled must be a vector select that we can eliminate.
1676 // TODO: The one-use requirement could be eased if X and/or Y are constants.
1677 Value *Cond, *X, *Y;
1678 if (!match(Shuf.getOperand(0),
1679 m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))))
1680 return nullptr;
1681
1682 // We need a narrow condition value. It must be extended with undef elements
1683 // and have the same number of elements as this shuffle.
1684 unsigned NarrowNumElts = Shuf.getType()->getVectorNumElements();
1685 Value *NarrowCond;
1686 if (!match(Cond, m_OneUse(m_ShuffleVector(m_Value(NarrowCond), m_Undef(),
1687 m_Constant()))) ||
1688 NarrowCond->getType()->getVectorNumElements() != NarrowNumElts ||
1689 !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding())
1690 return nullptr;
1691
1692 // shuf (sel (shuf NarrowCond, undef, WideMask), X, Y), undef, NarrowMask) -->
1693 // sel NarrowCond, (shuf X, undef, NarrowMask), (shuf Y, undef, NarrowMask)
1694 Value *Undef = UndefValue::get(X->getType());
1695 Value *NarrowX = Builder.CreateShuffleVector(X, Undef, Shuf.getMask());
1696 Value *NarrowY = Builder.CreateShuffleVector(Y, Undef, Shuf.getMask());
1697 return SelectInst::Create(NarrowCond, NarrowX, NarrowY);
1698}
1699
Sanjay Patel71811462018-10-14 15:25:06 +00001700/// Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask.
1701static Instruction *foldIdentityExtractShuffle(ShuffleVectorInst &Shuf) {
1702 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
1703 if (!Shuf.isIdentityWithExtract() || !isa<UndefValue>(Op1))
1704 return nullptr;
1705
1706 Value *X, *Y;
1707 Constant *Mask;
1708 if (!match(Op0, m_ShuffleVector(m_Value(X), m_Value(Y), m_Constant(Mask))))
1709 return nullptr;
1710
Sanjay Patelcddb1e52019-02-05 22:58:45 +00001711 // Be conservative with shuffle transforms. If we can't kill the 1st shuffle,
1712 // then combining may result in worse codegen.
1713 if (!Op0->hasOneUse())
1714 return nullptr;
1715
Sanjay Patel71811462018-10-14 15:25:06 +00001716 // We are extracting a subvector from a shuffle. Remove excess elements from
1717 // the 1st shuffle mask to eliminate the extract.
1718 //
1719 // This transform is conservatively limited to identity extracts because we do
1720 // not allow arbitrary shuffle mask creation as a target-independent transform
1721 // (because we can't guarantee that will lower efficiently).
1722 //
1723 // If the extracting shuffle has an undef mask element, it transfers to the
1724 // new shuffle mask. Otherwise, copy the original mask element. Example:
1725 // shuf (shuf X, Y, <C0, C1, C2, undef, C4>), undef, <0, undef, 2, 3> -->
1726 // shuf X, Y, <C0, undef, C2, undef>
1727 unsigned NumElts = Shuf.getType()->getVectorNumElements();
1728 SmallVector<Constant *, 16> NewMask(NumElts);
1729 assert(NumElts < Mask->getType()->getVectorNumElements() &&
1730 "Identity with extract must have less elements than its inputs");
1731
1732 for (unsigned i = 0; i != NumElts; ++i) {
1733 Constant *ExtractMaskElt = Shuf.getMask()->getAggregateElement(i);
1734 Constant *MaskElt = Mask->getAggregateElement(i);
1735 NewMask[i] = isa<UndefValue>(ExtractMaskElt) ? ExtractMaskElt : MaskElt;
1736 }
1737 return new ShuffleVectorInst(X, Y, ConstantVector::get(NewMask));
1738}
1739
Sanjay Patel396d18a2019-12-10 10:10:05 -05001740/// Try to replace a shuffle with an insertelement or try to replace a shuffle
1741/// operand with the operand of an insertelement.
Nikita Popov5a8819b2020-02-03 21:17:36 +01001742static Instruction *foldShuffleWithInsert(ShuffleVectorInst &Shuf,
1743 InstCombiner &IC) {
Sanjay Patelb12e4102018-10-30 15:26:39 +00001744 Value *V0 = Shuf.getOperand(0), *V1 = Shuf.getOperand(1);
1745 SmallVector<int, 16> Mask = Shuf.getShuffleMask();
1746
1747 // The shuffle must not change vector sizes.
1748 // TODO: This restriction could be removed if the insert has only one use
1749 // (because the transform would require a new length-changing shuffle).
1750 int NumElts = Mask.size();
1751 if (NumElts != (int)(V0->getType()->getVectorNumElements()))
1752 return nullptr;
1753
Sanjay Patel396d18a2019-12-10 10:10:05 -05001754 // This is a specialization of a fold in SimplifyDemandedVectorElts. We may
1755 // not be able to handle it there if the insertelement has >1 use.
1756 // If the shuffle has an insertelement operand but does not choose the
1757 // inserted scalar element from that value, then we can replace that shuffle
1758 // operand with the source vector of the insertelement.
1759 Value *X;
1760 uint64_t IdxC;
1761 if (match(V0, m_InsertElement(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
1762 // shuf (inselt X, ?, IdxC), ?, Mask --> shuf X, ?, Mask
Nikita Popov5a8819b2020-02-03 21:17:36 +01001763 if (none_of(Mask, [IdxC](int MaskElt) { return MaskElt == (int)IdxC; }))
1764 return IC.replaceOperand(Shuf, 0, X);
Sanjay Patel396d18a2019-12-10 10:10:05 -05001765 }
1766 if (match(V1, m_InsertElement(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
1767 // Offset the index constant by the vector width because we are checking for
1768 // accesses to the 2nd vector input of the shuffle.
1769 IdxC += NumElts;
1770 // shuf ?, (inselt X, ?, IdxC), Mask --> shuf ?, X, Mask
Nikita Popov5a8819b2020-02-03 21:17:36 +01001771 if (none_of(Mask, [IdxC](int MaskElt) { return MaskElt == (int)IdxC; }))
1772 return IC.replaceOperand(Shuf, 1, X);
Sanjay Patel396d18a2019-12-10 10:10:05 -05001773 }
1774
Sanjay Patelb12e4102018-10-30 15:26:39 +00001775 // shuffle (insert ?, Scalar, IndexC), V1, Mask --> insert V1, Scalar, IndexC'
1776 auto isShufflingScalarIntoOp1 = [&](Value *&Scalar, ConstantInt *&IndexC) {
1777 // We need an insertelement with a constant index.
1778 if (!match(V0, m_InsertElement(m_Value(), m_Value(Scalar),
1779 m_ConstantInt(IndexC))))
1780 return false;
1781
1782 // Test the shuffle mask to see if it splices the inserted scalar into the
1783 // operand 1 vector of the shuffle.
1784 int NewInsIndex = -1;
1785 for (int i = 0; i != NumElts; ++i) {
1786 // Ignore undef mask elements.
1787 if (Mask[i] == -1)
1788 continue;
1789
1790 // The shuffle takes elements of operand 1 without lane changes.
1791 if (Mask[i] == NumElts + i)
1792 continue;
1793
1794 // The shuffle must choose the inserted scalar exactly once.
1795 if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue())
1796 return false;
1797
1798 // The shuffle is placing the inserted scalar into element i.
1799 NewInsIndex = i;
1800 }
1801
1802 assert(NewInsIndex != -1 && "Did not fold shuffle with unused operand?");
1803
1804 // Index is updated to the potentially translated insertion lane.
1805 IndexC = ConstantInt::get(IndexC->getType(), NewInsIndex);
1806 return true;
1807 };
1808
1809 // If the shuffle is unnecessary, insert the scalar operand directly into
1810 // operand 1 of the shuffle. Example:
1811 // shuffle (insert ?, S, 1), V1, <1, 5, 6, 7> --> insert V1, S, 0
1812 Value *Scalar;
1813 ConstantInt *IndexC;
1814 if (isShufflingScalarIntoOp1(Scalar, IndexC))
1815 return InsertElementInst::Create(V1, Scalar, IndexC);
1816
1817 // Try again after commuting shuffle. Example:
1818 // shuffle V0, (insert ?, S, 0), <0, 1, 2, 4> -->
1819 // shuffle (insert ?, S, 0), V0, <4, 5, 6, 0> --> insert V0, S, 3
1820 std::swap(V0, V1);
1821 ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
1822 if (isShufflingScalarIntoOp1(Scalar, IndexC))
1823 return InsertElementInst::Create(V1, Scalar, IndexC);
1824
1825 return nullptr;
1826}
1827
Sanjay Patel6a554182019-05-22 00:32:25 +00001828static Instruction *foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf) {
1829 // Match the operands as identity with padding (also known as concatenation
1830 // with undef) shuffles of the same source type. The backend is expected to
1831 // recreate these concatenations from a shuffle of narrow operands.
1832 auto *Shuffle0 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(0));
1833 auto *Shuffle1 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(1));
1834 if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() ||
1835 !Shuffle1 || !Shuffle1->isIdentityWithPadding())
1836 return nullptr;
1837
1838 // We limit this transform to power-of-2 types because we expect that the
1839 // backend can convert the simplified IR patterns to identical nodes as the
1840 // original IR.
Sanjay Patel3249be12019-05-23 18:46:03 +00001841 // TODO: If we can verify the same behavior for arbitrary types, the
1842 // power-of-2 checks can be removed.
Sanjay Patel6a554182019-05-22 00:32:25 +00001843 Value *X = Shuffle0->getOperand(0);
1844 Value *Y = Shuffle1->getOperand(0);
1845 if (X->getType() != Y->getType() ||
1846 !isPowerOf2_32(Shuf.getType()->getVectorNumElements()) ||
1847 !isPowerOf2_32(Shuffle0->getType()->getVectorNumElements()) ||
1848 !isPowerOf2_32(X->getType()->getVectorNumElements()) ||
1849 isa<UndefValue>(X) || isa<UndefValue>(Y))
1850 return nullptr;
1851 assert(isa<UndefValue>(Shuffle0->getOperand(1)) &&
1852 isa<UndefValue>(Shuffle1->getOperand(1)) &&
1853 "Unexpected operand for identity shuffle");
1854
1855 // This is a shuffle of 2 widening shuffles. We can shuffle the narrow source
1856 // operands directly by adjusting the shuffle mask to account for the narrower
1857 // types:
1858 // shuf (widen X), (widen Y), Mask --> shuf X, Y, Mask'
1859 int NarrowElts = X->getType()->getVectorNumElements();
1860 int WideElts = Shuffle0->getType()->getVectorNumElements();
1861 assert(WideElts > NarrowElts && "Unexpected types for identity with padding");
1862
1863 Type *I32Ty = IntegerType::getInt32Ty(Shuf.getContext());
1864 SmallVector<int, 16> Mask = Shuf.getShuffleMask();
1865 SmallVector<Constant *, 16> NewMask(Mask.size(), UndefValue::get(I32Ty));
1866 for (int i = 0, e = Mask.size(); i != e; ++i) {
1867 if (Mask[i] == -1)
1868 continue;
Sanjay Patel3249be12019-05-23 18:46:03 +00001869
1870 // If this shuffle is choosing an undef element from 1 of the sources, that
1871 // element is undef.
1872 if (Mask[i] < WideElts) {
1873 if (Shuffle0->getMaskValue(Mask[i]) == -1)
1874 continue;
1875 } else {
1876 if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1)
1877 continue;
1878 }
1879
1880 // If this shuffle is choosing from the 1st narrow op, the mask element is
1881 // the same. If this shuffle is choosing from the 2nd narrow op, the mask
1882 // element is offset down to adjust for the narrow vector widths.
1883 if (Mask[i] < WideElts) {
1884 assert(Mask[i] < NarrowElts && "Unexpected shuffle mask");
Sanjay Patel6a554182019-05-22 00:32:25 +00001885 NewMask[i] = ConstantInt::get(I32Ty, Mask[i]);
Sanjay Patel3249be12019-05-23 18:46:03 +00001886 } else {
1887 assert(Mask[i] < (WideElts + NarrowElts) && "Unexpected shuffle mask");
Sanjay Patel6a554182019-05-22 00:32:25 +00001888 NewMask[i] = ConstantInt::get(I32Ty, Mask[i] - (WideElts - NarrowElts));
Sanjay Patel3249be12019-05-23 18:46:03 +00001889 }
Sanjay Patel6a554182019-05-22 00:32:25 +00001890 }
1891 return new ShuffleVectorInst(X, Y, ConstantVector::get(NewMask));
1892}
1893
Chris Lattnerec97a902010-01-05 05:36:20 +00001894Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
1895 Value *LHS = SVI.getOperand(0);
1896 Value *RHS = SVI.getOperand(1);
Craig Toppera4205622017-06-09 03:21:29 +00001897 if (auto *V = SimplifyShuffleVectorInst(
1898 LHS, RHS, SVI.getMask(), SVI.getType(), SQ.getWithInstruction(&SVI)))
Zvi Rackover82bf48d2017-04-04 04:47:57 +00001899 return replaceInstUsesWith(SVI, V);
1900
Sanjay Patel35827162019-11-25 13:30:45 -05001901 // shuffle x, x, mask --> shuffle x, undef, mask'
Sanjay Patel3f4d1b42019-03-29 16:49:38 +00001902 unsigned VWidth = SVI.getType()->getVectorNumElements();
1903 unsigned LHSWidth = LHS->getType()->getVectorNumElements();
1904 SmallVector<int, 16> Mask = SVI.getShuffleMask();
1905 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
Sanjay Patel35827162019-11-25 13:30:45 -05001906 if (LHS == RHS) {
Sanjay Patel847aabf2019-11-25 10:54:18 -05001907 assert(!isa<UndefValue>(RHS) && "Shuffle with 2 undef ops not simplified?");
Chris Lattnerec97a902010-01-05 05:36:20 +00001908 // Remap any references to RHS to use LHS.
Chris Lattner0256be92012-01-27 03:08:05 +00001909 SmallVector<Constant*, 16> Elts;
Sanjay Patel20684092019-11-25 10:40:21 -05001910 for (unsigned i = 0; i != VWidth; ++i) {
Sanjay Patel35827162019-11-25 13:30:45 -05001911 // Propagate undef elements or force mask to LHS.
1912 if (Mask[i] < 0)
JF Bastiend52c9902015-02-25 22:30:51 +00001913 Elts.push_back(UndefValue::get(Int32Ty));
Sanjay Patelfc31b582019-11-25 11:11:12 -05001914 else
1915 Elts.push_back(ConstantInt::get(Int32Ty, Mask[i] % LHSWidth));
Chris Lattnerec97a902010-01-05 05:36:20 +00001916 }
Nikita Popovd4627b92020-02-08 17:02:10 +01001917 return new ShuffleVectorInst(LHS, UndefValue::get(RHS->getType()),
1918 ConstantVector::get(Elts));
Chris Lattnerec97a902010-01-05 05:36:20 +00001919 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00001920
Sanjay Patel35827162019-11-25 13:30:45 -05001921 // shuffle undef, x, mask --> shuffle x, undef, mask'
1922 if (isa<UndefValue>(LHS)) {
1923 SVI.commute();
1924 return &SVI;
1925 }
1926
Sanjay Patel0b591032019-07-08 16:26:48 +00001927 if (Instruction *I = canonicalizeInsertSplat(SVI, Builder))
1928 return I;
1929
Sanjay Patel3f4d1b42019-03-29 16:49:38 +00001930 if (Instruction *I = foldSelectShuffle(SVI, Builder, DL))
1931 return I;
1932
1933 if (Instruction *I = narrowVectorSelect(SVI, Builder))
1934 return I;
1935
1936 APInt UndefElts(VWidth, 0);
1937 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
1938 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
1939 if (V != &SVI)
1940 return replaceInstUsesWith(SVI, V);
1941 return &SVI;
1942 }
1943
1944 if (Instruction *I = foldIdentityExtractShuffle(SVI))
1945 return I;
1946
Sanjay Patel6a554182019-05-22 00:32:25 +00001947 // These transforms have the potential to lose undef knowledge, so they are
Sanjay Patel3f4d1b42019-03-29 16:49:38 +00001948 // intentionally placed after SimplifyDemandedVectorElts().
Nikita Popov5a8819b2020-02-03 21:17:36 +01001949 if (Instruction *I = foldShuffleWithInsert(SVI, *this))
Sanjay Patel3f4d1b42019-03-29 16:49:38 +00001950 return I;
Sanjay Patel6a554182019-05-22 00:32:25 +00001951 if (Instruction *I = foldIdentityPaddedShuffles(SVI))
1952 return I;
Sanjay Patel3f4d1b42019-03-29 16:49:38 +00001953
Sanjay Patel26c119a2018-09-30 13:50:42 +00001954 if (isa<UndefValue>(RHS) && canEvaluateShuffled(LHS, Mask)) {
Sanjay Patel54d31ef2018-09-29 15:05:24 +00001955 Value *V = evaluateInDifferentElementOrder(LHS, Mask);
Sanjay Patel4b198802016-02-01 22:23:39 +00001956 return replaceInstUsesWith(SVI, V);
Nick Lewyckya2b77202013-05-31 00:59:42 +00001957 }
1958
JF Bastiend52c9902015-02-25 22:30:51 +00001959 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
1960 // a non-vector type. We can instead bitcast the original vector followed by
1961 // an extract of the desired element:
1962 //
1963 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
1964 // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
1965 // %1 = bitcast <4 x i8> %sroa to i32
1966 // Becomes:
1967 // %bc = bitcast <16 x i8> %in to <4 x i32>
1968 // %ext = extractelement <4 x i32> %bc, i32 0
1969 //
1970 // If the shuffle is extracting a contiguous range of values from the input
1971 // vector then each use which is a bitcast of the extracted size can be
1972 // replaced. This will work if the vector types are compatible, and the begin
1973 // index is aligned to a value in the casted vector type. If the begin index
1974 // isn't aligned then we can shuffle the original vector (keeping the same
1975 // vector type) before extracting.
1976 //
1977 // This code will bail out if the target type is fundamentally incompatible
1978 // with vectors of the source type.
1979 //
1980 // Example of <16 x i8>, target type i32:
1981 // Index range [4,8): v-----------v Will work.
1982 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1983 // <16 x i8>: | | | | | | | | | | | | | | | | |
1984 // <4 x i32>: | | | | |
1985 // +-----------+-----------+-----------+-----------+
1986 // Index range [6,10): ^-----------^ Needs an extra shuffle.
1987 // Target type i40: ^--------------^ Won't work, bail.
Sanjay Patel3f4d1b42019-03-29 16:49:38 +00001988 bool MadeChange = false;
JF Bastiend52c9902015-02-25 22:30:51 +00001989 if (isShuffleExtractingFromLHS(SVI, Mask)) {
1990 Value *V = LHS;
1991 unsigned MaskElems = Mask.size();
JF Bastiend52c9902015-02-25 22:30:51 +00001992 VectorType *SrcTy = cast<VectorType>(V->getType());
1993 unsigned VecBitWidth = SrcTy->getBitWidth();
David Majnemer98cfe2b2015-04-03 20:18:40 +00001994 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
JF Bastiend52c9902015-02-25 22:30:51 +00001995 assert(SrcElemBitWidth && "vector elements must have a bitwidth");
1996 unsigned SrcNumElems = SrcTy->getNumElements();
1997 SmallVector<BitCastInst *, 8> BCs;
1998 DenseMap<Type *, Value *> NewBCs;
1999 for (User *U : SVI.users())
2000 if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
2001 if (!BC->use_empty())
2002 // Only visit bitcasts that weren't previously handled.
2003 BCs.push_back(BC);
2004 for (BitCastInst *BC : BCs) {
Eugene Leviant958fcd72017-02-17 07:36:03 +00002005 unsigned BegIdx = Mask.front();
JF Bastiend52c9902015-02-25 22:30:51 +00002006 Type *TgtTy = BC->getDestTy();
David Majnemer98cfe2b2015-04-03 20:18:40 +00002007 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
JF Bastiend52c9902015-02-25 22:30:51 +00002008 if (!TgtElemBitWidth)
2009 continue;
2010 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
2011 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
2012 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
2013 if (!VecBitWidthsEqual)
2014 continue;
2015 if (!VectorType::isValidElementType(TgtTy))
2016 continue;
2017 VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems);
2018 if (!BegIsAligned) {
2019 // Shuffle the input so [0,NumElements) contains the output, and
2020 // [NumElems,SrcNumElems) is undef.
2021 SmallVector<Constant *, 16> ShuffleMask(SrcNumElems,
2022 UndefValue::get(Int32Ty));
2023 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
2024 ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx);
Craig Topperbb4069e2017-07-07 23:16:26 +00002025 V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
2026 ConstantVector::get(ShuffleMask),
2027 SVI.getName() + ".extract");
JF Bastiend52c9902015-02-25 22:30:51 +00002028 BegIdx = 0;
2029 }
2030 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
2031 assert(SrcElemsPerTgtElem);
2032 BegIdx /= SrcElemsPerTgtElem;
2033 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
2034 auto *NewBC =
2035 BCAlreadyExists
2036 ? NewBCs[CastSrcTy]
Craig Topperbb4069e2017-07-07 23:16:26 +00002037 : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
JF Bastiend52c9902015-02-25 22:30:51 +00002038 if (!BCAlreadyExists)
2039 NewBCs[CastSrcTy] = NewBC;
Craig Topperbb4069e2017-07-07 23:16:26 +00002040 auto *Ext = Builder.CreateExtractElement(
JF Bastiend52c9902015-02-25 22:30:51 +00002041 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
2042 // The shufflevector isn't being replaced: the bitcast that used it
2043 // is. InstCombine will visit the newly-created instructions.
Sanjay Patel4b198802016-02-01 22:23:39 +00002044 replaceInstUsesWith(*BC, Ext);
JF Bastiend52c9902015-02-25 22:30:51 +00002045 MadeChange = true;
2046 }
2047 }
2048
Eric Christopher51edc7b2010-08-17 22:55:27 +00002049 // If the LHS is a shufflevector itself, see if we can combine it with this
Eli Friedmance818272011-10-21 19:06:29 +00002050 // one without producing an unusual shuffle.
2051 // Cases that might be simplified:
2052 // 1.
2053 // x1=shuffle(v1,v2,mask1)
2054 // x=shuffle(x1,undef,mask)
2055 // ==>
2056 // x=shuffle(v1,undef,newMask)
2057 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
2058 // 2.
2059 // x1=shuffle(v1,undef,mask1)
2060 // x=shuffle(x1,x2,mask)
2061 // where v1.size() == mask1.size()
2062 // ==>
2063 // x=shuffle(v1,x2,newMask)
2064 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
2065 // 3.
2066 // x2=shuffle(v2,undef,mask2)
2067 // x=shuffle(x1,x2,mask)
2068 // where v2.size() == mask2.size()
2069 // ==>
2070 // x=shuffle(x1,v2,newMask)
2071 // newMask[i] = (mask[i] < x1.size())
2072 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
2073 // 4.
2074 // x1=shuffle(v1,undef,mask1)
2075 // x2=shuffle(v2,undef,mask2)
2076 // x=shuffle(x1,x2,mask)
2077 // where v1.size() == v2.size()
2078 // ==>
2079 // x=shuffle(v1,v2,newMask)
2080 // newMask[i] = (mask[i] < x1.size())
2081 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
2082 //
2083 // Here we are really conservative:
Eric Christopher51edc7b2010-08-17 22:55:27 +00002084 // we are absolutely afraid of producing a shuffle mask not in the input
2085 // program, because the code gen may not be smart enough to turn a merged
2086 // shuffle into two specific shuffles: it may produce worse code. As such,
Jim Grosbachd11584a2013-05-01 00:25:27 +00002087 // we only merge two shuffles if the result is either a splat or one of the
2088 // input shuffle masks. In this case, merging the shuffles just removes
2089 // one instruction, which we know is safe. This is good for things like
Eli Friedmance818272011-10-21 19:06:29 +00002090 // turning: (splat(splat)) -> splat, or
2091 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
2092 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
2093 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
2094 if (LHSShuffle)
2095 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS))
Craig Topperf40110f2014-04-25 05:29:35 +00002096 LHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00002097 if (RHSShuffle)
2098 if (!isa<UndefValue>(RHSShuffle->getOperand(1)))
Craig Topperf40110f2014-04-25 05:29:35 +00002099 RHSShuffle = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00002100 if (!LHSShuffle && !RHSShuffle)
Craig Topperf40110f2014-04-25 05:29:35 +00002101 return MadeChange ? &SVI : nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00002102
Craig Topperf40110f2014-04-25 05:29:35 +00002103 Value* LHSOp0 = nullptr;
2104 Value* LHSOp1 = nullptr;
2105 Value* RHSOp0 = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00002106 unsigned LHSOp0Width = 0;
2107 unsigned RHSOp0Width = 0;
2108 if (LHSShuffle) {
2109 LHSOp0 = LHSShuffle->getOperand(0);
2110 LHSOp1 = LHSShuffle->getOperand(1);
Craig Topper17b55682016-12-29 07:03:18 +00002111 LHSOp0Width = LHSOp0->getType()->getVectorNumElements();
Eli Friedmance818272011-10-21 19:06:29 +00002112 }
2113 if (RHSShuffle) {
2114 RHSOp0 = RHSShuffle->getOperand(0);
Craig Topper17b55682016-12-29 07:03:18 +00002115 RHSOp0Width = RHSOp0->getType()->getVectorNumElements();
Eli Friedmance818272011-10-21 19:06:29 +00002116 }
2117 Value* newLHS = LHS;
2118 Value* newRHS = RHS;
2119 if (LHSShuffle) {
2120 // case 1
Eric Christopher51edc7b2010-08-17 22:55:27 +00002121 if (isa<UndefValue>(RHS)) {
Eli Friedmance818272011-10-21 19:06:29 +00002122 newLHS = LHSOp0;
2123 newRHS = LHSOp1;
2124 }
2125 // case 2 or 4
2126 else if (LHSOp0Width == LHSWidth) {
2127 newLHS = LHSOp0;
2128 }
2129 }
2130 // case 3 or 4
2131 if (RHSShuffle && RHSOp0Width == LHSWidth) {
2132 newRHS = RHSOp0;
2133 }
2134 // case 4
2135 if (LHSOp0 == RHSOp0) {
2136 newLHS = LHSOp0;
Craig Topperf40110f2014-04-25 05:29:35 +00002137 newRHS = nullptr;
Eli Friedmance818272011-10-21 19:06:29 +00002138 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00002139
Eli Friedmance818272011-10-21 19:06:29 +00002140 if (newLHS == LHS && newRHS == RHS)
Craig Topperf40110f2014-04-25 05:29:35 +00002141 return MadeChange ? &SVI : nullptr;
Bob Wilson8ecf98b2010-10-29 22:20:43 +00002142
Eli Friedmance818272011-10-21 19:06:29 +00002143 SmallVector<int, 16> LHSMask;
2144 SmallVector<int, 16> RHSMask;
Chris Lattner8326bd82012-01-26 00:42:34 +00002145 if (newLHS != LHS)
2146 LHSMask = LHSShuffle->getShuffleMask();
2147 if (RHSShuffle && newRHS != RHS)
2148 RHSMask = RHSShuffle->getShuffleMask();
2149
Eli Friedmance818272011-10-21 19:06:29 +00002150 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
2151 SmallVector<int, 16> newMask;
2152 bool isSplat = true;
2153 int SplatElt = -1;
2154 // Create a new mask for the new ShuffleVectorInst so that the new
2155 // ShuffleVectorInst is equivalent to the original one.
2156 for (unsigned i = 0; i < VWidth; ++i) {
2157 int eltMask;
Craig Topper45d9f4b2013-01-18 05:30:07 +00002158 if (Mask[i] < 0) {
Eli Friedmance818272011-10-21 19:06:29 +00002159 // This element is an undef value.
2160 eltMask = -1;
2161 } else if (Mask[i] < (int)LHSWidth) {
2162 // This element is from left hand side vector operand.
Craig Topper2ea22b02013-01-18 05:09:16 +00002163 //
Eli Friedmance818272011-10-21 19:06:29 +00002164 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
2165 // new mask value for the element.
2166 if (newLHS != LHS) {
2167 eltMask = LHSMask[Mask[i]];
2168 // If the value selected is an undef value, explicitly specify it
2169 // with a -1 mask value.
2170 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
2171 eltMask = -1;
Craig Topper2ea22b02013-01-18 05:09:16 +00002172 } else
Eli Friedmance818272011-10-21 19:06:29 +00002173 eltMask = Mask[i];
2174 } else {
2175 // This element is from right hand side vector operand
2176 //
2177 // If the value selected is an undef value, explicitly specify it
2178 // with a -1 mask value. (case 1)
2179 if (isa<UndefValue>(RHS))
2180 eltMask = -1;
2181 // If RHS is going to be replaced (case 3 or 4), calculate the
2182 // new mask value for the element.
2183 else if (newRHS != RHS) {
2184 eltMask = RHSMask[Mask[i]-LHSWidth];
2185 // If the value selected is an undef value, explicitly specify it
2186 // with a -1 mask value.
2187 if (eltMask >= (int)RHSOp0Width) {
2188 assert(isa<UndefValue>(RHSShuffle->getOperand(1))
2189 && "should have been check above");
2190 eltMask = -1;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00002191 }
Craig Topper2ea22b02013-01-18 05:09:16 +00002192 } else
Eli Friedmance818272011-10-21 19:06:29 +00002193 eltMask = Mask[i]-LHSWidth;
2194
2195 // If LHS's width is changed, shift the mask value accordingly.
Eugene Zelenko7f0f9bc2017-10-24 21:24:53 +00002196 // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any
Michael Gottesman02a11412012-10-16 21:29:38 +00002197 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
2198 // If newRHS == newLHS, we want to remap any references from newRHS to
2199 // newLHS so that we can properly identify splats that may occur due to
Alp Tokercb402912014-01-24 17:20:08 +00002200 // obfuscation across the two vectors.
Craig Topperf40110f2014-04-25 05:29:35 +00002201 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00002202 eltMask += newLHSWidth;
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00002203 }
Eli Friedmance818272011-10-21 19:06:29 +00002204
2205 // Check if this could still be a splat.
2206 if (eltMask >= 0) {
2207 if (SplatElt >= 0 && SplatElt != eltMask)
2208 isSplat = false;
2209 SplatElt = eltMask;
2210 }
2211
2212 newMask.push_back(eltMask);
2213 }
2214
2215 // If the result mask is equal to one of the original shuffle masks,
Jim Grosbachd11584a2013-05-01 00:25:27 +00002216 // or is a splat, do the replacement.
2217 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
Eli Friedmance818272011-10-21 19:06:29 +00002218 SmallVector<Constant*, 16> Elts;
Eli Friedmance818272011-10-21 19:06:29 +00002219 for (unsigned i = 0, e = newMask.size(); i != e; ++i) {
2220 if (newMask[i] < 0) {
2221 Elts.push_back(UndefValue::get(Int32Ty));
2222 } else {
2223 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i]));
2224 }
2225 }
Craig Topperf40110f2014-04-25 05:29:35 +00002226 if (!newRHS)
Eli Friedmance818272011-10-21 19:06:29 +00002227 newRHS = UndefValue::get(newLHS->getType());
2228 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts));
Nate Begeman2a0ca3e92010-08-13 00:17:53 +00002229 }
Bob Wilson8ecf98b2010-10-29 22:20:43 +00002230
Craig Topperf40110f2014-04-25 05:29:35 +00002231 return MadeChange ? &SVI : nullptr;
Chris Lattnerec97a902010-01-05 05:36:20 +00002232}