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