1 //===- InstCombineVectorOps.cpp -------------------------------------------===//
2 //
3 // 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
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements instcombine for ExtractElement, InsertElement and
10 // ShuffleVector.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "InstCombineInternal.h"
15 #include "llvm/ADT/APInt.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallBitVector.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/VectorUtils.h"
24 #include "llvm/IR/BasicBlock.h"
25 #include "llvm/IR/Constant.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/InstrTypes.h"
29 #include "llvm/IR/Instruction.h"
30 #include "llvm/IR/Instructions.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/IR/Type.h"
34 #include "llvm/IR/User.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Transforms/InstCombine/InstCombiner.h"
39 #include <cassert>
40 #include <cstdint>
41 #include <iterator>
42 #include <utility>
43
44 #define DEBUG_TYPE "instcombine"
45
46 using namespace llvm;
47 using namespace PatternMatch;
48
49 STATISTIC(NumAggregateReconstructionsSimplified,
50 "Number of aggregate reconstructions turned into reuse of the "
51 "original aggregate");
52
53 /// Return true if the value is cheaper to scalarize than it is to leave as a
54 /// vector operation. If the extract index \p EI is a constant integer then
55 /// some operations may be cheap to scalarize.
56 ///
57 /// FIXME: It's possible to create more instructions than previously existed.
cheapToScalarize(Value * V,Value * EI)58 static bool cheapToScalarize(Value *V, Value *EI) {
59 ConstantInt *CEI = dyn_cast<ConstantInt>(EI);
60
61 // If we can pick a scalar constant value out of a vector, that is free.
62 if (auto *C = dyn_cast<Constant>(V))
63 return CEI || C->getSplatValue();
64
65 if (CEI && match(V, m_Intrinsic<Intrinsic::experimental_stepvector>())) {
66 ElementCount EC = cast<VectorType>(V->getType())->getElementCount();
67 // Index needs to be lower than the minimum size of the vector, because
68 // for scalable vector, the vector size is known at run time.
69 return CEI->getValue().ult(EC.getKnownMinValue());
70 }
71
72 // An insertelement to the same constant index as our extract will simplify
73 // to the scalar inserted element. An insertelement to a different constant
74 // index is irrelevant to our extract.
75 if (match(V, m_InsertElt(m_Value(), m_Value(), m_ConstantInt())))
76 return CEI;
77
78 if (match(V, m_OneUse(m_Load(m_Value()))))
79 return true;
80
81 if (match(V, m_OneUse(m_UnOp())))
82 return true;
83
84 Value *V0, *V1;
85 if (match(V, m_OneUse(m_BinOp(m_Value(V0), m_Value(V1)))))
86 if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
87 return true;
88
89 CmpInst::Predicate UnusedPred;
90 if (match(V, m_OneUse(m_Cmp(UnusedPred, m_Value(V0), m_Value(V1)))))
91 if (cheapToScalarize(V0, EI) || cheapToScalarize(V1, EI))
92 return true;
93
94 return false;
95 }
96
97 // If we have a PHI node with a vector type that is only used to feed
98 // itself and be an operand of extractelement at a constant location,
99 // try to replace the PHI of the vector type with a PHI of a scalar type.
scalarizePHI(ExtractElementInst & EI,PHINode * PN)100 Instruction *InstCombinerImpl::scalarizePHI(ExtractElementInst &EI,
101 PHINode *PN) {
102 SmallVector<Instruction *, 2> Extracts;
103 // The users we want the PHI to have are:
104 // 1) The EI ExtractElement (we already know this)
105 // 2) Possibly more ExtractElements with the same index.
106 // 3) Another operand, which will feed back into the PHI.
107 Instruction *PHIUser = nullptr;
108 for (auto *U : PN->users()) {
109 if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) {
110 if (EI.getIndexOperand() == EU->getIndexOperand())
111 Extracts.push_back(EU);
112 else
113 return nullptr;
114 } else if (!PHIUser) {
115 PHIUser = cast<Instruction>(U);
116 } else {
117 return nullptr;
118 }
119 }
120
121 if (!PHIUser)
122 return nullptr;
123
124 // Verify that this PHI user has one use, which is the PHI itself,
125 // and that it is a binary operation which is cheap to scalarize.
126 // otherwise return nullptr.
127 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) ||
128 !(isa<BinaryOperator>(PHIUser)) ||
129 !cheapToScalarize(PHIUser, EI.getIndexOperand()))
130 return nullptr;
131
132 // Create a scalar PHI node that will replace the vector PHI node
133 // just before the current PHI node.
134 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith(
135 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN));
136 // Scalarize each PHI operand.
137 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
138 Value *PHIInVal = PN->getIncomingValue(i);
139 BasicBlock *inBB = PN->getIncomingBlock(i);
140 Value *Elt = EI.getIndexOperand();
141 // If the operand is the PHI induction variable:
142 if (PHIInVal == PHIUser) {
143 // Scalarize the binary operation. Its first operand is the
144 // scalar PHI, and the second operand is extracted from the other
145 // vector operand.
146 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser);
147 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0;
148 Value *Op = InsertNewInstWith(
149 ExtractElementInst::Create(B0->getOperand(opId), Elt,
150 B0->getOperand(opId)->getName() + ".Elt"),
151 *B0);
152 Value *newPHIUser = InsertNewInstWith(
153 BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(),
154 scalarPHI, Op, B0), *B0);
155 scalarPHI->addIncoming(newPHIUser, inBB);
156 } else {
157 // Scalarize PHI input:
158 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, "");
159 // Insert the new instruction into the predecessor basic block.
160 Instruction *pos = dyn_cast<Instruction>(PHIInVal);
161 BasicBlock::iterator InsertPos;
162 if (pos && !isa<PHINode>(pos)) {
163 InsertPos = ++pos->getIterator();
164 } else {
165 InsertPos = inBB->getFirstInsertionPt();
166 }
167
168 InsertNewInstWith(newEI, *InsertPos);
169
170 scalarPHI->addIncoming(newEI, inBB);
171 }
172 }
173
174 for (auto *E : Extracts)
175 replaceInstUsesWith(*E, scalarPHI);
176
177 return &EI;
178 }
179
foldBitcastExtElt(ExtractElementInst & Ext)180 Instruction *InstCombinerImpl::foldBitcastExtElt(ExtractElementInst &Ext) {
181 Value *X;
182 uint64_t ExtIndexC;
183 if (!match(Ext.getVectorOperand(), m_BitCast(m_Value(X))) ||
184 !match(Ext.getIndexOperand(), m_ConstantInt(ExtIndexC)))
185 return nullptr;
186
187 ElementCount NumElts =
188 cast<VectorType>(Ext.getVectorOperandType())->getElementCount();
189 Type *DestTy = Ext.getType();
190 unsigned DestWidth = DestTy->getPrimitiveSizeInBits();
191 bool IsBigEndian = DL.isBigEndian();
192
193 // If we are casting an integer to vector and extracting a portion, that is
194 // a shift-right and truncate.
195 if (X->getType()->isIntegerTy()) {
196 assert(isa<FixedVectorType>(Ext.getVectorOperand()->getType()) &&
197 "Expected fixed vector type for bitcast from scalar integer");
198
199 // Big endian requires adjusting the extract index since MSB is at index 0.
200 // LittleEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 X to i8
201 // BigEndian: extelt (bitcast i32 X to v4i8), 0 -> trunc i32 (X >> 24) to i8
202 if (IsBigEndian)
203 ExtIndexC = NumElts.getKnownMinValue() - 1 - ExtIndexC;
204 unsigned ShiftAmountC = ExtIndexC * DestWidth;
205 if (!ShiftAmountC ||
206 (isDesirableIntType(X->getType()->getPrimitiveSizeInBits()) &&
207 Ext.getVectorOperand()->hasOneUse())) {
208 if (ShiftAmountC)
209 X = Builder.CreateLShr(X, ShiftAmountC, "extelt.offset");
210 if (DestTy->isFloatingPointTy()) {
211 Type *DstIntTy = IntegerType::getIntNTy(X->getContext(), DestWidth);
212 Value *Trunc = Builder.CreateTrunc(X, DstIntTy);
213 return new BitCastInst(Trunc, DestTy);
214 }
215 return new TruncInst(X, DestTy);
216 }
217 }
218
219 if (!X->getType()->isVectorTy())
220 return nullptr;
221
222 // If this extractelement is using a bitcast from a vector of the same number
223 // of elements, see if we can find the source element from the source vector:
224 // extelt (bitcast VecX), IndexC --> bitcast X[IndexC]
225 auto *SrcTy = cast<VectorType>(X->getType());
226 ElementCount NumSrcElts = SrcTy->getElementCount();
227 if (NumSrcElts == NumElts)
228 if (Value *Elt = findScalarElement(X, ExtIndexC))
229 return new BitCastInst(Elt, DestTy);
230
231 assert(NumSrcElts.isScalable() == NumElts.isScalable() &&
232 "Src and Dst must be the same sort of vector type");
233
234 // If the source elements are wider than the destination, try to shift and
235 // truncate a subset of scalar bits of an insert op.
236 if (NumSrcElts.getKnownMinValue() < NumElts.getKnownMinValue()) {
237 Value *Scalar;
238 Value *Vec;
239 uint64_t InsIndexC;
240 if (!match(X, m_InsertElt(m_Value(Vec), m_Value(Scalar),
241 m_ConstantInt(InsIndexC))))
242 return nullptr;
243
244 // The extract must be from the subset of vector elements that we inserted
245 // into. Example: if we inserted element 1 of a <2 x i64> and we are
246 // extracting an i16 (narrowing ratio = 4), then this extract must be from 1
247 // of elements 4-7 of the bitcasted vector.
248 unsigned NarrowingRatio =
249 NumElts.getKnownMinValue() / NumSrcElts.getKnownMinValue();
250
251 if (ExtIndexC / NarrowingRatio != InsIndexC) {
252 // Remove insertelement, if we don't use the inserted element.
253 // extractelement (bitcast (insertelement (Vec, b)), a) ->
254 // extractelement (bitcast (Vec), a)
255 // FIXME: this should be removed to SimplifyDemandedVectorElts,
256 // once scale vectors are supported.
257 if (X->hasOneUse() && Ext.getVectorOperand()->hasOneUse()) {
258 Value *NewBC = Builder.CreateBitCast(Vec, Ext.getVectorOperandType());
259 return ExtractElementInst::Create(NewBC, Ext.getIndexOperand());
260 }
261 return nullptr;
262 }
263
264 // We are extracting part of the original scalar. How that scalar is
265 // inserted into the vector depends on the endian-ness. Example:
266 // Vector Byte Elt Index: 0 1 2 3 4 5 6 7
267 // +--+--+--+--+--+--+--+--+
268 // inselt <2 x i32> V, <i32> S, 1: |V0|V1|V2|V3|S0|S1|S2|S3|
269 // extelt <4 x i16> V', 3: | |S2|S3|
270 // +--+--+--+--+--+--+--+--+
271 // If this is little-endian, S2|S3 are the MSB of the 32-bit 'S' value.
272 // If this is big-endian, S2|S3 are the LSB of the 32-bit 'S' value.
273 // In this example, we must right-shift little-endian. Big-endian is just a
274 // truncate.
275 unsigned Chunk = ExtIndexC % NarrowingRatio;
276 if (IsBigEndian)
277 Chunk = NarrowingRatio - 1 - Chunk;
278
279 // Bail out if this is an FP vector to FP vector sequence. That would take
280 // more instructions than we started with unless there is no shift, and it
281 // may not be handled as well in the backend.
282 bool NeedSrcBitcast = SrcTy->getScalarType()->isFloatingPointTy();
283 bool NeedDestBitcast = DestTy->isFloatingPointTy();
284 if (NeedSrcBitcast && NeedDestBitcast)
285 return nullptr;
286
287 unsigned SrcWidth = SrcTy->getScalarSizeInBits();
288 unsigned ShAmt = Chunk * DestWidth;
289
290 // TODO: This limitation is more strict than necessary. We could sum the
291 // number of new instructions and subtract the number eliminated to know if
292 // we can proceed.
293 if (!X->hasOneUse() || !Ext.getVectorOperand()->hasOneUse())
294 if (NeedSrcBitcast || NeedDestBitcast)
295 return nullptr;
296
297 if (NeedSrcBitcast) {
298 Type *SrcIntTy = IntegerType::getIntNTy(Scalar->getContext(), SrcWidth);
299 Scalar = Builder.CreateBitCast(Scalar, SrcIntTy);
300 }
301
302 if (ShAmt) {
303 // Bail out if we could end with more instructions than we started with.
304 if (!Ext.getVectorOperand()->hasOneUse())
305 return nullptr;
306 Scalar = Builder.CreateLShr(Scalar, ShAmt);
307 }
308
309 if (NeedDestBitcast) {
310 Type *DestIntTy = IntegerType::getIntNTy(Scalar->getContext(), DestWidth);
311 return new BitCastInst(Builder.CreateTrunc(Scalar, DestIntTy), DestTy);
312 }
313 return new TruncInst(Scalar, DestTy);
314 }
315
316 return nullptr;
317 }
318
319 /// Find elements of V demanded by UserInstr.
findDemandedEltsBySingleUser(Value * V,Instruction * UserInstr)320 static APInt findDemandedEltsBySingleUser(Value *V, Instruction *UserInstr) {
321 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
322
323 // Conservatively assume that all elements are needed.
324 APInt UsedElts(APInt::getAllOnes(VWidth));
325
326 switch (UserInstr->getOpcode()) {
327 case Instruction::ExtractElement: {
328 ExtractElementInst *EEI = cast<ExtractElementInst>(UserInstr);
329 assert(EEI->getVectorOperand() == V);
330 ConstantInt *EEIIndexC = dyn_cast<ConstantInt>(EEI->getIndexOperand());
331 if (EEIIndexC && EEIIndexC->getValue().ult(VWidth)) {
332 UsedElts = APInt::getOneBitSet(VWidth, EEIIndexC->getZExtValue());
333 }
334 break;
335 }
336 case Instruction::ShuffleVector: {
337 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(UserInstr);
338 unsigned MaskNumElts =
339 cast<FixedVectorType>(UserInstr->getType())->getNumElements();
340
341 UsedElts = APInt(VWidth, 0);
342 for (unsigned i = 0; i < MaskNumElts; i++) {
343 unsigned MaskVal = Shuffle->getMaskValue(i);
344 if (MaskVal == -1u || MaskVal >= 2 * VWidth)
345 continue;
346 if (Shuffle->getOperand(0) == V && (MaskVal < VWidth))
347 UsedElts.setBit(MaskVal);
348 if (Shuffle->getOperand(1) == V &&
349 ((MaskVal >= VWidth) && (MaskVal < 2 * VWidth)))
350 UsedElts.setBit(MaskVal - VWidth);
351 }
352 break;
353 }
354 default:
355 break;
356 }
357 return UsedElts;
358 }
359
360 /// Find union of elements of V demanded by all its users.
361 /// If it is known by querying findDemandedEltsBySingleUser that
362 /// no user demands an element of V, then the corresponding bit
363 /// remains unset in the returned value.
findDemandedEltsByAllUsers(Value * V)364 static APInt findDemandedEltsByAllUsers(Value *V) {
365 unsigned VWidth = cast<FixedVectorType>(V->getType())->getNumElements();
366
367 APInt UnionUsedElts(VWidth, 0);
368 for (const Use &U : V->uses()) {
369 if (Instruction *I = dyn_cast<Instruction>(U.getUser())) {
370 UnionUsedElts |= findDemandedEltsBySingleUser(V, I);
371 } else {
372 UnionUsedElts = APInt::getAllOnes(VWidth);
373 break;
374 }
375
376 if (UnionUsedElts.isAllOnes())
377 break;
378 }
379
380 return UnionUsedElts;
381 }
382
383 /// Given a constant index for a extractelement or insertelement instruction,
384 /// return it with the canonical type if it isn't already canonical. We
385 /// arbitrarily pick 64 bit as our canonical type. The actual bitwidth doesn't
386 /// matter, we just want a consistent type to simplify CSE.
getPreferredVectorIndex(ConstantInt * IndexC)387 ConstantInt *getPreferredVectorIndex(ConstantInt *IndexC) {
388 const unsigned IndexBW = IndexC->getType()->getBitWidth();
389 if (IndexBW == 64 || IndexC->getValue().getActiveBits() > 64)
390 return nullptr;
391 return ConstantInt::get(IndexC->getContext(),
392 IndexC->getValue().zextOrTrunc(64));
393 }
394
visitExtractElementInst(ExtractElementInst & EI)395 Instruction *InstCombinerImpl::visitExtractElementInst(ExtractElementInst &EI) {
396 Value *SrcVec = EI.getVectorOperand();
397 Value *Index = EI.getIndexOperand();
398 if (Value *V = simplifyExtractElementInst(SrcVec, Index,
399 SQ.getWithInstruction(&EI)))
400 return replaceInstUsesWith(EI, V);
401
402 // extractelt (select %x, %vec1, %vec2), %const ->
403 // select %x, %vec1[%const], %vec2[%const]
404 // TODO: Support constant folding of multiple select operands:
405 // extractelt (select %x, %vec1, %vec2), (select %x, %c1, %c2)
406 // If the extractelement will for instance try to do out of bounds accesses
407 // because of the values of %c1 and/or %c2, the sequence could be optimized
408 // early. This is currently not possible because constant folding will reach
409 // an unreachable assertion if it doesn't find a constant operand.
410 if (SelectInst *SI = dyn_cast<SelectInst>(EI.getVectorOperand()))
411 if (SI->getCondition()->getType()->isIntegerTy() &&
412 isa<Constant>(EI.getIndexOperand()))
413 if (Instruction *R = FoldOpIntoSelect(EI, SI))
414 return R;
415
416 // If extracting a specified index from the vector, see if we can recursively
417 // find a previously computed scalar that was inserted into the vector.
418 auto *IndexC = dyn_cast<ConstantInt>(Index);
419 if (IndexC) {
420 // Canonicalize type of constant indices to i64 to simplify CSE
421 if (auto *NewIdx = getPreferredVectorIndex(IndexC))
422 return replaceOperand(EI, 1, NewIdx);
423
424 ElementCount EC = EI.getVectorOperandType()->getElementCount();
425 unsigned NumElts = EC.getKnownMinValue();
426
427 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(SrcVec)) {
428 Intrinsic::ID IID = II->getIntrinsicID();
429 // Index needs to be lower than the minimum size of the vector, because
430 // for scalable vector, the vector size is known at run time.
431 if (IID == Intrinsic::experimental_stepvector &&
432 IndexC->getValue().ult(NumElts)) {
433 Type *Ty = EI.getType();
434 unsigned BitWidth = Ty->getIntegerBitWidth();
435 Value *Idx;
436 // Return index when its value does not exceed the allowed limit
437 // for the element type of the vector, otherwise return undefined.
438 if (IndexC->getValue().getActiveBits() <= BitWidth)
439 Idx = ConstantInt::get(Ty, IndexC->getValue().zextOrTrunc(BitWidth));
440 else
441 Idx = UndefValue::get(Ty);
442 return replaceInstUsesWith(EI, Idx);
443 }
444 }
445
446 // InstSimplify should handle cases where the index is invalid.
447 // For fixed-length vector, it's invalid to extract out-of-range element.
448 if (!EC.isScalable() && IndexC->getValue().uge(NumElts))
449 return nullptr;
450
451 if (Instruction *I = foldBitcastExtElt(EI))
452 return I;
453
454 // If there's a vector PHI feeding a scalar use through this extractelement
455 // instruction, try to scalarize the PHI.
456 if (auto *Phi = dyn_cast<PHINode>(SrcVec))
457 if (Instruction *ScalarPHI = scalarizePHI(EI, Phi))
458 return ScalarPHI;
459 }
460
461 // TODO come up with a n-ary matcher that subsumes both unary and
462 // binary matchers.
463 UnaryOperator *UO;
464 if (match(SrcVec, m_UnOp(UO)) && cheapToScalarize(SrcVec, Index)) {
465 // extelt (unop X), Index --> unop (extelt X, Index)
466 Value *X = UO->getOperand(0);
467 Value *E = Builder.CreateExtractElement(X, Index);
468 return UnaryOperator::CreateWithCopiedFlags(UO->getOpcode(), E, UO);
469 }
470
471 BinaryOperator *BO;
472 if (match(SrcVec, m_BinOp(BO)) && cheapToScalarize(SrcVec, Index)) {
473 // extelt (binop X, Y), Index --> binop (extelt X, Index), (extelt Y, Index)
474 Value *X = BO->getOperand(0), *Y = BO->getOperand(1);
475 Value *E0 = Builder.CreateExtractElement(X, Index);
476 Value *E1 = Builder.CreateExtractElement(Y, Index);
477 return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), E0, E1, BO);
478 }
479
480 Value *X, *Y;
481 CmpInst::Predicate Pred;
482 if (match(SrcVec, m_Cmp(Pred, m_Value(X), m_Value(Y))) &&
483 cheapToScalarize(SrcVec, Index)) {
484 // extelt (cmp X, Y), Index --> cmp (extelt X, Index), (extelt Y, Index)
485 Value *E0 = Builder.CreateExtractElement(X, Index);
486 Value *E1 = Builder.CreateExtractElement(Y, Index);
487 return CmpInst::Create(cast<CmpInst>(SrcVec)->getOpcode(), Pred, E0, E1);
488 }
489
490 if (auto *I = dyn_cast<Instruction>(SrcVec)) {
491 if (auto *IE = dyn_cast<InsertElementInst>(I)) {
492 // instsimplify already handled the case where the indices are constants
493 // and equal by value, if both are constants, they must not be the same
494 // value, extract from the pre-inserted value instead.
495 if (isa<Constant>(IE->getOperand(2)) && IndexC)
496 return replaceOperand(EI, 0, IE->getOperand(0));
497 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
498 auto *VecType = cast<VectorType>(GEP->getType());
499 ElementCount EC = VecType->getElementCount();
500 uint64_t IdxVal = IndexC ? IndexC->getZExtValue() : 0;
501 if (IndexC && IdxVal < EC.getKnownMinValue() && GEP->hasOneUse()) {
502 // Find out why we have a vector result - these are a few examples:
503 // 1. We have a scalar pointer and a vector of indices, or
504 // 2. We have a vector of pointers and a scalar index, or
505 // 3. We have a vector of pointers and a vector of indices, etc.
506 // Here we only consider combining when there is exactly one vector
507 // operand, since the optimization is less obviously a win due to
508 // needing more than one extractelements.
509
510 unsigned VectorOps =
511 llvm::count_if(GEP->operands(), [](const Value *V) {
512 return isa<VectorType>(V->getType());
513 });
514 if (VectorOps == 1) {
515 Value *NewPtr = GEP->getPointerOperand();
516 if (isa<VectorType>(NewPtr->getType()))
517 NewPtr = Builder.CreateExtractElement(NewPtr, IndexC);
518
519 SmallVector<Value *> NewOps;
520 for (unsigned I = 1; I != GEP->getNumOperands(); ++I) {
521 Value *Op = GEP->getOperand(I);
522 if (isa<VectorType>(Op->getType()))
523 NewOps.push_back(Builder.CreateExtractElement(Op, IndexC));
524 else
525 NewOps.push_back(Op);
526 }
527
528 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(
529 GEP->getSourceElementType(), NewPtr, NewOps);
530 NewGEP->setIsInBounds(GEP->isInBounds());
531 return NewGEP;
532 }
533 }
534 } else if (auto *SVI = dyn_cast<ShuffleVectorInst>(I)) {
535 // If this is extracting an element from a shufflevector, figure out where
536 // it came from and extract from the appropriate input element instead.
537 // Restrict the following transformation to fixed-length vector.
538 if (isa<FixedVectorType>(SVI->getType()) && isa<ConstantInt>(Index)) {
539 int SrcIdx =
540 SVI->getMaskValue(cast<ConstantInt>(Index)->getZExtValue());
541 Value *Src;
542 unsigned LHSWidth = cast<FixedVectorType>(SVI->getOperand(0)->getType())
543 ->getNumElements();
544
545 if (SrcIdx < 0)
546 return replaceInstUsesWith(EI, UndefValue::get(EI.getType()));
547 if (SrcIdx < (int)LHSWidth)
548 Src = SVI->getOperand(0);
549 else {
550 SrcIdx -= LHSWidth;
551 Src = SVI->getOperand(1);
552 }
553 Type *Int32Ty = Type::getInt32Ty(EI.getContext());
554 return ExtractElementInst::Create(
555 Src, ConstantInt::get(Int32Ty, SrcIdx, false));
556 }
557 } else if (auto *CI = dyn_cast<CastInst>(I)) {
558 // Canonicalize extractelement(cast) -> cast(extractelement).
559 // Bitcasts can change the number of vector elements, and they cost
560 // nothing.
561 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) {
562 Value *EE = Builder.CreateExtractElement(CI->getOperand(0), Index);
563 return CastInst::Create(CI->getOpcode(), EE, EI.getType());
564 }
565 }
566 }
567
568 // Run demanded elements after other transforms as this can drop flags on
569 // binops. If there's two paths to the same final result, we prefer the
570 // one which doesn't force us to drop flags.
571 if (IndexC) {
572 ElementCount EC = EI.getVectorOperandType()->getElementCount();
573 unsigned NumElts = EC.getKnownMinValue();
574 // This instruction only demands the single element from the input vector.
575 // Skip for scalable type, the number of elements is unknown at
576 // compile-time.
577 if (!EC.isScalable() && NumElts != 1) {
578 // If the input vector has a single use, simplify it based on this use
579 // property.
580 if (SrcVec->hasOneUse()) {
581 APInt UndefElts(NumElts, 0);
582 APInt DemandedElts(NumElts, 0);
583 DemandedElts.setBit(IndexC->getZExtValue());
584 if (Value *V =
585 SimplifyDemandedVectorElts(SrcVec, DemandedElts, UndefElts))
586 return replaceOperand(EI, 0, V);
587 } else {
588 // If the input vector has multiple uses, simplify it based on a union
589 // of all elements used.
590 APInt DemandedElts = findDemandedEltsByAllUsers(SrcVec);
591 if (!DemandedElts.isAllOnes()) {
592 APInt UndefElts(NumElts, 0);
593 if (Value *V = SimplifyDemandedVectorElts(
594 SrcVec, DemandedElts, UndefElts, 0 /* Depth */,
595 true /* AllowMultipleUsers */)) {
596 if (V != SrcVec) {
597 SrcVec->replaceAllUsesWith(V);
598 return &EI;
599 }
600 }
601 }
602 }
603 }
604 }
605 return nullptr;
606 }
607
608 /// If V is a shuffle of values that ONLY returns elements from either LHS or
609 /// RHS, return the shuffle mask and true. Otherwise, return false.
collectSingleShuffleElements(Value * V,Value * LHS,Value * RHS,SmallVectorImpl<int> & Mask)610 static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
611 SmallVectorImpl<int> &Mask) {
612 assert(LHS->getType() == RHS->getType() &&
613 "Invalid CollectSingleShuffleElements");
614 unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
615
616 if (match(V, m_Undef())) {
617 Mask.assign(NumElts, -1);
618 return true;
619 }
620
621 if (V == LHS) {
622 for (unsigned i = 0; i != NumElts; ++i)
623 Mask.push_back(i);
624 return true;
625 }
626
627 if (V == RHS) {
628 for (unsigned i = 0; i != NumElts; ++i)
629 Mask.push_back(i + NumElts);
630 return true;
631 }
632
633 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
634 // If this is an insert of an extract from some other vector, include it.
635 Value *VecOp = IEI->getOperand(0);
636 Value *ScalarOp = IEI->getOperand(1);
637 Value *IdxOp = IEI->getOperand(2);
638
639 if (!isa<ConstantInt>(IdxOp))
640 return false;
641 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
642
643 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
644 // We can handle this if the vector we are inserting into is
645 // transitively ok.
646 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
647 // If so, update the mask to reflect the inserted undef.
648 Mask[InsertedIdx] = -1;
649 return true;
650 }
651 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
652 if (isa<ConstantInt>(EI->getOperand(1))) {
653 unsigned ExtractedIdx =
654 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
655 unsigned NumLHSElts =
656 cast<FixedVectorType>(LHS->getType())->getNumElements();
657
658 // This must be extracting from either LHS or RHS.
659 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
660 // We can handle this if the vector we are inserting into is
661 // transitively ok.
662 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
663 // If so, update the mask to reflect the inserted value.
664 if (EI->getOperand(0) == LHS) {
665 Mask[InsertedIdx % NumElts] = ExtractedIdx;
666 } else {
667 assert(EI->getOperand(0) == RHS);
668 Mask[InsertedIdx % NumElts] = ExtractedIdx + NumLHSElts;
669 }
670 return true;
671 }
672 }
673 }
674 }
675 }
676
677 return false;
678 }
679
680 /// If we have insertion into a vector that is wider than the vector that we
681 /// are extracting from, try to widen the source vector to allow a single
682 /// shufflevector to replace one or more insert/extract pairs.
replaceExtractElements(InsertElementInst * InsElt,ExtractElementInst * ExtElt,InstCombinerImpl & IC)683 static void replaceExtractElements(InsertElementInst *InsElt,
684 ExtractElementInst *ExtElt,
685 InstCombinerImpl &IC) {
686 auto *InsVecType = cast<FixedVectorType>(InsElt->getType());
687 auto *ExtVecType = cast<FixedVectorType>(ExtElt->getVectorOperandType());
688 unsigned NumInsElts = InsVecType->getNumElements();
689 unsigned NumExtElts = ExtVecType->getNumElements();
690
691 // The inserted-to vector must be wider than the extracted-from vector.
692 if (InsVecType->getElementType() != ExtVecType->getElementType() ||
693 NumExtElts >= NumInsElts)
694 return;
695
696 // Create a shuffle mask to widen the extended-from vector using poison
697 // values. The mask selects all of the values of the original vector followed
698 // by as many poison values as needed to create a vector of the same length
699 // as the inserted-to vector.
700 SmallVector<int, 16> ExtendMask;
701 for (unsigned i = 0; i < NumExtElts; ++i)
702 ExtendMask.push_back(i);
703 for (unsigned i = NumExtElts; i < NumInsElts; ++i)
704 ExtendMask.push_back(-1);
705
706 Value *ExtVecOp = ExtElt->getVectorOperand();
707 auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp);
708 BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
709 ? ExtVecOpInst->getParent()
710 : ExtElt->getParent();
711
712 // TODO: This restriction matches the basic block check below when creating
713 // new extractelement instructions. If that limitation is removed, this one
714 // could also be removed. But for now, we just bail out to ensure that we
715 // will replace the extractelement instruction that is feeding our
716 // insertelement instruction. This allows the insertelement to then be
717 // replaced by a shufflevector. If the insertelement is not replaced, we can
718 // induce infinite looping because there's an optimization for extractelement
719 // that will delete our widening shuffle. This would trigger another attempt
720 // here to create that shuffle, and we spin forever.
721 if (InsertionBlock != InsElt->getParent())
722 return;
723
724 // TODO: This restriction matches the check in visitInsertElementInst() and
725 // prevents an infinite loop caused by not turning the extract/insert pair
726 // into a shuffle. We really should not need either check, but we're lacking
727 // folds for shufflevectors because we're afraid to generate shuffle masks
728 // that the backend can't handle.
729 if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back()))
730 return;
731
732 auto *WideVec = new ShuffleVectorInst(ExtVecOp, ExtendMask);
733
734 // Insert the new shuffle after the vector operand of the extract is defined
735 // (as long as it's not a PHI) or at the start of the basic block of the
736 // extract, so any subsequent extracts in the same basic block can use it.
737 // TODO: Insert before the earliest ExtractElementInst that is replaced.
738 if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst))
739 WideVec->insertAfter(ExtVecOpInst);
740 else
741 IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt());
742
743 // Replace extracts from the original narrow vector with extracts from the new
744 // wide vector.
745 for (User *U : ExtVecOp->users()) {
746 ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U);
747 if (!OldExt || OldExt->getParent() != WideVec->getParent())
748 continue;
749 auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1));
750 NewExt->insertAfter(OldExt);
751 IC.replaceInstUsesWith(*OldExt, NewExt);
752 }
753 }
754
755 /// We are building a shuffle to create V, which is a sequence of insertelement,
756 /// extractelement pairs. If PermittedRHS is set, then we must either use it or
757 /// not rely on the second vector source. Return a std::pair containing the
758 /// left and right vectors of the proposed shuffle (or 0), and set the Mask
759 /// parameter as required.
760 ///
761 /// Note: we intentionally don't try to fold earlier shuffles since they have
762 /// often been chosen carefully to be efficiently implementable on the target.
763 using ShuffleOps = std::pair<Value *, Value *>;
764
collectShuffleElements(Value * V,SmallVectorImpl<int> & Mask,Value * PermittedRHS,InstCombinerImpl & IC)765 static ShuffleOps collectShuffleElements(Value *V, SmallVectorImpl<int> &Mask,
766 Value *PermittedRHS,
767 InstCombinerImpl &IC) {
768 assert(V->getType()->isVectorTy() && "Invalid shuffle!");
769 unsigned NumElts = cast<FixedVectorType>(V->getType())->getNumElements();
770
771 if (match(V, m_Undef())) {
772 Mask.assign(NumElts, -1);
773 return std::make_pair(
774 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr);
775 }
776
777 if (isa<ConstantAggregateZero>(V)) {
778 Mask.assign(NumElts, 0);
779 return std::make_pair(V, nullptr);
780 }
781
782 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
783 // If this is an insert of an extract from some other vector, include it.
784 Value *VecOp = IEI->getOperand(0);
785 Value *ScalarOp = IEI->getOperand(1);
786 Value *IdxOp = IEI->getOperand(2);
787
788 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
789 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) {
790 unsigned ExtractedIdx =
791 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
792 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
793
794 // Either the extracted from or inserted into vector must be RHSVec,
795 // otherwise we'd end up with a shuffle of three inputs.
796 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) {
797 Value *RHS = EI->getOperand(0);
798 ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC);
799 assert(LR.second == nullptr || LR.second == RHS);
800
801 if (LR.first->getType() != RHS->getType()) {
802 // Although we are giving up for now, see if we can create extracts
803 // that match the inserts for another round of combining.
804 replaceExtractElements(IEI, EI, IC);
805
806 // We tried our best, but we can't find anything compatible with RHS
807 // further up the chain. Return a trivial shuffle.
808 for (unsigned i = 0; i < NumElts; ++i)
809 Mask[i] = i;
810 return std::make_pair(V, nullptr);
811 }
812
813 unsigned NumLHSElts =
814 cast<FixedVectorType>(RHS->getType())->getNumElements();
815 Mask[InsertedIdx % NumElts] = NumLHSElts + ExtractedIdx;
816 return std::make_pair(LR.first, RHS);
817 }
818
819 if (VecOp == PermittedRHS) {
820 // We've gone as far as we can: anything on the other side of the
821 // extractelement will already have been converted into a shuffle.
822 unsigned NumLHSElts =
823 cast<FixedVectorType>(EI->getOperand(0)->getType())
824 ->getNumElements();
825 for (unsigned i = 0; i != NumElts; ++i)
826 Mask.push_back(i == InsertedIdx ? ExtractedIdx : NumLHSElts + i);
827 return std::make_pair(EI->getOperand(0), PermittedRHS);
828 }
829
830 // If this insertelement is a chain that comes from exactly these two
831 // vectors, return the vector and the effective shuffle.
832 if (EI->getOperand(0)->getType() == PermittedRHS->getType() &&
833 collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS,
834 Mask))
835 return std::make_pair(EI->getOperand(0), PermittedRHS);
836 }
837 }
838 }
839
840 // Otherwise, we can't do anything fancy. Return an identity vector.
841 for (unsigned i = 0; i != NumElts; ++i)
842 Mask.push_back(i);
843 return std::make_pair(V, nullptr);
844 }
845
846 /// Look for chain of insertvalue's that fully define an aggregate, and trace
847 /// back the values inserted, see if they are all were extractvalue'd from
848 /// the same source aggregate from the exact same element indexes.
849 /// If they were, just reuse the source aggregate.
850 /// This potentially deals with PHI indirections.
foldAggregateConstructionIntoAggregateReuse(InsertValueInst & OrigIVI)851 Instruction *InstCombinerImpl::foldAggregateConstructionIntoAggregateReuse(
852 InsertValueInst &OrigIVI) {
853 Type *AggTy = OrigIVI.getType();
854 unsigned NumAggElts;
855 switch (AggTy->getTypeID()) {
856 case Type::StructTyID:
857 NumAggElts = AggTy->getStructNumElements();
858 break;
859 case Type::ArrayTyID:
860 NumAggElts = AggTy->getArrayNumElements();
861 break;
862 default:
863 llvm_unreachable("Unhandled aggregate type?");
864 }
865
866 // Arbitrary aggregate size cut-off. Motivation for limit of 2 is to be able
867 // to handle clang C++ exception struct (which is hardcoded as {i8*, i32}),
868 // FIXME: any interesting patterns to be caught with larger limit?
869 assert(NumAggElts > 0 && "Aggregate should have elements.");
870 if (NumAggElts > 2)
871 return nullptr;
872
873 static constexpr auto NotFound = std::nullopt;
874 static constexpr auto FoundMismatch = nullptr;
875
876 // Try to find a value of each element of an aggregate.
877 // FIXME: deal with more complex, not one-dimensional, aggregate types
878 SmallVector<std::optional<Instruction *>, 2> AggElts(NumAggElts, NotFound);
879
880 // Do we know values for each element of the aggregate?
881 auto KnowAllElts = [&AggElts]() {
882 return !llvm::is_contained(AggElts, NotFound);
883 };
884
885 int Depth = 0;
886
887 // Arbitrary `insertvalue` visitation depth limit. Let's be okay with
888 // every element being overwritten twice, which should never happen.
889 static const int DepthLimit = 2 * NumAggElts;
890
891 // Recurse up the chain of `insertvalue` aggregate operands until either we've
892 // reconstructed full initializer or can't visit any more `insertvalue`'s.
893 for (InsertValueInst *CurrIVI = &OrigIVI;
894 Depth < DepthLimit && CurrIVI && !KnowAllElts();
895 CurrIVI = dyn_cast<InsertValueInst>(CurrIVI->getAggregateOperand()),
896 ++Depth) {
897 auto *InsertedValue =
898 dyn_cast<Instruction>(CurrIVI->getInsertedValueOperand());
899 if (!InsertedValue)
900 return nullptr; // Inserted value must be produced by an instruction.
901
902 ArrayRef<unsigned int> Indices = CurrIVI->getIndices();
903
904 // Don't bother with more than single-level aggregates.
905 if (Indices.size() != 1)
906 return nullptr; // FIXME: deal with more complex aggregates?
907
908 // Now, we may have already previously recorded the value for this element
909 // of an aggregate. If we did, that means the CurrIVI will later be
910 // overwritten with the already-recorded value. But if not, let's record it!
911 std::optional<Instruction *> &Elt = AggElts[Indices.front()];
912 Elt = Elt.value_or(InsertedValue);
913
914 // FIXME: should we handle chain-terminating undef base operand?
915 }
916
917 // Was that sufficient to deduce the full initializer for the aggregate?
918 if (!KnowAllElts())
919 return nullptr; // Give up then.
920
921 // We now want to find the source[s] of the aggregate elements we've found.
922 // And with "source" we mean the original aggregate[s] from which
923 // the inserted elements were extracted. This may require PHI translation.
924
925 enum class AggregateDescription {
926 /// When analyzing the value that was inserted into an aggregate, we did
927 /// not manage to find defining `extractvalue` instruction to analyze.
928 NotFound,
929 /// When analyzing the value that was inserted into an aggregate, we did
930 /// manage to find defining `extractvalue` instruction[s], and everything
931 /// matched perfectly - aggregate type, element insertion/extraction index.
932 Found,
933 /// When analyzing the value that was inserted into an aggregate, we did
934 /// manage to find defining `extractvalue` instruction, but there was
935 /// a mismatch: either the source type from which the extraction was didn't
936 /// match the aggregate type into which the insertion was,
937 /// or the extraction/insertion channels mismatched,
938 /// or different elements had different source aggregates.
939 FoundMismatch
940 };
941 auto Describe = [](std::optional<Value *> SourceAggregate) {
942 if (SourceAggregate == NotFound)
943 return AggregateDescription::NotFound;
944 if (*SourceAggregate == FoundMismatch)
945 return AggregateDescription::FoundMismatch;
946 return AggregateDescription::Found;
947 };
948
949 // Given the value \p Elt that was being inserted into element \p EltIdx of an
950 // aggregate AggTy, see if \p Elt was originally defined by an
951 // appropriate extractvalue (same element index, same aggregate type).
952 // If found, return the source aggregate from which the extraction was.
953 // If \p PredBB is provided, does PHI translation of an \p Elt first.
954 auto FindSourceAggregate =
955 [&](Instruction *Elt, unsigned EltIdx, std::optional<BasicBlock *> UseBB,
956 std::optional<BasicBlock *> PredBB) -> std::optional<Value *> {
957 // For now(?), only deal with, at most, a single level of PHI indirection.
958 if (UseBB && PredBB)
959 Elt = dyn_cast<Instruction>(Elt->DoPHITranslation(*UseBB, *PredBB));
960 // FIXME: deal with multiple levels of PHI indirection?
961
962 // Did we find an extraction?
963 auto *EVI = dyn_cast_or_null<ExtractValueInst>(Elt);
964 if (!EVI)
965 return NotFound;
966
967 Value *SourceAggregate = EVI->getAggregateOperand();
968
969 // Is the extraction from the same type into which the insertion was?
970 if (SourceAggregate->getType() != AggTy)
971 return FoundMismatch;
972 // And the element index doesn't change between extraction and insertion?
973 if (EVI->getNumIndices() != 1 || EltIdx != EVI->getIndices().front())
974 return FoundMismatch;
975
976 return SourceAggregate; // AggregateDescription::Found
977 };
978
979 // Given elements AggElts that were constructing an aggregate OrigIVI,
980 // see if we can find appropriate source aggregate for each of the elements,
981 // and see it's the same aggregate for each element. If so, return it.
982 auto FindCommonSourceAggregate =
983 [&](std::optional<BasicBlock *> UseBB,
984 std::optional<BasicBlock *> PredBB) -> std::optional<Value *> {
985 std::optional<Value *> SourceAggregate;
986
987 for (auto I : enumerate(AggElts)) {
988 assert(Describe(SourceAggregate) != AggregateDescription::FoundMismatch &&
989 "We don't store nullptr in SourceAggregate!");
990 assert((Describe(SourceAggregate) == AggregateDescription::Found) ==
991 (I.index() != 0) &&
992 "SourceAggregate should be valid after the first element,");
993
994 // For this element, is there a plausible source aggregate?
995 // FIXME: we could special-case undef element, IFF we know that in the
996 // source aggregate said element isn't poison.
997 std::optional<Value *> SourceAggregateForElement =
998 FindSourceAggregate(*I.value(), I.index(), UseBB, PredBB);
999
1000 // Okay, what have we found? Does that correlate with previous findings?
1001
1002 // Regardless of whether or not we have previously found source
1003 // aggregate for previous elements (if any), if we didn't find one for
1004 // this element, passthrough whatever we have just found.
1005 if (Describe(SourceAggregateForElement) != AggregateDescription::Found)
1006 return SourceAggregateForElement;
1007
1008 // Okay, we have found source aggregate for this element.
1009 // Let's see what we already know from previous elements, if any.
1010 switch (Describe(SourceAggregate)) {
1011 case AggregateDescription::NotFound:
1012 // This is apparently the first element that we have examined.
1013 SourceAggregate = SourceAggregateForElement; // Record the aggregate!
1014 continue; // Great, now look at next element.
1015 case AggregateDescription::Found:
1016 // We have previously already successfully examined other elements.
1017 // Is this the same source aggregate we've found for other elements?
1018 if (*SourceAggregateForElement != *SourceAggregate)
1019 return FoundMismatch;
1020 continue; // Still the same aggregate, look at next element.
1021 case AggregateDescription::FoundMismatch:
1022 llvm_unreachable("Can't happen. We would have early-exited then.");
1023 };
1024 }
1025
1026 assert(Describe(SourceAggregate) == AggregateDescription::Found &&
1027 "Must be a valid Value");
1028 return *SourceAggregate;
1029 };
1030
1031 std::optional<Value *> SourceAggregate;
1032
1033 // Can we find the source aggregate without looking at predecessors?
1034 SourceAggregate = FindCommonSourceAggregate(/*UseBB=*/std::nullopt,
1035 /*PredBB=*/std::nullopt);
1036 if (Describe(SourceAggregate) != AggregateDescription::NotFound) {
1037 if (Describe(SourceAggregate) == AggregateDescription::FoundMismatch)
1038 return nullptr; // Conflicting source aggregates!
1039 ++NumAggregateReconstructionsSimplified;
1040 return replaceInstUsesWith(OrigIVI, *SourceAggregate);
1041 }
1042
1043 // Okay, apparently we need to look at predecessors.
1044
1045 // We should be smart about picking the "use" basic block, which will be the
1046 // merge point for aggregate, where we'll insert the final PHI that will be
1047 // used instead of OrigIVI. Basic block of OrigIVI is *not* the right choice.
1048 // We should look in which blocks each of the AggElts is being defined,
1049 // they all should be defined in the same basic block.
1050 BasicBlock *UseBB = nullptr;
1051
1052 for (const std::optional<Instruction *> &I : AggElts) {
1053 BasicBlock *BB = (*I)->getParent();
1054 // If it's the first instruction we've encountered, record the basic block.
1055 if (!UseBB) {
1056 UseBB = BB;
1057 continue;
1058 }
1059 // Otherwise, this must be the same basic block we've seen previously.
1060 if (UseBB != BB)
1061 return nullptr;
1062 }
1063
1064 // If *all* of the elements are basic-block-independent, meaning they are
1065 // either function arguments, or constant expressions, then if we didn't
1066 // handle them without predecessor-aware handling, we won't handle them now.
1067 if (!UseBB)
1068 return nullptr;
1069
1070 // If we didn't manage to find source aggregate without looking at
1071 // predecessors, and there are no predecessors to look at, then we're done.
1072 if (pred_empty(UseBB))
1073 return nullptr;
1074
1075 // Arbitrary predecessor count limit.
1076 static const int PredCountLimit = 64;
1077
1078 // Cache the (non-uniqified!) list of predecessors in a vector,
1079 // checking the limit at the same time for efficiency.
1080 SmallVector<BasicBlock *, 4> Preds; // May have duplicates!
1081 for (BasicBlock *Pred : predecessors(UseBB)) {
1082 // Don't bother if there are too many predecessors.
1083 if (Preds.size() >= PredCountLimit) // FIXME: only count duplicates once?
1084 return nullptr;
1085 Preds.emplace_back(Pred);
1086 }
1087
1088 // For each predecessor, what is the source aggregate,
1089 // from which all the elements were originally extracted from?
1090 // Note that we want for the map to have stable iteration order!
1091 SmallDenseMap<BasicBlock *, Value *, 4> SourceAggregates;
1092 for (BasicBlock *Pred : Preds) {
1093 std::pair<decltype(SourceAggregates)::iterator, bool> IV =
1094 SourceAggregates.insert({Pred, nullptr});
1095 // Did we already evaluate this predecessor?
1096 if (!IV.second)
1097 continue;
1098
1099 // Let's hope that when coming from predecessor Pred, all elements of the
1100 // aggregate produced by OrigIVI must have been originally extracted from
1101 // the same aggregate. Is that so? Can we find said original aggregate?
1102 SourceAggregate = FindCommonSourceAggregate(UseBB, Pred);
1103 if (Describe(SourceAggregate) != AggregateDescription::Found)
1104 return nullptr; // Give up.
1105 IV.first->second = *SourceAggregate;
1106 }
1107
1108 // All good! Now we just need to thread the source aggregates here.
1109 // Note that we have to insert the new PHI here, ourselves, because we can't
1110 // rely on InstCombinerImpl::run() inserting it into the right basic block.
1111 // Note that the same block can be a predecessor more than once,
1112 // and we need to preserve that invariant for the PHI node.
1113 BuilderTy::InsertPointGuard Guard(Builder);
1114 Builder.SetInsertPoint(UseBB->getFirstNonPHI());
1115 auto *PHI =
1116 Builder.CreatePHI(AggTy, Preds.size(), OrigIVI.getName() + ".merged");
1117 for (BasicBlock *Pred : Preds)
1118 PHI->addIncoming(SourceAggregates[Pred], Pred);
1119
1120 ++NumAggregateReconstructionsSimplified;
1121 return replaceInstUsesWith(OrigIVI, PHI);
1122 }
1123
1124 /// Try to find redundant insertvalue instructions, like the following ones:
1125 /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0
1126 /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0
1127 /// Here the second instruction inserts values at the same indices, as the
1128 /// first one, making the first one redundant.
1129 /// It should be transformed to:
1130 /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0
visitInsertValueInst(InsertValueInst & I)1131 Instruction *InstCombinerImpl::visitInsertValueInst(InsertValueInst &I) {
1132 bool IsRedundant = false;
1133 ArrayRef<unsigned int> FirstIndices = I.getIndices();
1134
1135 // If there is a chain of insertvalue instructions (each of them except the
1136 // last one has only one use and it's another insertvalue insn from this
1137 // chain), check if any of the 'children' uses the same indices as the first
1138 // instruction. In this case, the first one is redundant.
1139 Value *V = &I;
1140 unsigned Depth = 0;
1141 while (V->hasOneUse() && Depth < 10) {
1142 User *U = V->user_back();
1143 auto UserInsInst = dyn_cast<InsertValueInst>(U);
1144 if (!UserInsInst || U->getOperand(0) != V)
1145 break;
1146 if (UserInsInst->getIndices() == FirstIndices) {
1147 IsRedundant = true;
1148 break;
1149 }
1150 V = UserInsInst;
1151 Depth++;
1152 }
1153
1154 if (IsRedundant)
1155 return replaceInstUsesWith(I, I.getOperand(0));
1156
1157 if (Instruction *NewI = foldAggregateConstructionIntoAggregateReuse(I))
1158 return NewI;
1159
1160 return nullptr;
1161 }
1162
isShuffleEquivalentToSelect(ShuffleVectorInst & Shuf)1163 static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) {
1164 // Can not analyze scalable type, the number of elements is not a compile-time
1165 // constant.
1166 if (isa<ScalableVectorType>(Shuf.getOperand(0)->getType()))
1167 return false;
1168
1169 int MaskSize = Shuf.getShuffleMask().size();
1170 int VecSize =
1171 cast<FixedVectorType>(Shuf.getOperand(0)->getType())->getNumElements();
1172
1173 // A vector select does not change the size of the operands.
1174 if (MaskSize != VecSize)
1175 return false;
1176
1177 // Each mask element must be undefined or choose a vector element from one of
1178 // the source operands without crossing vector lanes.
1179 for (int i = 0; i != MaskSize; ++i) {
1180 int Elt = Shuf.getMaskValue(i);
1181 if (Elt != -1 && Elt != i && Elt != i + VecSize)
1182 return false;
1183 }
1184
1185 return true;
1186 }
1187
1188 /// Turn a chain of inserts that splats a value into an insert + shuffle:
1189 /// insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... ->
1190 /// shufflevector(insertelt(X, %k, 0), poison, zero)
foldInsSequenceIntoSplat(InsertElementInst & InsElt)1191 static Instruction *foldInsSequenceIntoSplat(InsertElementInst &InsElt) {
1192 // We are interested in the last insert in a chain. So if this insert has a
1193 // single user and that user is an insert, bail.
1194 if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back()))
1195 return nullptr;
1196
1197 VectorType *VecTy = InsElt.getType();
1198 // Can not handle scalable type, the number of elements is not a compile-time
1199 // constant.
1200 if (isa<ScalableVectorType>(VecTy))
1201 return nullptr;
1202 unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
1203
1204 // Do not try to do this for a one-element vector, since that's a nop,
1205 // and will cause an inf-loop.
1206 if (NumElements == 1)
1207 return nullptr;
1208
1209 Value *SplatVal = InsElt.getOperand(1);
1210 InsertElementInst *CurrIE = &InsElt;
1211 SmallBitVector ElementPresent(NumElements, false);
1212 InsertElementInst *FirstIE = nullptr;
1213
1214 // Walk the chain backwards, keeping track of which indices we inserted into,
1215 // until we hit something that isn't an insert of the splatted value.
1216 while (CurrIE) {
1217 auto *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2));
1218 if (!Idx || CurrIE->getOperand(1) != SplatVal)
1219 return nullptr;
1220
1221 auto *NextIE = dyn_cast<InsertElementInst>(CurrIE->getOperand(0));
1222 // Check none of the intermediate steps have any additional uses, except
1223 // for the root insertelement instruction, which can be re-used, if it
1224 // inserts at position 0.
1225 if (CurrIE != &InsElt &&
1226 (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero())))
1227 return nullptr;
1228
1229 ElementPresent[Idx->getZExtValue()] = true;
1230 FirstIE = CurrIE;
1231 CurrIE = NextIE;
1232 }
1233
1234 // If this is just a single insertelement (not a sequence), we are done.
1235 if (FirstIE == &InsElt)
1236 return nullptr;
1237
1238 // If we are not inserting into an undef vector, make sure we've seen an
1239 // insert into every element.
1240 // TODO: If the base vector is not undef, it might be better to create a splat
1241 // and then a select-shuffle (blend) with the base vector.
1242 if (!match(FirstIE->getOperand(0), m_Undef()))
1243 if (!ElementPresent.all())
1244 return nullptr;
1245
1246 // Create the insert + shuffle.
1247 Type *Int32Ty = Type::getInt32Ty(InsElt.getContext());
1248 PoisonValue *PoisonVec = PoisonValue::get(VecTy);
1249 Constant *Zero = ConstantInt::get(Int32Ty, 0);
1250 if (!cast<ConstantInt>(FirstIE->getOperand(2))->isZero())
1251 FirstIE = InsertElementInst::Create(PoisonVec, SplatVal, Zero, "", &InsElt);
1252
1253 // Splat from element 0, but replace absent elements with undef in the mask.
1254 SmallVector<int, 16> Mask(NumElements, 0);
1255 for (unsigned i = 0; i != NumElements; ++i)
1256 if (!ElementPresent[i])
1257 Mask[i] = -1;
1258
1259 return new ShuffleVectorInst(FirstIE, Mask);
1260 }
1261
1262 /// Try to fold an insert element into an existing splat shuffle by changing
1263 /// the shuffle's mask to include the index of this insert element.
foldInsEltIntoSplat(InsertElementInst & InsElt)1264 static Instruction *foldInsEltIntoSplat(InsertElementInst &InsElt) {
1265 // Check if the vector operand of this insert is a canonical splat shuffle.
1266 auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
1267 if (!Shuf || !Shuf->isZeroEltSplat())
1268 return nullptr;
1269
1270 // Bail out early if shuffle is scalable type. The number of elements in
1271 // shuffle mask is unknown at compile-time.
1272 if (isa<ScalableVectorType>(Shuf->getType()))
1273 return nullptr;
1274
1275 // Check for a constant insertion index.
1276 uint64_t IdxC;
1277 if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
1278 return nullptr;
1279
1280 // Check if the splat shuffle's input is the same as this insert's scalar op.
1281 Value *X = InsElt.getOperand(1);
1282 Value *Op0 = Shuf->getOperand(0);
1283 if (!match(Op0, m_InsertElt(m_Undef(), m_Specific(X), m_ZeroInt())))
1284 return nullptr;
1285
1286 // Replace the shuffle mask element at the index of this insert with a zero.
1287 // For example:
1288 // inselt (shuf (inselt undef, X, 0), _, <0,undef,0,undef>), X, 1
1289 // --> shuf (inselt undef, X, 0), poison, <0,0,0,undef>
1290 unsigned NumMaskElts =
1291 cast<FixedVectorType>(Shuf->getType())->getNumElements();
1292 SmallVector<int, 16> NewMask(NumMaskElts);
1293 for (unsigned i = 0; i != NumMaskElts; ++i)
1294 NewMask[i] = i == IdxC ? 0 : Shuf->getMaskValue(i);
1295
1296 return new ShuffleVectorInst(Op0, NewMask);
1297 }
1298
1299 /// Try to fold an extract+insert element into an existing identity shuffle by
1300 /// changing the shuffle's mask to include the index of this insert element.
foldInsEltIntoIdentityShuffle(InsertElementInst & InsElt)1301 static Instruction *foldInsEltIntoIdentityShuffle(InsertElementInst &InsElt) {
1302 // Check if the vector operand of this insert is an identity shuffle.
1303 auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0));
1304 if (!Shuf || !match(Shuf->getOperand(1), m_Undef()) ||
1305 !(Shuf->isIdentityWithExtract() || Shuf->isIdentityWithPadding()))
1306 return nullptr;
1307
1308 // Bail out early if shuffle is scalable type. The number of elements in
1309 // shuffle mask is unknown at compile-time.
1310 if (isa<ScalableVectorType>(Shuf->getType()))
1311 return nullptr;
1312
1313 // Check for a constant insertion index.
1314 uint64_t IdxC;
1315 if (!match(InsElt.getOperand(2), m_ConstantInt(IdxC)))
1316 return nullptr;
1317
1318 // Check if this insert's scalar op is extracted from the identity shuffle's
1319 // input vector.
1320 Value *Scalar = InsElt.getOperand(1);
1321 Value *X = Shuf->getOperand(0);
1322 if (!match(Scalar, m_ExtractElt(m_Specific(X), m_SpecificInt(IdxC))))
1323 return nullptr;
1324
1325 // Replace the shuffle mask element at the index of this extract+insert with
1326 // that same index value.
1327 // For example:
1328 // inselt (shuf X, IdMask), (extelt X, IdxC), IdxC --> shuf X, IdMask'
1329 unsigned NumMaskElts =
1330 cast<FixedVectorType>(Shuf->getType())->getNumElements();
1331 SmallVector<int, 16> NewMask(NumMaskElts);
1332 ArrayRef<int> OldMask = Shuf->getShuffleMask();
1333 for (unsigned i = 0; i != NumMaskElts; ++i) {
1334 if (i != IdxC) {
1335 // All mask elements besides the inserted element remain the same.
1336 NewMask[i] = OldMask[i];
1337 } else if (OldMask[i] == (int)IdxC) {
1338 // If the mask element was already set, there's nothing to do
1339 // (demanded elements analysis may unset it later).
1340 return nullptr;
1341 } else {
1342 assert(OldMask[i] == UndefMaskElem &&
1343 "Unexpected shuffle mask element for identity shuffle");
1344 NewMask[i] = IdxC;
1345 }
1346 }
1347
1348 return new ShuffleVectorInst(X, Shuf->getOperand(1), NewMask);
1349 }
1350
1351 /// If we have an insertelement instruction feeding into another insertelement
1352 /// and the 2nd is inserting a constant into the vector, canonicalize that
1353 /// constant insertion before the insertion of a variable:
1354 ///
1355 /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 -->
1356 /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1
1357 ///
1358 /// This has the potential of eliminating the 2nd insertelement instruction
1359 /// via constant folding of the scalar constant into a vector constant.
hoistInsEltConst(InsertElementInst & InsElt2,InstCombiner::BuilderTy & Builder)1360 static Instruction *hoistInsEltConst(InsertElementInst &InsElt2,
1361 InstCombiner::BuilderTy &Builder) {
1362 auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0));
1363 if (!InsElt1 || !InsElt1->hasOneUse())
1364 return nullptr;
1365
1366 Value *X, *Y;
1367 Constant *ScalarC;
1368 ConstantInt *IdxC1, *IdxC2;
1369 if (match(InsElt1->getOperand(0), m_Value(X)) &&
1370 match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) &&
1371 match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) &&
1372 match(InsElt2.getOperand(1), m_Constant(ScalarC)) &&
1373 match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) {
1374 Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2);
1375 return InsertElementInst::Create(NewInsElt1, Y, IdxC1);
1376 }
1377
1378 return nullptr;
1379 }
1380
1381 /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex
1382 /// --> shufflevector X, CVec', Mask'
foldConstantInsEltIntoShuffle(InsertElementInst & InsElt)1383 static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) {
1384 auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0));
1385 // Bail out if the parent has more than one use. In that case, we'd be
1386 // replacing the insertelt with a shuffle, and that's not a clear win.
1387 if (!Inst || !Inst->hasOneUse())
1388 return nullptr;
1389 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) {
1390 // The shuffle must have a constant vector operand. The insertelt must have
1391 // a constant scalar being inserted at a constant position in the vector.
1392 Constant *ShufConstVec, *InsEltScalar;
1393 uint64_t InsEltIndex;
1394 if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) ||
1395 !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) ||
1396 !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex)))
1397 return nullptr;
1398
1399 // Adding an element to an arbitrary shuffle could be expensive, but a
1400 // shuffle that selects elements from vectors without crossing lanes is
1401 // assumed cheap.
1402 // If we're just adding a constant into that shuffle, it will still be
1403 // cheap.
1404 if (!isShuffleEquivalentToSelect(*Shuf))
1405 return nullptr;
1406
1407 // From the above 'select' check, we know that the mask has the same number
1408 // of elements as the vector input operands. We also know that each constant
1409 // input element is used in its lane and can not be used more than once by
1410 // the shuffle. Therefore, replace the constant in the shuffle's constant
1411 // vector with the insertelt constant. Replace the constant in the shuffle's
1412 // mask vector with the insertelt index plus the length of the vector
1413 // (because the constant vector operand of a shuffle is always the 2nd
1414 // operand).
1415 ArrayRef<int> Mask = Shuf->getShuffleMask();
1416 unsigned NumElts = Mask.size();
1417 SmallVector<Constant *, 16> NewShufElts(NumElts);
1418 SmallVector<int, 16> NewMaskElts(NumElts);
1419 for (unsigned I = 0; I != NumElts; ++I) {
1420 if (I == InsEltIndex) {
1421 NewShufElts[I] = InsEltScalar;
1422 NewMaskElts[I] = InsEltIndex + NumElts;
1423 } else {
1424 // Copy over the existing values.
1425 NewShufElts[I] = ShufConstVec->getAggregateElement(I);
1426 NewMaskElts[I] = Mask[I];
1427 }
1428
1429 // Bail if we failed to find an element.
1430 if (!NewShufElts[I])
1431 return nullptr;
1432 }
1433
1434 // Create new operands for a shuffle that includes the constant of the
1435 // original insertelt. The old shuffle will be dead now.
1436 return new ShuffleVectorInst(Shuf->getOperand(0),
1437 ConstantVector::get(NewShufElts), NewMaskElts);
1438 } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) {
1439 // Transform sequences of insertelements ops with constant data/indexes into
1440 // a single shuffle op.
1441 // Can not handle scalable type, the number of elements needed to create
1442 // shuffle mask is not a compile-time constant.
1443 if (isa<ScalableVectorType>(InsElt.getType()))
1444 return nullptr;
1445 unsigned NumElts =
1446 cast<FixedVectorType>(InsElt.getType())->getNumElements();
1447
1448 uint64_t InsertIdx[2];
1449 Constant *Val[2];
1450 if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) ||
1451 !match(InsElt.getOperand(1), m_Constant(Val[0])) ||
1452 !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) ||
1453 !match(IEI->getOperand(1), m_Constant(Val[1])))
1454 return nullptr;
1455 SmallVector<Constant *, 16> Values(NumElts);
1456 SmallVector<int, 16> Mask(NumElts);
1457 auto ValI = std::begin(Val);
1458 // Generate new constant vector and mask.
1459 // We have 2 values/masks from the insertelements instructions. Insert them
1460 // into new value/mask vectors.
1461 for (uint64_t I : InsertIdx) {
1462 if (!Values[I]) {
1463 Values[I] = *ValI;
1464 Mask[I] = NumElts + I;
1465 }
1466 ++ValI;
1467 }
1468 // Remaining values are filled with 'undef' values.
1469 for (unsigned I = 0; I < NumElts; ++I) {
1470 if (!Values[I]) {
1471 Values[I] = UndefValue::get(InsElt.getType()->getElementType());
1472 Mask[I] = I;
1473 }
1474 }
1475 // Create new operands for a shuffle that includes the constant of the
1476 // original insertelt.
1477 return new ShuffleVectorInst(IEI->getOperand(0),
1478 ConstantVector::get(Values), Mask);
1479 }
1480 return nullptr;
1481 }
1482
1483 /// If both the base vector and the inserted element are extended from the same
1484 /// type, do the insert element in the narrow source type followed by extend.
1485 /// TODO: This can be extended to include other cast opcodes, but particularly
1486 /// if we create a wider insertelement, make sure codegen is not harmed.
narrowInsElt(InsertElementInst & InsElt,InstCombiner::BuilderTy & Builder)1487 static Instruction *narrowInsElt(InsertElementInst &InsElt,
1488 InstCombiner::BuilderTy &Builder) {
1489 // We are creating a vector extend. If the original vector extend has another
1490 // use, that would mean we end up with 2 vector extends, so avoid that.
1491 // TODO: We could ease the use-clause to "if at least one op has one use"
1492 // (assuming that the source types match - see next TODO comment).
1493 Value *Vec = InsElt.getOperand(0);
1494 if (!Vec->hasOneUse())
1495 return nullptr;
1496
1497 Value *Scalar = InsElt.getOperand(1);
1498 Value *X, *Y;
1499 CastInst::CastOps CastOpcode;
1500 if (match(Vec, m_FPExt(m_Value(X))) && match(Scalar, m_FPExt(m_Value(Y))))
1501 CastOpcode = Instruction::FPExt;
1502 else if (match(Vec, m_SExt(m_Value(X))) && match(Scalar, m_SExt(m_Value(Y))))
1503 CastOpcode = Instruction::SExt;
1504 else if (match(Vec, m_ZExt(m_Value(X))) && match(Scalar, m_ZExt(m_Value(Y))))
1505 CastOpcode = Instruction::ZExt;
1506 else
1507 return nullptr;
1508
1509 // TODO: We can allow mismatched types by creating an intermediate cast.
1510 if (X->getType()->getScalarType() != Y->getType())
1511 return nullptr;
1512
1513 // inselt (ext X), (ext Y), Index --> ext (inselt X, Y, Index)
1514 Value *NewInsElt = Builder.CreateInsertElement(X, Y, InsElt.getOperand(2));
1515 return CastInst::Create(CastOpcode, NewInsElt, InsElt.getType());
1516 }
1517
1518 /// If we are inserting 2 halves of a value into adjacent elements of a vector,
1519 /// try to convert to a single insert with appropriate bitcasts.
foldTruncInsEltPair(InsertElementInst & InsElt,bool IsBigEndian,InstCombiner::BuilderTy & Builder)1520 static Instruction *foldTruncInsEltPair(InsertElementInst &InsElt,
1521 bool IsBigEndian,
1522 InstCombiner::BuilderTy &Builder) {
1523 Value *VecOp = InsElt.getOperand(0);
1524 Value *ScalarOp = InsElt.getOperand(1);
1525 Value *IndexOp = InsElt.getOperand(2);
1526
1527 // Pattern depends on endian because we expect lower index is inserted first.
1528 // Big endian:
1529 // inselt (inselt BaseVec, (trunc (lshr X, BW/2), Index0), (trunc X), Index1
1530 // Little endian:
1531 // inselt (inselt BaseVec, (trunc X), Index0), (trunc (lshr X, BW/2)), Index1
1532 // Note: It is not safe to do this transform with an arbitrary base vector
1533 // because the bitcast of that vector to fewer/larger elements could
1534 // allow poison to spill into an element that was not poison before.
1535 // TODO: Detect smaller fractions of the scalar.
1536 // TODO: One-use checks are conservative.
1537 auto *VTy = dyn_cast<FixedVectorType>(InsElt.getType());
1538 Value *Scalar0, *BaseVec;
1539 uint64_t Index0, Index1;
1540 if (!VTy || (VTy->getNumElements() & 1) ||
1541 !match(IndexOp, m_ConstantInt(Index1)) ||
1542 !match(VecOp, m_InsertElt(m_Value(BaseVec), m_Value(Scalar0),
1543 m_ConstantInt(Index0))) ||
1544 !match(BaseVec, m_Undef()))
1545 return nullptr;
1546
1547 // The first insert must be to the index one less than this one, and
1548 // the first insert must be to an even index.
1549 if (Index0 + 1 != Index1 || Index0 & 1)
1550 return nullptr;
1551
1552 // For big endian, the high half of the value should be inserted first.
1553 // For little endian, the low half of the value should be inserted first.
1554 Value *X;
1555 uint64_t ShAmt;
1556 if (IsBigEndian) {
1557 if (!match(ScalarOp, m_Trunc(m_Value(X))) ||
1558 !match(Scalar0, m_Trunc(m_LShr(m_Specific(X), m_ConstantInt(ShAmt)))))
1559 return nullptr;
1560 } else {
1561 if (!match(Scalar0, m_Trunc(m_Value(X))) ||
1562 !match(ScalarOp, m_Trunc(m_LShr(m_Specific(X), m_ConstantInt(ShAmt)))))
1563 return nullptr;
1564 }
1565
1566 Type *SrcTy = X->getType();
1567 unsigned ScalarWidth = SrcTy->getScalarSizeInBits();
1568 unsigned VecEltWidth = VTy->getScalarSizeInBits();
1569 if (ScalarWidth != VecEltWidth * 2 || ShAmt != VecEltWidth)
1570 return nullptr;
1571
1572 // Bitcast the base vector to a vector type with the source element type.
1573 Type *CastTy = FixedVectorType::get(SrcTy, VTy->getNumElements() / 2);
1574 Value *CastBaseVec = Builder.CreateBitCast(BaseVec, CastTy);
1575
1576 // Scale the insert index for a vector with half as many elements.
1577 // bitcast (inselt (bitcast BaseVec), X, NewIndex)
1578 uint64_t NewIndex = IsBigEndian ? Index1 / 2 : Index0 / 2;
1579 Value *NewInsert = Builder.CreateInsertElement(CastBaseVec, X, NewIndex);
1580 return new BitCastInst(NewInsert, VTy);
1581 }
1582
visitInsertElementInst(InsertElementInst & IE)1583 Instruction *InstCombinerImpl::visitInsertElementInst(InsertElementInst &IE) {
1584 Value *VecOp = IE.getOperand(0);
1585 Value *ScalarOp = IE.getOperand(1);
1586 Value *IdxOp = IE.getOperand(2);
1587
1588 if (auto *V = simplifyInsertElementInst(
1589 VecOp, ScalarOp, IdxOp, SQ.getWithInstruction(&IE)))
1590 return replaceInstUsesWith(IE, V);
1591
1592 // Canonicalize type of constant indices to i64 to simplify CSE
1593 if (auto *IndexC = dyn_cast<ConstantInt>(IdxOp)) {
1594 if (auto *NewIdx = getPreferredVectorIndex(IndexC))
1595 return replaceOperand(IE, 2, NewIdx);
1596
1597 Value *BaseVec, *OtherScalar;
1598 uint64_t OtherIndexVal;
1599 if (match(VecOp, m_OneUse(m_InsertElt(m_Value(BaseVec),
1600 m_Value(OtherScalar),
1601 m_ConstantInt(OtherIndexVal)))) &&
1602 !isa<Constant>(OtherScalar) && OtherIndexVal > IndexC->getZExtValue()) {
1603 Value *NewIns = Builder.CreateInsertElement(BaseVec, ScalarOp, IdxOp);
1604 return InsertElementInst::Create(NewIns, OtherScalar,
1605 Builder.getInt64(OtherIndexVal));
1606 }
1607 }
1608
1609 // If the scalar is bitcast and inserted into undef, do the insert in the
1610 // source type followed by bitcast.
1611 // TODO: Generalize for insert into any constant, not just undef?
1612 Value *ScalarSrc;
1613 if (match(VecOp, m_Undef()) &&
1614 match(ScalarOp, m_OneUse(m_BitCast(m_Value(ScalarSrc)))) &&
1615 (ScalarSrc->getType()->isIntegerTy() ||
1616 ScalarSrc->getType()->isFloatingPointTy())) {
1617 // inselt undef, (bitcast ScalarSrc), IdxOp -->
1618 // bitcast (inselt undef, ScalarSrc, IdxOp)
1619 Type *ScalarTy = ScalarSrc->getType();
1620 Type *VecTy = VectorType::get(ScalarTy, IE.getType()->getElementCount());
1621 UndefValue *NewUndef = UndefValue::get(VecTy);
1622 Value *NewInsElt = Builder.CreateInsertElement(NewUndef, ScalarSrc, IdxOp);
1623 return new BitCastInst(NewInsElt, IE.getType());
1624 }
1625
1626 // If the vector and scalar are both bitcast from the same element type, do
1627 // the insert in that source type followed by bitcast.
1628 Value *VecSrc;
1629 if (match(VecOp, m_BitCast(m_Value(VecSrc))) &&
1630 match(ScalarOp, m_BitCast(m_Value(ScalarSrc))) &&
1631 (VecOp->hasOneUse() || ScalarOp->hasOneUse()) &&
1632 VecSrc->getType()->isVectorTy() && !ScalarSrc->getType()->isVectorTy() &&
1633 cast<VectorType>(VecSrc->getType())->getElementType() ==
1634 ScalarSrc->getType()) {
1635 // inselt (bitcast VecSrc), (bitcast ScalarSrc), IdxOp -->
1636 // bitcast (inselt VecSrc, ScalarSrc, IdxOp)
1637 Value *NewInsElt = Builder.CreateInsertElement(VecSrc, ScalarSrc, IdxOp);
1638 return new BitCastInst(NewInsElt, IE.getType());
1639 }
1640
1641 // If the inserted element was extracted from some other fixed-length vector
1642 // and both indexes are valid constants, try to turn this into a shuffle.
1643 // Can not handle scalable vector type, the number of elements needed to
1644 // create shuffle mask is not a compile-time constant.
1645 uint64_t InsertedIdx, ExtractedIdx;
1646 Value *ExtVecOp;
1647 if (isa<FixedVectorType>(IE.getType()) &&
1648 match(IdxOp, m_ConstantInt(InsertedIdx)) &&
1649 match(ScalarOp,
1650 m_ExtractElt(m_Value(ExtVecOp), m_ConstantInt(ExtractedIdx))) &&
1651 isa<FixedVectorType>(ExtVecOp->getType()) &&
1652 ExtractedIdx <
1653 cast<FixedVectorType>(ExtVecOp->getType())->getNumElements()) {
1654 // TODO: Looking at the user(s) to determine if this insert is a
1655 // fold-to-shuffle opportunity does not match the usual instcombine
1656 // constraints. We should decide if the transform is worthy based only
1657 // on this instruction and its operands, but that may not work currently.
1658 //
1659 // Here, we are trying to avoid creating shuffles before reaching
1660 // the end of a chain of extract-insert pairs. This is complicated because
1661 // we do not generally form arbitrary shuffle masks in instcombine
1662 // (because those may codegen poorly), but collectShuffleElements() does
1663 // exactly that.
1664 //
1665 // The rules for determining what is an acceptable target-independent
1666 // shuffle mask are fuzzy because they evolve based on the backend's
1667 // capabilities and real-world impact.
1668 auto isShuffleRootCandidate = [](InsertElementInst &Insert) {
1669 if (!Insert.hasOneUse())
1670 return true;
1671 auto *InsertUser = dyn_cast<InsertElementInst>(Insert.user_back());
1672 if (!InsertUser)
1673 return true;
1674 return false;
1675 };
1676
1677 // Try to form a shuffle from a chain of extract-insert ops.
1678 if (isShuffleRootCandidate(IE)) {
1679 SmallVector<int, 16> Mask;
1680 ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this);
1681
1682 // The proposed shuffle may be trivial, in which case we shouldn't
1683 // perform the combine.
1684 if (LR.first != &IE && LR.second != &IE) {
1685 // We now have a shuffle of LHS, RHS, Mask.
1686 if (LR.second == nullptr)
1687 LR.second = UndefValue::get(LR.first->getType());
1688 return new ShuffleVectorInst(LR.first, LR.second, Mask);
1689 }
1690 }
1691 }
1692
1693 if (auto VecTy = dyn_cast<FixedVectorType>(VecOp->getType())) {
1694 unsigned VWidth = VecTy->getNumElements();
1695 APInt UndefElts(VWidth, 0);
1696 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
1697 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) {
1698 if (V != &IE)
1699 return replaceInstUsesWith(IE, V);
1700 return &IE;
1701 }
1702 }
1703
1704 if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE))
1705 return Shuf;
1706
1707 if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder))
1708 return NewInsElt;
1709
1710 if (Instruction *Broadcast = foldInsSequenceIntoSplat(IE))
1711 return Broadcast;
1712
1713 if (Instruction *Splat = foldInsEltIntoSplat(IE))
1714 return Splat;
1715
1716 if (Instruction *IdentityShuf = foldInsEltIntoIdentityShuffle(IE))
1717 return IdentityShuf;
1718
1719 if (Instruction *Ext = narrowInsElt(IE, Builder))
1720 return Ext;
1721
1722 if (Instruction *Ext = foldTruncInsEltPair(IE, DL.isBigEndian(), Builder))
1723 return Ext;
1724
1725 return nullptr;
1726 }
1727
1728 /// Return true if we can evaluate the specified expression tree if the vector
1729 /// elements were shuffled in a different order.
canEvaluateShuffled(Value * V,ArrayRef<int> Mask,unsigned Depth=5)1730 static bool canEvaluateShuffled(Value *V, ArrayRef<int> Mask,
1731 unsigned Depth = 5) {
1732 // We can always reorder the elements of a constant.
1733 if (isa<Constant>(V))
1734 return true;
1735
1736 // We won't reorder vector arguments. No IPO here.
1737 Instruction *I = dyn_cast<Instruction>(V);
1738 if (!I) return false;
1739
1740 // Two users may expect different orders of the elements. Don't try it.
1741 if (!I->hasOneUse())
1742 return false;
1743
1744 if (Depth == 0) return false;
1745
1746 switch (I->getOpcode()) {
1747 case Instruction::UDiv:
1748 case Instruction::SDiv:
1749 case Instruction::URem:
1750 case Instruction::SRem:
1751 // Propagating an undefined shuffle mask element to integer div/rem is not
1752 // allowed because those opcodes can create immediate undefined behavior
1753 // from an undefined element in an operand.
1754 if (llvm::is_contained(Mask, -1))
1755 return false;
1756 [[fallthrough]];
1757 case Instruction::Add:
1758 case Instruction::FAdd:
1759 case Instruction::Sub:
1760 case Instruction::FSub:
1761 case Instruction::Mul:
1762 case Instruction::FMul:
1763 case Instruction::FDiv:
1764 case Instruction::FRem:
1765 case Instruction::Shl:
1766 case Instruction::LShr:
1767 case Instruction::AShr:
1768 case Instruction::And:
1769 case Instruction::Or:
1770 case Instruction::Xor:
1771 case Instruction::ICmp:
1772 case Instruction::FCmp:
1773 case Instruction::Trunc:
1774 case Instruction::ZExt:
1775 case Instruction::SExt:
1776 case Instruction::FPToUI:
1777 case Instruction::FPToSI:
1778 case Instruction::UIToFP:
1779 case Instruction::SIToFP:
1780 case Instruction::FPTrunc:
1781 case Instruction::FPExt:
1782 case Instruction::GetElementPtr: {
1783 // Bail out if we would create longer vector ops. We could allow creating
1784 // longer vector ops, but that may result in more expensive codegen.
1785 Type *ITy = I->getType();
1786 if (ITy->isVectorTy() &&
1787 Mask.size() > cast<FixedVectorType>(ITy)->getNumElements())
1788 return false;
1789 for (Value *Operand : I->operands()) {
1790 if (!canEvaluateShuffled(Operand, Mask, Depth - 1))
1791 return false;
1792 }
1793 return true;
1794 }
1795 case Instruction::InsertElement: {
1796 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2));
1797 if (!CI) return false;
1798 int ElementNumber = CI->getLimitedValue();
1799
1800 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement'
1801 // can't put an element into multiple indices.
1802 bool SeenOnce = false;
1803 for (int I : Mask) {
1804 if (I == ElementNumber) {
1805 if (SeenOnce)
1806 return false;
1807 SeenOnce = true;
1808 }
1809 }
1810 return canEvaluateShuffled(I->getOperand(0), Mask, Depth - 1);
1811 }
1812 }
1813 return false;
1814 }
1815
1816 /// Rebuild a new instruction just like 'I' but with the new operands given.
1817 /// In the event of type mismatch, the type of the operands is correct.
buildNew(Instruction * I,ArrayRef<Value * > NewOps)1818 static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) {
1819 // We don't want to use the IRBuilder here because we want the replacement
1820 // instructions to appear next to 'I', not the builder's insertion point.
1821 switch (I->getOpcode()) {
1822 case Instruction::Add:
1823 case Instruction::FAdd:
1824 case Instruction::Sub:
1825 case Instruction::FSub:
1826 case Instruction::Mul:
1827 case Instruction::FMul:
1828 case Instruction::UDiv:
1829 case Instruction::SDiv:
1830 case Instruction::FDiv:
1831 case Instruction::URem:
1832 case Instruction::SRem:
1833 case Instruction::FRem:
1834 case Instruction::Shl:
1835 case Instruction::LShr:
1836 case Instruction::AShr:
1837 case Instruction::And:
1838 case Instruction::Or:
1839 case Instruction::Xor: {
1840 BinaryOperator *BO = cast<BinaryOperator>(I);
1841 assert(NewOps.size() == 2 && "binary operator with #ops != 2");
1842 BinaryOperator *New =
1843 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(),
1844 NewOps[0], NewOps[1], "", BO);
1845 if (isa<OverflowingBinaryOperator>(BO)) {
1846 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap());
1847 New->setHasNoSignedWrap(BO->hasNoSignedWrap());
1848 }
1849 if (isa<PossiblyExactOperator>(BO)) {
1850 New->setIsExact(BO->isExact());
1851 }
1852 if (isa<FPMathOperator>(BO))
1853 New->copyFastMathFlags(I);
1854 return New;
1855 }
1856 case Instruction::ICmp:
1857 assert(NewOps.size() == 2 && "icmp with #ops != 2");
1858 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(),
1859 NewOps[0], NewOps[1]);
1860 case Instruction::FCmp:
1861 assert(NewOps.size() == 2 && "fcmp with #ops != 2");
1862 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(),
1863 NewOps[0], NewOps[1]);
1864 case Instruction::Trunc:
1865 case Instruction::ZExt:
1866 case Instruction::SExt:
1867 case Instruction::FPToUI:
1868 case Instruction::FPToSI:
1869 case Instruction::UIToFP:
1870 case Instruction::SIToFP:
1871 case Instruction::FPTrunc:
1872 case Instruction::FPExt: {
1873 // It's possible that the mask has a different number of elements from
1874 // the original cast. We recompute the destination type to match the mask.
1875 Type *DestTy = VectorType::get(
1876 I->getType()->getScalarType(),
1877 cast<VectorType>(NewOps[0]->getType())->getElementCount());
1878 assert(NewOps.size() == 1 && "cast with #ops != 1");
1879 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy,
1880 "", I);
1881 }
1882 case Instruction::GetElementPtr: {
1883 Value *Ptr = NewOps[0];
1884 ArrayRef<Value*> Idx = NewOps.slice(1);
1885 GetElementPtrInst *GEP = GetElementPtrInst::Create(
1886 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I);
1887 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds());
1888 return GEP;
1889 }
1890 }
1891 llvm_unreachable("failed to rebuild vector instructions");
1892 }
1893
evaluateInDifferentElementOrder(Value * V,ArrayRef<int> Mask)1894 static Value *evaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) {
1895 // Mask.size() does not need to be equal to the number of vector elements.
1896
1897 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements");
1898 Type *EltTy = V->getType()->getScalarType();
1899 Type *I32Ty = IntegerType::getInt32Ty(V->getContext());
1900 if (match(V, m_Undef()))
1901 return UndefValue::get(FixedVectorType::get(EltTy, Mask.size()));
1902
1903 if (isa<ConstantAggregateZero>(V))
1904 return ConstantAggregateZero::get(FixedVectorType::get(EltTy, Mask.size()));
1905
1906 if (Constant *C = dyn_cast<Constant>(V))
1907 return ConstantExpr::getShuffleVector(C, PoisonValue::get(C->getType()),
1908 Mask);
1909
1910 Instruction *I = cast<Instruction>(V);
1911 switch (I->getOpcode()) {
1912 case Instruction::Add:
1913 case Instruction::FAdd:
1914 case Instruction::Sub:
1915 case Instruction::FSub:
1916 case Instruction::Mul:
1917 case Instruction::FMul:
1918 case Instruction::UDiv:
1919 case Instruction::SDiv:
1920 case Instruction::FDiv:
1921 case Instruction::URem:
1922 case Instruction::SRem:
1923 case Instruction::FRem:
1924 case Instruction::Shl:
1925 case Instruction::LShr:
1926 case Instruction::AShr:
1927 case Instruction::And:
1928 case Instruction::Or:
1929 case Instruction::Xor:
1930 case Instruction::ICmp:
1931 case Instruction::FCmp:
1932 case Instruction::Trunc:
1933 case Instruction::ZExt:
1934 case Instruction::SExt:
1935 case Instruction::FPToUI:
1936 case Instruction::FPToSI:
1937 case Instruction::UIToFP:
1938 case Instruction::SIToFP:
1939 case Instruction::FPTrunc:
1940 case Instruction::FPExt:
1941 case Instruction::Select:
1942 case Instruction::GetElementPtr: {
1943 SmallVector<Value*, 8> NewOps;
1944 bool NeedsRebuild =
1945 (Mask.size() !=
1946 cast<FixedVectorType>(I->getType())->getNumElements());
1947 for (int i = 0, e = I->getNumOperands(); i != e; ++i) {
1948 Value *V;
1949 // Recursively call evaluateInDifferentElementOrder on vector arguments
1950 // as well. E.g. GetElementPtr may have scalar operands even if the
1951 // return value is a vector, so we need to examine the operand type.
1952 if (I->getOperand(i)->getType()->isVectorTy())
1953 V = evaluateInDifferentElementOrder(I->getOperand(i), Mask);
1954 else
1955 V = I->getOperand(i);
1956 NewOps.push_back(V);
1957 NeedsRebuild |= (V != I->getOperand(i));
1958 }
1959 if (NeedsRebuild) {
1960 return buildNew(I, NewOps);
1961 }
1962 return I;
1963 }
1964 case Instruction::InsertElement: {
1965 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue();
1966
1967 // The insertelement was inserting at Element. Figure out which element
1968 // that becomes after shuffling. The answer is guaranteed to be unique
1969 // by CanEvaluateShuffled.
1970 bool Found = false;
1971 int Index = 0;
1972 for (int e = Mask.size(); Index != e; ++Index) {
1973 if (Mask[Index] == Element) {
1974 Found = true;
1975 break;
1976 }
1977 }
1978
1979 // If element is not in Mask, no need to handle the operand 1 (element to
1980 // be inserted). Just evaluate values in operand 0 according to Mask.
1981 if (!Found)
1982 return evaluateInDifferentElementOrder(I->getOperand(0), Mask);
1983
1984 Value *V = evaluateInDifferentElementOrder(I->getOperand(0), Mask);
1985 return InsertElementInst::Create(V, I->getOperand(1),
1986 ConstantInt::get(I32Ty, Index), "", I);
1987 }
1988 }
1989 llvm_unreachable("failed to reorder elements of vector instruction!");
1990 }
1991
1992 // Returns true if the shuffle is extracting a contiguous range of values from
1993 // LHS, for example:
1994 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
1995 // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP|
1996 // Shuffles to: |EE|FF|GG|HH|
1997 // +--+--+--+--+
isShuffleExtractingFromLHS(ShuffleVectorInst & SVI,ArrayRef<int> Mask)1998 static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI,
1999 ArrayRef<int> Mask) {
2000 unsigned LHSElems =
2001 cast<FixedVectorType>(SVI.getOperand(0)->getType())->getNumElements();
2002 unsigned MaskElems = Mask.size();
2003 unsigned BegIdx = Mask.front();
2004 unsigned EndIdx = Mask.back();
2005 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1)
2006 return false;
2007 for (unsigned I = 0; I != MaskElems; ++I)
2008 if (static_cast<unsigned>(Mask[I]) != BegIdx + I)
2009 return false;
2010 return true;
2011 }
2012
2013 /// These are the ingredients in an alternate form binary operator as described
2014 /// below.
2015 struct BinopElts {
2016 BinaryOperator::BinaryOps Opcode;
2017 Value *Op0;
2018 Value *Op1;
BinopEltsBinopElts2019 BinopElts(BinaryOperator::BinaryOps Opc = (BinaryOperator::BinaryOps)0,
2020 Value *V0 = nullptr, Value *V1 = nullptr) :
2021 Opcode(Opc), Op0(V0), Op1(V1) {}
operator boolBinopElts2022 operator bool() const { return Opcode != 0; }
2023 };
2024
2025 /// Binops may be transformed into binops with different opcodes and operands.
2026 /// Reverse the usual canonicalization to enable folds with the non-canonical
2027 /// form of the binop. If a transform is possible, return the elements of the
2028 /// new binop. If not, return invalid elements.
getAlternateBinop(BinaryOperator * BO,const DataLayout & DL)2029 static BinopElts getAlternateBinop(BinaryOperator *BO, const DataLayout &DL) {
2030 Value *BO0 = BO->getOperand(0), *BO1 = BO->getOperand(1);
2031 Type *Ty = BO->getType();
2032 switch (BO->getOpcode()) {
2033 case Instruction::Shl: {
2034 // shl X, C --> mul X, (1 << C)
2035 Constant *C;
2036 if (match(BO1, m_Constant(C))) {
2037 Constant *ShlOne = ConstantExpr::getShl(ConstantInt::get(Ty, 1), C);
2038 return {Instruction::Mul, BO0, ShlOne};
2039 }
2040 break;
2041 }
2042 case Instruction::Or: {
2043 // or X, C --> add X, C (when X and C have no common bits set)
2044 const APInt *C;
2045 if (match(BO1, m_APInt(C)) && MaskedValueIsZero(BO0, *C, DL))
2046 return {Instruction::Add, BO0, BO1};
2047 break;
2048 }
2049 case Instruction::Sub:
2050 // sub 0, X --> mul X, -1
2051 if (match(BO0, m_ZeroInt()))
2052 return {Instruction::Mul, BO1, ConstantInt::getAllOnesValue(Ty)};
2053 break;
2054 default:
2055 break;
2056 }
2057 return {};
2058 }
2059
2060 /// A select shuffle of a select shuffle with a shared operand can be reduced
2061 /// to a single select shuffle. This is an obvious improvement in IR, and the
2062 /// backend is expected to lower select shuffles efficiently.
foldSelectShuffleOfSelectShuffle(ShuffleVectorInst & Shuf)2063 static Instruction *foldSelectShuffleOfSelectShuffle(ShuffleVectorInst &Shuf) {
2064 assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
2065
2066 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2067 SmallVector<int, 16> Mask;
2068 Shuf.getShuffleMask(Mask);
2069 unsigned NumElts = Mask.size();
2070
2071 // Canonicalize a select shuffle with common operand as Op1.
2072 auto *ShufOp = dyn_cast<ShuffleVectorInst>(Op0);
2073 if (ShufOp && ShufOp->isSelect() &&
2074 (ShufOp->getOperand(0) == Op1 || ShufOp->getOperand(1) == Op1)) {
2075 std::swap(Op0, Op1);
2076 ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
2077 }
2078
2079 ShufOp = dyn_cast<ShuffleVectorInst>(Op1);
2080 if (!ShufOp || !ShufOp->isSelect() ||
2081 (ShufOp->getOperand(0) != Op0 && ShufOp->getOperand(1) != Op0))
2082 return nullptr;
2083
2084 Value *X = ShufOp->getOperand(0), *Y = ShufOp->getOperand(1);
2085 SmallVector<int, 16> Mask1;
2086 ShufOp->getShuffleMask(Mask1);
2087 assert(Mask1.size() == NumElts && "Vector size changed with select shuffle");
2088
2089 // Canonicalize common operand (Op0) as X (first operand of first shuffle).
2090 if (Y == Op0) {
2091 std::swap(X, Y);
2092 ShuffleVectorInst::commuteShuffleMask(Mask1, NumElts);
2093 }
2094
2095 // If the mask chooses from X (operand 0), it stays the same.
2096 // If the mask chooses from the earlier shuffle, the other mask value is
2097 // transferred to the combined select shuffle:
2098 // shuf X, (shuf X, Y, M1), M --> shuf X, Y, M'
2099 SmallVector<int, 16> NewMask(NumElts);
2100 for (unsigned i = 0; i != NumElts; ++i)
2101 NewMask[i] = Mask[i] < (signed)NumElts ? Mask[i] : Mask1[i];
2102
2103 // A select mask with undef elements might look like an identity mask.
2104 assert((ShuffleVectorInst::isSelectMask(NewMask) ||
2105 ShuffleVectorInst::isIdentityMask(NewMask)) &&
2106 "Unexpected shuffle mask");
2107 return new ShuffleVectorInst(X, Y, NewMask);
2108 }
2109
foldSelectShuffleWith1Binop(ShuffleVectorInst & Shuf)2110 static Instruction *foldSelectShuffleWith1Binop(ShuffleVectorInst &Shuf) {
2111 assert(Shuf.isSelect() && "Must have select-equivalent shuffle");
2112
2113 // Are we shuffling together some value and that same value after it has been
2114 // modified by a binop with a constant?
2115 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2116 Constant *C;
2117 bool Op0IsBinop;
2118 if (match(Op0, m_BinOp(m_Specific(Op1), m_Constant(C))))
2119 Op0IsBinop = true;
2120 else if (match(Op1, m_BinOp(m_Specific(Op0), m_Constant(C))))
2121 Op0IsBinop = false;
2122 else
2123 return nullptr;
2124
2125 // The identity constant for a binop leaves a variable operand unchanged. For
2126 // a vector, this is a splat of something like 0, -1, or 1.
2127 // If there's no identity constant for this binop, we're done.
2128 auto *BO = cast<BinaryOperator>(Op0IsBinop ? Op0 : Op1);
2129 BinaryOperator::BinaryOps BOpcode = BO->getOpcode();
2130 Constant *IdC = ConstantExpr::getBinOpIdentity(BOpcode, Shuf.getType(), true);
2131 if (!IdC)
2132 return nullptr;
2133
2134 // Shuffle identity constants into the lanes that return the original value.
2135 // Example: shuf (mul X, {-1,-2,-3,-4}), X, {0,5,6,3} --> mul X, {-1,1,1,-4}
2136 // Example: shuf X, (add X, {-1,-2,-3,-4}), {0,1,6,7} --> add X, {0,0,-3,-4}
2137 // The existing binop constant vector remains in the same operand position.
2138 ArrayRef<int> Mask = Shuf.getShuffleMask();
2139 Constant *NewC = Op0IsBinop ? ConstantExpr::getShuffleVector(C, IdC, Mask) :
2140 ConstantExpr::getShuffleVector(IdC, C, Mask);
2141
2142 bool MightCreatePoisonOrUB =
2143 is_contained(Mask, UndefMaskElem) &&
2144 (Instruction::isIntDivRem(BOpcode) || Instruction::isShift(BOpcode));
2145 if (MightCreatePoisonOrUB)
2146 NewC = InstCombiner::getSafeVectorConstantForBinop(BOpcode, NewC, true);
2147
2148 // shuf (bop X, C), X, M --> bop X, C'
2149 // shuf X, (bop X, C), M --> bop X, C'
2150 Value *X = Op0IsBinop ? Op1 : Op0;
2151 Instruction *NewBO = BinaryOperator::Create(BOpcode, X, NewC);
2152 NewBO->copyIRFlags(BO);
2153
2154 // An undef shuffle mask element may propagate as an undef constant element in
2155 // the new binop. That would produce poison where the original code might not.
2156 // If we already made a safe constant, then there's no danger.
2157 if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB)
2158 NewBO->dropPoisonGeneratingFlags();
2159 return NewBO;
2160 }
2161
2162 /// If we have an insert of a scalar to a non-zero element of an undefined
2163 /// vector and then shuffle that value, that's the same as inserting to the zero
2164 /// element and shuffling. Splatting from the zero element is recognized as the
2165 /// canonical form of splat.
canonicalizeInsertSplat(ShuffleVectorInst & Shuf,InstCombiner::BuilderTy & Builder)2166 static Instruction *canonicalizeInsertSplat(ShuffleVectorInst &Shuf,
2167 InstCombiner::BuilderTy &Builder) {
2168 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2169 ArrayRef<int> Mask = Shuf.getShuffleMask();
2170 Value *X;
2171 uint64_t IndexC;
2172
2173 // Match a shuffle that is a splat to a non-zero element.
2174 if (!match(Op0, m_OneUse(m_InsertElt(m_Undef(), m_Value(X),
2175 m_ConstantInt(IndexC)))) ||
2176 !match(Op1, m_Undef()) || match(Mask, m_ZeroMask()) || IndexC == 0)
2177 return nullptr;
2178
2179 // Insert into element 0 of an undef vector.
2180 UndefValue *UndefVec = UndefValue::get(Shuf.getType());
2181 Constant *Zero = Builder.getInt32(0);
2182 Value *NewIns = Builder.CreateInsertElement(UndefVec, X, Zero);
2183
2184 // Splat from element 0. Any mask element that is undefined remains undefined.
2185 // For example:
2186 // shuf (inselt undef, X, 2), _, <2,2,undef>
2187 // --> shuf (inselt undef, X, 0), poison, <0,0,undef>
2188 unsigned NumMaskElts =
2189 cast<FixedVectorType>(Shuf.getType())->getNumElements();
2190 SmallVector<int, 16> NewMask(NumMaskElts, 0);
2191 for (unsigned i = 0; i != NumMaskElts; ++i)
2192 if (Mask[i] == UndefMaskElem)
2193 NewMask[i] = Mask[i];
2194
2195 return new ShuffleVectorInst(NewIns, NewMask);
2196 }
2197
2198 /// Try to fold shuffles that are the equivalent of a vector select.
foldSelectShuffle(ShuffleVectorInst & Shuf)2199 Instruction *InstCombinerImpl::foldSelectShuffle(ShuffleVectorInst &Shuf) {
2200 if (!Shuf.isSelect())
2201 return nullptr;
2202
2203 // Canonicalize to choose from operand 0 first unless operand 1 is undefined.
2204 // Commuting undef to operand 0 conflicts with another canonicalization.
2205 unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
2206 if (!match(Shuf.getOperand(1), m_Undef()) &&
2207 Shuf.getMaskValue(0) >= (int)NumElts) {
2208 // TODO: Can we assert that both operands of a shuffle-select are not undef
2209 // (otherwise, it would have been folded by instsimplify?
2210 Shuf.commute();
2211 return &Shuf;
2212 }
2213
2214 if (Instruction *I = foldSelectShuffleOfSelectShuffle(Shuf))
2215 return I;
2216
2217 if (Instruction *I = foldSelectShuffleWith1Binop(Shuf))
2218 return I;
2219
2220 BinaryOperator *B0, *B1;
2221 if (!match(Shuf.getOperand(0), m_BinOp(B0)) ||
2222 !match(Shuf.getOperand(1), m_BinOp(B1)))
2223 return nullptr;
2224
2225 // If one operand is "0 - X", allow that to be viewed as "X * -1"
2226 // (ConstantsAreOp1) by getAlternateBinop below. If the neg is not paired
2227 // with a multiply, we will exit because C0/C1 will not be set.
2228 Value *X, *Y;
2229 Constant *C0 = nullptr, *C1 = nullptr;
2230 bool ConstantsAreOp1;
2231 if (match(B0, m_BinOp(m_Constant(C0), m_Value(X))) &&
2232 match(B1, m_BinOp(m_Constant(C1), m_Value(Y))))
2233 ConstantsAreOp1 = false;
2234 else if (match(B0, m_CombineOr(m_BinOp(m_Value(X), m_Constant(C0)),
2235 m_Neg(m_Value(X)))) &&
2236 match(B1, m_CombineOr(m_BinOp(m_Value(Y), m_Constant(C1)),
2237 m_Neg(m_Value(Y)))))
2238 ConstantsAreOp1 = true;
2239 else
2240 return nullptr;
2241
2242 // We need matching binops to fold the lanes together.
2243 BinaryOperator::BinaryOps Opc0 = B0->getOpcode();
2244 BinaryOperator::BinaryOps Opc1 = B1->getOpcode();
2245 bool DropNSW = false;
2246 if (ConstantsAreOp1 && Opc0 != Opc1) {
2247 // TODO: We drop "nsw" if shift is converted into multiply because it may
2248 // not be correct when the shift amount is BitWidth - 1. We could examine
2249 // each vector element to determine if it is safe to keep that flag.
2250 if (Opc0 == Instruction::Shl || Opc1 == Instruction::Shl)
2251 DropNSW = true;
2252 if (BinopElts AltB0 = getAlternateBinop(B0, DL)) {
2253 assert(isa<Constant>(AltB0.Op1) && "Expecting constant with alt binop");
2254 Opc0 = AltB0.Opcode;
2255 C0 = cast<Constant>(AltB0.Op1);
2256 } else if (BinopElts AltB1 = getAlternateBinop(B1, DL)) {
2257 assert(isa<Constant>(AltB1.Op1) && "Expecting constant with alt binop");
2258 Opc1 = AltB1.Opcode;
2259 C1 = cast<Constant>(AltB1.Op1);
2260 }
2261 }
2262
2263 if (Opc0 != Opc1 || !C0 || !C1)
2264 return nullptr;
2265
2266 // The opcodes must be the same. Use a new name to make that clear.
2267 BinaryOperator::BinaryOps BOpc = Opc0;
2268
2269 // Select the constant elements needed for the single binop.
2270 ArrayRef<int> Mask = Shuf.getShuffleMask();
2271 Constant *NewC = ConstantExpr::getShuffleVector(C0, C1, Mask);
2272
2273 // We are moving a binop after a shuffle. When a shuffle has an undefined
2274 // mask element, the result is undefined, but it is not poison or undefined
2275 // behavior. That is not necessarily true for div/rem/shift.
2276 bool MightCreatePoisonOrUB =
2277 is_contained(Mask, UndefMaskElem) &&
2278 (Instruction::isIntDivRem(BOpc) || Instruction::isShift(BOpc));
2279 if (MightCreatePoisonOrUB)
2280 NewC = InstCombiner::getSafeVectorConstantForBinop(BOpc, NewC,
2281 ConstantsAreOp1);
2282
2283 Value *V;
2284 if (X == Y) {
2285 // Remove a binop and the shuffle by rearranging the constant:
2286 // shuffle (op V, C0), (op V, C1), M --> op V, C'
2287 // shuffle (op C0, V), (op C1, V), M --> op C', V
2288 V = X;
2289 } else {
2290 // If there are 2 different variable operands, we must create a new shuffle
2291 // (select) first, so check uses to ensure that we don't end up with more
2292 // instructions than we started with.
2293 if (!B0->hasOneUse() && !B1->hasOneUse())
2294 return nullptr;
2295
2296 // If we use the original shuffle mask and op1 is *variable*, we would be
2297 // putting an undef into operand 1 of div/rem/shift. This is either UB or
2298 // poison. We do not have to guard against UB when *constants* are op1
2299 // because safe constants guarantee that we do not overflow sdiv/srem (and
2300 // there's no danger for other opcodes).
2301 // TODO: To allow this case, create a new shuffle mask with no undefs.
2302 if (MightCreatePoisonOrUB && !ConstantsAreOp1)
2303 return nullptr;
2304
2305 // Note: In general, we do not create new shuffles in InstCombine because we
2306 // do not know if a target can lower an arbitrary shuffle optimally. In this
2307 // case, the shuffle uses the existing mask, so there is no additional risk.
2308
2309 // Select the variable vectors first, then perform the binop:
2310 // shuffle (op X, C0), (op Y, C1), M --> op (shuffle X, Y, M), C'
2311 // shuffle (op C0, X), (op C1, Y), M --> op C', (shuffle X, Y, M)
2312 V = Builder.CreateShuffleVector(X, Y, Mask);
2313 }
2314
2315 Value *NewBO = ConstantsAreOp1 ? Builder.CreateBinOp(BOpc, V, NewC) :
2316 Builder.CreateBinOp(BOpc, NewC, V);
2317
2318 // Flags are intersected from the 2 source binops. But there are 2 exceptions:
2319 // 1. If we changed an opcode, poison conditions might have changed.
2320 // 2. If the shuffle had undef mask elements, the new binop might have undefs
2321 // where the original code did not. But if we already made a safe constant,
2322 // then there's no danger.
2323 if (auto *NewI = dyn_cast<Instruction>(NewBO)) {
2324 NewI->copyIRFlags(B0);
2325 NewI->andIRFlags(B1);
2326 if (DropNSW)
2327 NewI->setHasNoSignedWrap(false);
2328 if (is_contained(Mask, UndefMaskElem) && !MightCreatePoisonOrUB)
2329 NewI->dropPoisonGeneratingFlags();
2330 }
2331 return replaceInstUsesWith(Shuf, NewBO);
2332 }
2333
2334 /// Convert a narrowing shuffle of a bitcasted vector into a vector truncate.
2335 /// Example (little endian):
2336 /// shuf (bitcast <4 x i16> X to <8 x i8>), <0, 2, 4, 6> --> trunc X to <4 x i8>
foldTruncShuffle(ShuffleVectorInst & Shuf,bool IsBigEndian)2337 static Instruction *foldTruncShuffle(ShuffleVectorInst &Shuf,
2338 bool IsBigEndian) {
2339 // This must be a bitcasted shuffle of 1 vector integer operand.
2340 Type *DestType = Shuf.getType();
2341 Value *X;
2342 if (!match(Shuf.getOperand(0), m_BitCast(m_Value(X))) ||
2343 !match(Shuf.getOperand(1), m_Undef()) || !DestType->isIntOrIntVectorTy())
2344 return nullptr;
2345
2346 // The source type must have the same number of elements as the shuffle,
2347 // and the source element type must be larger than the shuffle element type.
2348 Type *SrcType = X->getType();
2349 if (!SrcType->isVectorTy() || !SrcType->isIntOrIntVectorTy() ||
2350 cast<FixedVectorType>(SrcType)->getNumElements() !=
2351 cast<FixedVectorType>(DestType)->getNumElements() ||
2352 SrcType->getScalarSizeInBits() % DestType->getScalarSizeInBits() != 0)
2353 return nullptr;
2354
2355 assert(Shuf.changesLength() && !Shuf.increasesLength() &&
2356 "Expected a shuffle that decreases length");
2357
2358 // Last, check that the mask chooses the correct low bits for each narrow
2359 // element in the result.
2360 uint64_t TruncRatio =
2361 SrcType->getScalarSizeInBits() / DestType->getScalarSizeInBits();
2362 ArrayRef<int> Mask = Shuf.getShuffleMask();
2363 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
2364 if (Mask[i] == UndefMaskElem)
2365 continue;
2366 uint64_t LSBIndex = IsBigEndian ? (i + 1) * TruncRatio - 1 : i * TruncRatio;
2367 assert(LSBIndex <= INT32_MAX && "Overflowed 32-bits");
2368 if (Mask[i] != (int)LSBIndex)
2369 return nullptr;
2370 }
2371
2372 return new TruncInst(X, DestType);
2373 }
2374
2375 /// Match a shuffle-select-shuffle pattern where the shuffles are widening and
2376 /// narrowing (concatenating with undef and extracting back to the original
2377 /// length). This allows replacing the wide select with a narrow select.
narrowVectorSelect(ShuffleVectorInst & Shuf,InstCombiner::BuilderTy & Builder)2378 static Instruction *narrowVectorSelect(ShuffleVectorInst &Shuf,
2379 InstCombiner::BuilderTy &Builder) {
2380 // This must be a narrowing identity shuffle. It extracts the 1st N elements
2381 // of the 1st vector operand of a shuffle.
2382 if (!match(Shuf.getOperand(1), m_Undef()) || !Shuf.isIdentityWithExtract())
2383 return nullptr;
2384
2385 // The vector being shuffled must be a vector select that we can eliminate.
2386 // TODO: The one-use requirement could be eased if X and/or Y are constants.
2387 Value *Cond, *X, *Y;
2388 if (!match(Shuf.getOperand(0),
2389 m_OneUse(m_Select(m_Value(Cond), m_Value(X), m_Value(Y)))))
2390 return nullptr;
2391
2392 // We need a narrow condition value. It must be extended with undef elements
2393 // and have the same number of elements as this shuffle.
2394 unsigned NarrowNumElts =
2395 cast<FixedVectorType>(Shuf.getType())->getNumElements();
2396 Value *NarrowCond;
2397 if (!match(Cond, m_OneUse(m_Shuffle(m_Value(NarrowCond), m_Undef()))) ||
2398 cast<FixedVectorType>(NarrowCond->getType())->getNumElements() !=
2399 NarrowNumElts ||
2400 !cast<ShuffleVectorInst>(Cond)->isIdentityWithPadding())
2401 return nullptr;
2402
2403 // shuf (sel (shuf NarrowCond, undef, WideMask), X, Y), undef, NarrowMask) -->
2404 // sel NarrowCond, (shuf X, undef, NarrowMask), (shuf Y, undef, NarrowMask)
2405 Value *NarrowX = Builder.CreateShuffleVector(X, Shuf.getShuffleMask());
2406 Value *NarrowY = Builder.CreateShuffleVector(Y, Shuf.getShuffleMask());
2407 return SelectInst::Create(NarrowCond, NarrowX, NarrowY);
2408 }
2409
2410 /// Canonicalize FP negate after shuffle.
foldFNegShuffle(ShuffleVectorInst & Shuf,InstCombiner::BuilderTy & Builder)2411 static Instruction *foldFNegShuffle(ShuffleVectorInst &Shuf,
2412 InstCombiner::BuilderTy &Builder) {
2413 Instruction *FNeg0;
2414 Value *X;
2415 if (!match(Shuf.getOperand(0), m_CombineAnd(m_Instruction(FNeg0),
2416 m_FNeg(m_Value(X)))))
2417 return nullptr;
2418
2419 // shuffle (fneg X), Mask --> fneg (shuffle X, Mask)
2420 if (FNeg0->hasOneUse() && match(Shuf.getOperand(1), m_Undef())) {
2421 Value *NewShuf = Builder.CreateShuffleVector(X, Shuf.getShuffleMask());
2422 return UnaryOperator::CreateFNegFMF(NewShuf, FNeg0);
2423 }
2424
2425 Instruction *FNeg1;
2426 Value *Y;
2427 if (!match(Shuf.getOperand(1), m_CombineAnd(m_Instruction(FNeg1),
2428 m_FNeg(m_Value(Y)))))
2429 return nullptr;
2430
2431 // shuffle (fneg X), (fneg Y), Mask --> fneg (shuffle X, Y, Mask)
2432 if (FNeg0->hasOneUse() || FNeg1->hasOneUse()) {
2433 Value *NewShuf = Builder.CreateShuffleVector(X, Y, Shuf.getShuffleMask());
2434 Instruction *NewFNeg = UnaryOperator::CreateFNeg(NewShuf);
2435 NewFNeg->copyIRFlags(FNeg0);
2436 NewFNeg->andIRFlags(FNeg1);
2437 return NewFNeg;
2438 }
2439
2440 return nullptr;
2441 }
2442
2443 /// Canonicalize casts after shuffle.
foldCastShuffle(ShuffleVectorInst & Shuf,InstCombiner::BuilderTy & Builder)2444 static Instruction *foldCastShuffle(ShuffleVectorInst &Shuf,
2445 InstCombiner::BuilderTy &Builder) {
2446 // Do we have 2 matching cast operands?
2447 auto *Cast0 = dyn_cast<CastInst>(Shuf.getOperand(0));
2448 auto *Cast1 = dyn_cast<CastInst>(Shuf.getOperand(1));
2449 if (!Cast0 || !Cast1 || Cast0->getOpcode() != Cast1->getOpcode() ||
2450 Cast0->getSrcTy() != Cast1->getSrcTy())
2451 return nullptr;
2452
2453 // TODO: Allow other opcodes? That would require easing the type restrictions
2454 // below here.
2455 CastInst::CastOps CastOpcode = Cast0->getOpcode();
2456 switch (CastOpcode) {
2457 case Instruction::FPToSI:
2458 case Instruction::FPToUI:
2459 case Instruction::SIToFP:
2460 case Instruction::UIToFP:
2461 break;
2462 default:
2463 return nullptr;
2464 }
2465
2466 VectorType *ShufTy = Shuf.getType();
2467 VectorType *ShufOpTy = cast<VectorType>(Shuf.getOperand(0)->getType());
2468 VectorType *CastSrcTy = cast<VectorType>(Cast0->getSrcTy());
2469
2470 // TODO: Allow length-increasing shuffles?
2471 if (ShufTy->getElementCount().getKnownMinValue() >
2472 ShufOpTy->getElementCount().getKnownMinValue())
2473 return nullptr;
2474
2475 // TODO: Allow element-size-decreasing casts (ex: fptosi float to i8)?
2476 assert(isa<FixedVectorType>(CastSrcTy) && isa<FixedVectorType>(ShufOpTy) &&
2477 "Expected fixed vector operands for casts and binary shuffle");
2478 if (CastSrcTy->getPrimitiveSizeInBits() > ShufOpTy->getPrimitiveSizeInBits())
2479 return nullptr;
2480
2481 // At least one of the operands must have only one use (the shuffle).
2482 if (!Cast0->hasOneUse() && !Cast1->hasOneUse())
2483 return nullptr;
2484
2485 // shuffle (cast X), (cast Y), Mask --> cast (shuffle X, Y, Mask)
2486 Value *X = Cast0->getOperand(0);
2487 Value *Y = Cast1->getOperand(0);
2488 Value *NewShuf = Builder.CreateShuffleVector(X, Y, Shuf.getShuffleMask());
2489 return CastInst::Create(CastOpcode, NewShuf, ShufTy);
2490 }
2491
2492 /// Try to fold an extract subvector operation.
foldIdentityExtractShuffle(ShuffleVectorInst & Shuf)2493 static Instruction *foldIdentityExtractShuffle(ShuffleVectorInst &Shuf) {
2494 Value *Op0 = Shuf.getOperand(0), *Op1 = Shuf.getOperand(1);
2495 if (!Shuf.isIdentityWithExtract() || !match(Op1, m_Undef()))
2496 return nullptr;
2497
2498 // Check if we are extracting all bits of an inserted scalar:
2499 // extract-subvec (bitcast (inselt ?, X, 0) --> bitcast X to subvec type
2500 Value *X;
2501 if (match(Op0, m_BitCast(m_InsertElt(m_Value(), m_Value(X), m_Zero()))) &&
2502 X->getType()->getPrimitiveSizeInBits() ==
2503 Shuf.getType()->getPrimitiveSizeInBits())
2504 return new BitCastInst(X, Shuf.getType());
2505
2506 // Try to combine 2 shuffles into 1 shuffle by concatenating a shuffle mask.
2507 Value *Y;
2508 ArrayRef<int> Mask;
2509 if (!match(Op0, m_Shuffle(m_Value(X), m_Value(Y), m_Mask(Mask))))
2510 return nullptr;
2511
2512 // Be conservative with shuffle transforms. If we can't kill the 1st shuffle,
2513 // then combining may result in worse codegen.
2514 if (!Op0->hasOneUse())
2515 return nullptr;
2516
2517 // We are extracting a subvector from a shuffle. Remove excess elements from
2518 // the 1st shuffle mask to eliminate the extract.
2519 //
2520 // This transform is conservatively limited to identity extracts because we do
2521 // not allow arbitrary shuffle mask creation as a target-independent transform
2522 // (because we can't guarantee that will lower efficiently).
2523 //
2524 // If the extracting shuffle has an undef mask element, it transfers to the
2525 // new shuffle mask. Otherwise, copy the original mask element. Example:
2526 // shuf (shuf X, Y, <C0, C1, C2, undef, C4>), undef, <0, undef, 2, 3> -->
2527 // shuf X, Y, <C0, undef, C2, undef>
2528 unsigned NumElts = cast<FixedVectorType>(Shuf.getType())->getNumElements();
2529 SmallVector<int, 16> NewMask(NumElts);
2530 assert(NumElts < Mask.size() &&
2531 "Identity with extract must have less elements than its inputs");
2532
2533 for (unsigned i = 0; i != NumElts; ++i) {
2534 int ExtractMaskElt = Shuf.getMaskValue(i);
2535 int MaskElt = Mask[i];
2536 NewMask[i] = ExtractMaskElt == UndefMaskElem ? ExtractMaskElt : MaskElt;
2537 }
2538 return new ShuffleVectorInst(X, Y, NewMask);
2539 }
2540
2541 /// Try to replace a shuffle with an insertelement or try to replace a shuffle
2542 /// operand with the operand of an insertelement.
foldShuffleWithInsert(ShuffleVectorInst & Shuf,InstCombinerImpl & IC)2543 static Instruction *foldShuffleWithInsert(ShuffleVectorInst &Shuf,
2544 InstCombinerImpl &IC) {
2545 Value *V0 = Shuf.getOperand(0), *V1 = Shuf.getOperand(1);
2546 SmallVector<int, 16> Mask;
2547 Shuf.getShuffleMask(Mask);
2548
2549 int NumElts = Mask.size();
2550 int InpNumElts = cast<FixedVectorType>(V0->getType())->getNumElements();
2551
2552 // This is a specialization of a fold in SimplifyDemandedVectorElts. We may
2553 // not be able to handle it there if the insertelement has >1 use.
2554 // If the shuffle has an insertelement operand but does not choose the
2555 // inserted scalar element from that value, then we can replace that shuffle
2556 // operand with the source vector of the insertelement.
2557 Value *X;
2558 uint64_t IdxC;
2559 if (match(V0, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
2560 // shuf (inselt X, ?, IdxC), ?, Mask --> shuf X, ?, Mask
2561 if (!is_contained(Mask, (int)IdxC))
2562 return IC.replaceOperand(Shuf, 0, X);
2563 }
2564 if (match(V1, m_InsertElt(m_Value(X), m_Value(), m_ConstantInt(IdxC)))) {
2565 // Offset the index constant by the vector width because we are checking for
2566 // accesses to the 2nd vector input of the shuffle.
2567 IdxC += InpNumElts;
2568 // shuf ?, (inselt X, ?, IdxC), Mask --> shuf ?, X, Mask
2569 if (!is_contained(Mask, (int)IdxC))
2570 return IC.replaceOperand(Shuf, 1, X);
2571 }
2572 // For the rest of the transform, the shuffle must not change vector sizes.
2573 // TODO: This restriction could be removed if the insert has only one use
2574 // (because the transform would require a new length-changing shuffle).
2575 if (NumElts != InpNumElts)
2576 return nullptr;
2577
2578 // shuffle (insert ?, Scalar, IndexC), V1, Mask --> insert V1, Scalar, IndexC'
2579 auto isShufflingScalarIntoOp1 = [&](Value *&Scalar, ConstantInt *&IndexC) {
2580 // We need an insertelement with a constant index.
2581 if (!match(V0, m_InsertElt(m_Value(), m_Value(Scalar),
2582 m_ConstantInt(IndexC))))
2583 return false;
2584
2585 // Test the shuffle mask to see if it splices the inserted scalar into the
2586 // operand 1 vector of the shuffle.
2587 int NewInsIndex = -1;
2588 for (int i = 0; i != NumElts; ++i) {
2589 // Ignore undef mask elements.
2590 if (Mask[i] == -1)
2591 continue;
2592
2593 // The shuffle takes elements of operand 1 without lane changes.
2594 if (Mask[i] == NumElts + i)
2595 continue;
2596
2597 // The shuffle must choose the inserted scalar exactly once.
2598 if (NewInsIndex != -1 || Mask[i] != IndexC->getSExtValue())
2599 return false;
2600
2601 // The shuffle is placing the inserted scalar into element i.
2602 NewInsIndex = i;
2603 }
2604
2605 assert(NewInsIndex != -1 && "Did not fold shuffle with unused operand?");
2606
2607 // Index is updated to the potentially translated insertion lane.
2608 IndexC = ConstantInt::get(IndexC->getType(), NewInsIndex);
2609 return true;
2610 };
2611
2612 // If the shuffle is unnecessary, insert the scalar operand directly into
2613 // operand 1 of the shuffle. Example:
2614 // shuffle (insert ?, S, 1), V1, <1, 5, 6, 7> --> insert V1, S, 0
2615 Value *Scalar;
2616 ConstantInt *IndexC;
2617 if (isShufflingScalarIntoOp1(Scalar, IndexC))
2618 return InsertElementInst::Create(V1, Scalar, IndexC);
2619
2620 // Try again after commuting shuffle. Example:
2621 // shuffle V0, (insert ?, S, 0), <0, 1, 2, 4> -->
2622 // shuffle (insert ?, S, 0), V0, <4, 5, 6, 0> --> insert V0, S, 3
2623 std::swap(V0, V1);
2624 ShuffleVectorInst::commuteShuffleMask(Mask, NumElts);
2625 if (isShufflingScalarIntoOp1(Scalar, IndexC))
2626 return InsertElementInst::Create(V1, Scalar, IndexC);
2627
2628 return nullptr;
2629 }
2630
foldIdentityPaddedShuffles(ShuffleVectorInst & Shuf)2631 static Instruction *foldIdentityPaddedShuffles(ShuffleVectorInst &Shuf) {
2632 // Match the operands as identity with padding (also known as concatenation
2633 // with undef) shuffles of the same source type. The backend is expected to
2634 // recreate these concatenations from a shuffle of narrow operands.
2635 auto *Shuffle0 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(0));
2636 auto *Shuffle1 = dyn_cast<ShuffleVectorInst>(Shuf.getOperand(1));
2637 if (!Shuffle0 || !Shuffle0->isIdentityWithPadding() ||
2638 !Shuffle1 || !Shuffle1->isIdentityWithPadding())
2639 return nullptr;
2640
2641 // We limit this transform to power-of-2 types because we expect that the
2642 // backend can convert the simplified IR patterns to identical nodes as the
2643 // original IR.
2644 // TODO: If we can verify the same behavior for arbitrary types, the
2645 // power-of-2 checks can be removed.
2646 Value *X = Shuffle0->getOperand(0);
2647 Value *Y = Shuffle1->getOperand(0);
2648 if (X->getType() != Y->getType() ||
2649 !isPowerOf2_32(cast<FixedVectorType>(Shuf.getType())->getNumElements()) ||
2650 !isPowerOf2_32(
2651 cast<FixedVectorType>(Shuffle0->getType())->getNumElements()) ||
2652 !isPowerOf2_32(cast<FixedVectorType>(X->getType())->getNumElements()) ||
2653 match(X, m_Undef()) || match(Y, m_Undef()))
2654 return nullptr;
2655 assert(match(Shuffle0->getOperand(1), m_Undef()) &&
2656 match(Shuffle1->getOperand(1), m_Undef()) &&
2657 "Unexpected operand for identity shuffle");
2658
2659 // This is a shuffle of 2 widening shuffles. We can shuffle the narrow source
2660 // operands directly by adjusting the shuffle mask to account for the narrower
2661 // types:
2662 // shuf (widen X), (widen Y), Mask --> shuf X, Y, Mask'
2663 int NarrowElts = cast<FixedVectorType>(X->getType())->getNumElements();
2664 int WideElts = cast<FixedVectorType>(Shuffle0->getType())->getNumElements();
2665 assert(WideElts > NarrowElts && "Unexpected types for identity with padding");
2666
2667 ArrayRef<int> Mask = Shuf.getShuffleMask();
2668 SmallVector<int, 16> NewMask(Mask.size(), -1);
2669 for (int i = 0, e = Mask.size(); i != e; ++i) {
2670 if (Mask[i] == -1)
2671 continue;
2672
2673 // If this shuffle is choosing an undef element from 1 of the sources, that
2674 // element is undef.
2675 if (Mask[i] < WideElts) {
2676 if (Shuffle0->getMaskValue(Mask[i]) == -1)
2677 continue;
2678 } else {
2679 if (Shuffle1->getMaskValue(Mask[i] - WideElts) == -1)
2680 continue;
2681 }
2682
2683 // If this shuffle is choosing from the 1st narrow op, the mask element is
2684 // the same. If this shuffle is choosing from the 2nd narrow op, the mask
2685 // element is offset down to adjust for the narrow vector widths.
2686 if (Mask[i] < WideElts) {
2687 assert(Mask[i] < NarrowElts && "Unexpected shuffle mask");
2688 NewMask[i] = Mask[i];
2689 } else {
2690 assert(Mask[i] < (WideElts + NarrowElts) && "Unexpected shuffle mask");
2691 NewMask[i] = Mask[i] - (WideElts - NarrowElts);
2692 }
2693 }
2694 return new ShuffleVectorInst(X, Y, NewMask);
2695 }
2696
2697 // Splatting the first element of the result of a BinOp, where any of the
2698 // BinOp's operands are the result of a first element splat can be simplified to
2699 // splatting the first element of the result of the BinOp
simplifyBinOpSplats(ShuffleVectorInst & SVI)2700 Instruction *InstCombinerImpl::simplifyBinOpSplats(ShuffleVectorInst &SVI) {
2701 if (!match(SVI.getOperand(1), m_Undef()) ||
2702 !match(SVI.getShuffleMask(), m_ZeroMask()))
2703 return nullptr;
2704
2705 Value *Op0 = SVI.getOperand(0);
2706 Value *X, *Y;
2707 if (!match(Op0, m_BinOp(m_Shuffle(m_Value(X), m_Undef(), m_ZeroMask()),
2708 m_Value(Y))) &&
2709 !match(Op0, m_BinOp(m_Value(X),
2710 m_Shuffle(m_Value(Y), m_Undef(), m_ZeroMask()))))
2711 return nullptr;
2712 if (X->getType() != Y->getType())
2713 return nullptr;
2714
2715 auto *BinOp = cast<BinaryOperator>(Op0);
2716 if (!isSafeToSpeculativelyExecute(BinOp))
2717 return nullptr;
2718
2719 Value *NewBO = Builder.CreateBinOp(BinOp->getOpcode(), X, Y);
2720 if (auto NewBOI = dyn_cast<Instruction>(NewBO))
2721 NewBOI->copyIRFlags(BinOp);
2722
2723 return new ShuffleVectorInst(NewBO, SVI.getShuffleMask());
2724 }
2725
visitShuffleVectorInst(ShuffleVectorInst & SVI)2726 Instruction *InstCombinerImpl::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
2727 Value *LHS = SVI.getOperand(0);
2728 Value *RHS = SVI.getOperand(1);
2729 SimplifyQuery ShufQuery = SQ.getWithInstruction(&SVI);
2730 if (auto *V = simplifyShuffleVectorInst(LHS, RHS, SVI.getShuffleMask(),
2731 SVI.getType(), ShufQuery))
2732 return replaceInstUsesWith(SVI, V);
2733
2734 if (Instruction *I = simplifyBinOpSplats(SVI))
2735 return I;
2736
2737 if (isa<ScalableVectorType>(LHS->getType()))
2738 return nullptr;
2739
2740 unsigned VWidth = cast<FixedVectorType>(SVI.getType())->getNumElements();
2741 unsigned LHSWidth = cast<FixedVectorType>(LHS->getType())->getNumElements();
2742
2743 // shuffle (bitcast X), (bitcast Y), Mask --> bitcast (shuffle X, Y, Mask)
2744 //
2745 // if X and Y are of the same (vector) type, and the element size is not
2746 // changed by the bitcasts, we can distribute the bitcasts through the
2747 // shuffle, hopefully reducing the number of instructions. We make sure that
2748 // at least one bitcast only has one use, so we don't *increase* the number of
2749 // instructions here.
2750 Value *X, *Y;
2751 if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_BitCast(m_Value(Y))) &&
2752 X->getType()->isVectorTy() && X->getType() == Y->getType() &&
2753 X->getType()->getScalarSizeInBits() ==
2754 SVI.getType()->getScalarSizeInBits() &&
2755 (LHS->hasOneUse() || RHS->hasOneUse())) {
2756 Value *V = Builder.CreateShuffleVector(X, Y, SVI.getShuffleMask(),
2757 SVI.getName() + ".uncasted");
2758 return new BitCastInst(V, SVI.getType());
2759 }
2760
2761 ArrayRef<int> Mask = SVI.getShuffleMask();
2762 Type *Int32Ty = Type::getInt32Ty(SVI.getContext());
2763
2764 // Peek through a bitcasted shuffle operand by scaling the mask. If the
2765 // simulated shuffle can simplify, then this shuffle is unnecessary:
2766 // shuf (bitcast X), undef, Mask --> bitcast X'
2767 // TODO: This could be extended to allow length-changing shuffles.
2768 // The transform might also be obsoleted if we allowed canonicalization
2769 // of bitcasted shuffles.
2770 if (match(LHS, m_BitCast(m_Value(X))) && match(RHS, m_Undef()) &&
2771 X->getType()->isVectorTy() && VWidth == LHSWidth) {
2772 // Try to create a scaled mask constant.
2773 auto *XType = cast<FixedVectorType>(X->getType());
2774 unsigned XNumElts = XType->getNumElements();
2775 SmallVector<int, 16> ScaledMask;
2776 if (XNumElts >= VWidth) {
2777 assert(XNumElts % VWidth == 0 && "Unexpected vector bitcast");
2778 narrowShuffleMaskElts(XNumElts / VWidth, Mask, ScaledMask);
2779 } else {
2780 assert(VWidth % XNumElts == 0 && "Unexpected vector bitcast");
2781 if (!widenShuffleMaskElts(VWidth / XNumElts, Mask, ScaledMask))
2782 ScaledMask.clear();
2783 }
2784 if (!ScaledMask.empty()) {
2785 // If the shuffled source vector simplifies, cast that value to this
2786 // shuffle's type.
2787 if (auto *V = simplifyShuffleVectorInst(X, UndefValue::get(XType),
2788 ScaledMask, XType, ShufQuery))
2789 return BitCastInst::Create(Instruction::BitCast, V, SVI.getType());
2790 }
2791 }
2792
2793 // shuffle x, x, mask --> shuffle x, undef, mask'
2794 if (LHS == RHS) {
2795 assert(!match(RHS, m_Undef()) &&
2796 "Shuffle with 2 undef ops not simplified?");
2797 return new ShuffleVectorInst(LHS, createUnaryMask(Mask, LHSWidth));
2798 }
2799
2800 // shuffle undef, x, mask --> shuffle x, undef, mask'
2801 if (match(LHS, m_Undef())) {
2802 SVI.commute();
2803 return &SVI;
2804 }
2805
2806 if (Instruction *I = canonicalizeInsertSplat(SVI, Builder))
2807 return I;
2808
2809 if (Instruction *I = foldSelectShuffle(SVI))
2810 return I;
2811
2812 if (Instruction *I = foldTruncShuffle(SVI, DL.isBigEndian()))
2813 return I;
2814
2815 if (Instruction *I = narrowVectorSelect(SVI, Builder))
2816 return I;
2817
2818 if (Instruction *I = foldFNegShuffle(SVI, Builder))
2819 return I;
2820
2821 if (Instruction *I = foldCastShuffle(SVI, Builder))
2822 return I;
2823
2824 APInt UndefElts(VWidth, 0);
2825 APInt AllOnesEltMask(APInt::getAllOnes(VWidth));
2826 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
2827 if (V != &SVI)
2828 return replaceInstUsesWith(SVI, V);
2829 return &SVI;
2830 }
2831
2832 if (Instruction *I = foldIdentityExtractShuffle(SVI))
2833 return I;
2834
2835 // These transforms have the potential to lose undef knowledge, so they are
2836 // intentionally placed after SimplifyDemandedVectorElts().
2837 if (Instruction *I = foldShuffleWithInsert(SVI, *this))
2838 return I;
2839 if (Instruction *I = foldIdentityPaddedShuffles(SVI))
2840 return I;
2841
2842 if (match(RHS, m_Undef()) && canEvaluateShuffled(LHS, Mask)) {
2843 Value *V = evaluateInDifferentElementOrder(LHS, Mask);
2844 return replaceInstUsesWith(SVI, V);
2845 }
2846
2847 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to
2848 // a non-vector type. We can instead bitcast the original vector followed by
2849 // an extract of the desired element:
2850 //
2851 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef,
2852 // <4 x i32> <i32 0, i32 1, i32 2, i32 3>
2853 // %1 = bitcast <4 x i8> %sroa to i32
2854 // Becomes:
2855 // %bc = bitcast <16 x i8> %in to <4 x i32>
2856 // %ext = extractelement <4 x i32> %bc, i32 0
2857 //
2858 // If the shuffle is extracting a contiguous range of values from the input
2859 // vector then each use which is a bitcast of the extracted size can be
2860 // replaced. This will work if the vector types are compatible, and the begin
2861 // index is aligned to a value in the casted vector type. If the begin index
2862 // isn't aligned then we can shuffle the original vector (keeping the same
2863 // vector type) before extracting.
2864 //
2865 // This code will bail out if the target type is fundamentally incompatible
2866 // with vectors of the source type.
2867 //
2868 // Example of <16 x i8>, target type i32:
2869 // Index range [4,8): v-----------v Will work.
2870 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
2871 // <16 x i8>: | | | | | | | | | | | | | | | | |
2872 // <4 x i32>: | | | | |
2873 // +-----------+-----------+-----------+-----------+
2874 // Index range [6,10): ^-----------^ Needs an extra shuffle.
2875 // Target type i40: ^--------------^ Won't work, bail.
2876 bool MadeChange = false;
2877 if (isShuffleExtractingFromLHS(SVI, Mask)) {
2878 Value *V = LHS;
2879 unsigned MaskElems = Mask.size();
2880 auto *SrcTy = cast<FixedVectorType>(V->getType());
2881 unsigned VecBitWidth = SrcTy->getPrimitiveSizeInBits().getFixedValue();
2882 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType());
2883 assert(SrcElemBitWidth && "vector elements must have a bitwidth");
2884 unsigned SrcNumElems = SrcTy->getNumElements();
2885 SmallVector<BitCastInst *, 8> BCs;
2886 DenseMap<Type *, Value *> NewBCs;
2887 for (User *U : SVI.users())
2888 if (BitCastInst *BC = dyn_cast<BitCastInst>(U))
2889 if (!BC->use_empty())
2890 // Only visit bitcasts that weren't previously handled.
2891 BCs.push_back(BC);
2892 for (BitCastInst *BC : BCs) {
2893 unsigned BegIdx = Mask.front();
2894 Type *TgtTy = BC->getDestTy();
2895 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy);
2896 if (!TgtElemBitWidth)
2897 continue;
2898 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth;
2899 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth;
2900 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth);
2901 if (!VecBitWidthsEqual)
2902 continue;
2903 if (!VectorType::isValidElementType(TgtTy))
2904 continue;
2905 auto *CastSrcTy = FixedVectorType::get(TgtTy, TgtNumElems);
2906 if (!BegIsAligned) {
2907 // Shuffle the input so [0,NumElements) contains the output, and
2908 // [NumElems,SrcNumElems) is undef.
2909 SmallVector<int, 16> ShuffleMask(SrcNumElems, -1);
2910 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I)
2911 ShuffleMask[I] = Idx;
2912 V = Builder.CreateShuffleVector(V, ShuffleMask,
2913 SVI.getName() + ".extract");
2914 BegIdx = 0;
2915 }
2916 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth;
2917 assert(SrcElemsPerTgtElem);
2918 BegIdx /= SrcElemsPerTgtElem;
2919 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end();
2920 auto *NewBC =
2921 BCAlreadyExists
2922 ? NewBCs[CastSrcTy]
2923 : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc");
2924 if (!BCAlreadyExists)
2925 NewBCs[CastSrcTy] = NewBC;
2926 auto *Ext = Builder.CreateExtractElement(
2927 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract");
2928 // The shufflevector isn't being replaced: the bitcast that used it
2929 // is. InstCombine will visit the newly-created instructions.
2930 replaceInstUsesWith(*BC, Ext);
2931 MadeChange = true;
2932 }
2933 }
2934
2935 // If the LHS is a shufflevector itself, see if we can combine it with this
2936 // one without producing an unusual shuffle.
2937 // Cases that might be simplified:
2938 // 1.
2939 // x1=shuffle(v1,v2,mask1)
2940 // x=shuffle(x1,undef,mask)
2941 // ==>
2942 // x=shuffle(v1,undef,newMask)
2943 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1
2944 // 2.
2945 // x1=shuffle(v1,undef,mask1)
2946 // x=shuffle(x1,x2,mask)
2947 // where v1.size() == mask1.size()
2948 // ==>
2949 // x=shuffle(v1,x2,newMask)
2950 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i]
2951 // 3.
2952 // x2=shuffle(v2,undef,mask2)
2953 // x=shuffle(x1,x2,mask)
2954 // where v2.size() == mask2.size()
2955 // ==>
2956 // x=shuffle(x1,v2,newMask)
2957 // newMask[i] = (mask[i] < x1.size())
2958 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size()
2959 // 4.
2960 // x1=shuffle(v1,undef,mask1)
2961 // x2=shuffle(v2,undef,mask2)
2962 // x=shuffle(x1,x2,mask)
2963 // where v1.size() == v2.size()
2964 // ==>
2965 // x=shuffle(v1,v2,newMask)
2966 // newMask[i] = (mask[i] < x1.size())
2967 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size()
2968 //
2969 // Here we are really conservative:
2970 // we are absolutely afraid of producing a shuffle mask not in the input
2971 // program, because the code gen may not be smart enough to turn a merged
2972 // shuffle into two specific shuffles: it may produce worse code. As such,
2973 // we only merge two shuffles if the result is either a splat or one of the
2974 // input shuffle masks. In this case, merging the shuffles just removes
2975 // one instruction, which we know is safe. This is good for things like
2976 // turning: (splat(splat)) -> splat, or
2977 // merge(V[0..n], V[n+1..2n]) -> V[0..2n]
2978 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS);
2979 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS);
2980 if (LHSShuffle)
2981 if (!match(LHSShuffle->getOperand(1), m_Undef()) && !match(RHS, m_Undef()))
2982 LHSShuffle = nullptr;
2983 if (RHSShuffle)
2984 if (!match(RHSShuffle->getOperand(1), m_Undef()))
2985 RHSShuffle = nullptr;
2986 if (!LHSShuffle && !RHSShuffle)
2987 return MadeChange ? &SVI : nullptr;
2988
2989 Value* LHSOp0 = nullptr;
2990 Value* LHSOp1 = nullptr;
2991 Value* RHSOp0 = nullptr;
2992 unsigned LHSOp0Width = 0;
2993 unsigned RHSOp0Width = 0;
2994 if (LHSShuffle) {
2995 LHSOp0 = LHSShuffle->getOperand(0);
2996 LHSOp1 = LHSShuffle->getOperand(1);
2997 LHSOp0Width = cast<FixedVectorType>(LHSOp0->getType())->getNumElements();
2998 }
2999 if (RHSShuffle) {
3000 RHSOp0 = RHSShuffle->getOperand(0);
3001 RHSOp0Width = cast<FixedVectorType>(RHSOp0->getType())->getNumElements();
3002 }
3003 Value* newLHS = LHS;
3004 Value* newRHS = RHS;
3005 if (LHSShuffle) {
3006 // case 1
3007 if (match(RHS, m_Undef())) {
3008 newLHS = LHSOp0;
3009 newRHS = LHSOp1;
3010 }
3011 // case 2 or 4
3012 else if (LHSOp0Width == LHSWidth) {
3013 newLHS = LHSOp0;
3014 }
3015 }
3016 // case 3 or 4
3017 if (RHSShuffle && RHSOp0Width == LHSWidth) {
3018 newRHS = RHSOp0;
3019 }
3020 // case 4
3021 if (LHSOp0 == RHSOp0) {
3022 newLHS = LHSOp0;
3023 newRHS = nullptr;
3024 }
3025
3026 if (newLHS == LHS && newRHS == RHS)
3027 return MadeChange ? &SVI : nullptr;
3028
3029 ArrayRef<int> LHSMask;
3030 ArrayRef<int> RHSMask;
3031 if (newLHS != LHS)
3032 LHSMask = LHSShuffle->getShuffleMask();
3033 if (RHSShuffle && newRHS != RHS)
3034 RHSMask = RHSShuffle->getShuffleMask();
3035
3036 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth;
3037 SmallVector<int, 16> newMask;
3038 bool isSplat = true;
3039 int SplatElt = -1;
3040 // Create a new mask for the new ShuffleVectorInst so that the new
3041 // ShuffleVectorInst is equivalent to the original one.
3042 for (unsigned i = 0; i < VWidth; ++i) {
3043 int eltMask;
3044 if (Mask[i] < 0) {
3045 // This element is an undef value.
3046 eltMask = -1;
3047 } else if (Mask[i] < (int)LHSWidth) {
3048 // This element is from left hand side vector operand.
3049 //
3050 // If LHS is going to be replaced (case 1, 2, or 4), calculate the
3051 // new mask value for the element.
3052 if (newLHS != LHS) {
3053 eltMask = LHSMask[Mask[i]];
3054 // If the value selected is an undef value, explicitly specify it
3055 // with a -1 mask value.
3056 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1))
3057 eltMask = -1;
3058 } else
3059 eltMask = Mask[i];
3060 } else {
3061 // This element is from right hand side vector operand
3062 //
3063 // If the value selected is an undef value, explicitly specify it
3064 // with a -1 mask value. (case 1)
3065 if (match(RHS, m_Undef()))
3066 eltMask = -1;
3067 // If RHS is going to be replaced (case 3 or 4), calculate the
3068 // new mask value for the element.
3069 else if (newRHS != RHS) {
3070 eltMask = RHSMask[Mask[i]-LHSWidth];
3071 // If the value selected is an undef value, explicitly specify it
3072 // with a -1 mask value.
3073 if (eltMask >= (int)RHSOp0Width) {
3074 assert(match(RHSShuffle->getOperand(1), m_Undef()) &&
3075 "should have been check above");
3076 eltMask = -1;
3077 }
3078 } else
3079 eltMask = Mask[i]-LHSWidth;
3080
3081 // If LHS's width is changed, shift the mask value accordingly.
3082 // If newRHS == nullptr, i.e. LHSOp0 == RHSOp0, we want to remap any
3083 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask.
3084 // If newRHS == newLHS, we want to remap any references from newRHS to
3085 // newLHS so that we can properly identify splats that may occur due to
3086 // obfuscation across the two vectors.
3087 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS)
3088 eltMask += newLHSWidth;
3089 }
3090
3091 // Check if this could still be a splat.
3092 if (eltMask >= 0) {
3093 if (SplatElt >= 0 && SplatElt != eltMask)
3094 isSplat = false;
3095 SplatElt = eltMask;
3096 }
3097
3098 newMask.push_back(eltMask);
3099 }
3100
3101 // If the result mask is equal to one of the original shuffle masks,
3102 // or is a splat, do the replacement.
3103 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) {
3104 if (!newRHS)
3105 newRHS = UndefValue::get(newLHS->getType());
3106 return new ShuffleVectorInst(newLHS, newRHS, newMask);
3107 }
3108
3109 return MadeChange ? &SVI : nullptr;
3110 }
3111