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