1 //===- InstCombineVectorOps.cpp -------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements instcombine for ExtractElement, InsertElement and 11 // ShuffleVector. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "InstCombineInternal.h" 16 #include "llvm/ADT/DenseMap.h" 17 #include "llvm/Analysis/InstructionSimplify.h" 18 #include "llvm/Analysis/VectorUtils.h" 19 #include "llvm/IR/PatternMatch.h" 20 using namespace llvm; 21 using namespace PatternMatch; 22 23 #define DEBUG_TYPE "instcombine" 24 25 /// Return true if the value is cheaper to scalarize than it is to leave as a 26 /// vector operation. isConstant indicates whether we're extracting one known 27 /// element. If false we're extracting a variable index. 28 static bool cheapToScalarize(Value *V, bool isConstant) { 29 if (Constant *C = dyn_cast<Constant>(V)) { 30 if (isConstant) return true; 31 32 // If all elts are the same, we can extract it and use any of the values. 33 if (Constant *Op0 = C->getAggregateElement(0U)) { 34 for (unsigned i = 1, e = V->getType()->getVectorNumElements(); i != e; 35 ++i) 36 if (C->getAggregateElement(i) != Op0) 37 return false; 38 return true; 39 } 40 } 41 Instruction *I = dyn_cast<Instruction>(V); 42 if (!I) return false; 43 44 // Insert element gets simplified to the inserted element or is deleted if 45 // this is constant idx extract element and its a constant idx insertelt. 46 if (I->getOpcode() == Instruction::InsertElement && isConstant && 47 isa<ConstantInt>(I->getOperand(2))) 48 return true; 49 if (I->getOpcode() == Instruction::Load && I->hasOneUse()) 50 return true; 51 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) 52 if (BO->hasOneUse() && 53 (cheapToScalarize(BO->getOperand(0), isConstant) || 54 cheapToScalarize(BO->getOperand(1), isConstant))) 55 return true; 56 if (CmpInst *CI = dyn_cast<CmpInst>(I)) 57 if (CI->hasOneUse() && 58 (cheapToScalarize(CI->getOperand(0), isConstant) || 59 cheapToScalarize(CI->getOperand(1), isConstant))) 60 return true; 61 62 return false; 63 } 64 65 // If we have a PHI node with a vector type that is only used to feed 66 // itself and be an operand of extractelement at a constant location, 67 // try to replace the PHI of the vector type with a PHI of a scalar type. 68 Instruction *InstCombiner::scalarizePHI(ExtractElementInst &EI, PHINode *PN) { 69 SmallVector<Instruction *, 2> Extracts; 70 // The users we want the PHI to have are: 71 // 1) The EI ExtractElement (we already know this) 72 // 2) Possibly more ExtractElements with the same index. 73 // 3) Another operand, which will feed back into the PHI. 74 Instruction *PHIUser = nullptr; 75 for (auto U : PN->users()) { 76 if (ExtractElementInst *EU = dyn_cast<ExtractElementInst>(U)) { 77 if (EI.getIndexOperand() == EU->getIndexOperand()) 78 Extracts.push_back(EU); 79 else 80 return nullptr; 81 } else if (!PHIUser) { 82 PHIUser = cast<Instruction>(U); 83 } else { 84 return nullptr; 85 } 86 } 87 88 if (!PHIUser) 89 return nullptr; 90 91 // Verify that this PHI user has one use, which is the PHI itself, 92 // and that it is a binary operation which is cheap to scalarize. 93 // otherwise return NULL. 94 if (!PHIUser->hasOneUse() || !(PHIUser->user_back() == PN) || 95 !(isa<BinaryOperator>(PHIUser)) || !cheapToScalarize(PHIUser, true)) 96 return nullptr; 97 98 // Create a scalar PHI node that will replace the vector PHI node 99 // just before the current PHI node. 100 PHINode *scalarPHI = cast<PHINode>(InsertNewInstWith( 101 PHINode::Create(EI.getType(), PN->getNumIncomingValues(), ""), *PN)); 102 // Scalarize each PHI operand. 103 for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) { 104 Value *PHIInVal = PN->getIncomingValue(i); 105 BasicBlock *inBB = PN->getIncomingBlock(i); 106 Value *Elt = EI.getIndexOperand(); 107 // If the operand is the PHI induction variable: 108 if (PHIInVal == PHIUser) { 109 // Scalarize the binary operation. Its first operand is the 110 // scalar PHI, and the second operand is extracted from the other 111 // vector operand. 112 BinaryOperator *B0 = cast<BinaryOperator>(PHIUser); 113 unsigned opId = (B0->getOperand(0) == PN) ? 1 : 0; 114 Value *Op = InsertNewInstWith( 115 ExtractElementInst::Create(B0->getOperand(opId), Elt, 116 B0->getOperand(opId)->getName() + ".Elt"), 117 *B0); 118 Value *newPHIUser = InsertNewInstWith( 119 BinaryOperator::CreateWithCopiedFlags(B0->getOpcode(), 120 scalarPHI, Op, B0), *B0); 121 scalarPHI->addIncoming(newPHIUser, inBB); 122 } else { 123 // Scalarize PHI input: 124 Instruction *newEI = ExtractElementInst::Create(PHIInVal, Elt, ""); 125 // Insert the new instruction into the predecessor basic block. 126 Instruction *pos = dyn_cast<Instruction>(PHIInVal); 127 BasicBlock::iterator InsertPos; 128 if (pos && !isa<PHINode>(pos)) { 129 InsertPos = ++pos->getIterator(); 130 } else { 131 InsertPos = inBB->getFirstInsertionPt(); 132 } 133 134 InsertNewInstWith(newEI, *InsertPos); 135 136 scalarPHI->addIncoming(newEI, inBB); 137 } 138 } 139 140 for (auto E : Extracts) 141 replaceInstUsesWith(*E, scalarPHI); 142 143 return &EI; 144 } 145 146 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) { 147 if (Value *V = SimplifyExtractElementInst(EI.getVectorOperand(), 148 EI.getIndexOperand(), 149 SQ.getWithInstruction(&EI))) 150 return replaceInstUsesWith(EI, V); 151 152 // If vector val is constant with all elements the same, replace EI with 153 // that element. We handle a known element # below. 154 if (Constant *C = dyn_cast<Constant>(EI.getOperand(0))) 155 if (cheapToScalarize(C, false)) 156 return replaceInstUsesWith(EI, C->getAggregateElement(0U)); 157 158 // If extracting a specified index from the vector, see if we can recursively 159 // find a previously computed scalar that was inserted into the vector. 160 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) { 161 unsigned IndexVal = IdxC->getZExtValue(); 162 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements(); 163 164 // InstSimplify handles cases where the index is invalid. 165 assert(IndexVal < VectorWidth); 166 167 // This instruction only demands the single element from the input vector. 168 // If the input vector has a single use, simplify it based on this use 169 // property. 170 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) { 171 APInt UndefElts(VectorWidth, 0); 172 APInt DemandedMask(VectorWidth, 0); 173 DemandedMask.setBit(IndexVal); 174 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0), DemandedMask, 175 UndefElts)) { 176 EI.setOperand(0, V); 177 return &EI; 178 } 179 } 180 181 // If this extractelement is directly using a bitcast from a vector of 182 // the same number of elements, see if we can find the source element from 183 // it. In this case, we will end up needing to bitcast the scalars. 184 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) { 185 if (VectorType *VT = dyn_cast<VectorType>(BCI->getOperand(0)->getType())) 186 if (VT->getNumElements() == VectorWidth) 187 if (Value *Elt = findScalarElement(BCI->getOperand(0), IndexVal)) 188 return new BitCastInst(Elt, EI.getType()); 189 } 190 191 // If there's a vector PHI feeding a scalar use through this extractelement 192 // instruction, try to scalarize the PHI. 193 if (PHINode *PN = dyn_cast<PHINode>(EI.getOperand(0))) { 194 Instruction *scalarPHI = scalarizePHI(EI, PN); 195 if (scalarPHI) 196 return scalarPHI; 197 } 198 } 199 200 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) { 201 // Push extractelement into predecessor operation if legal and 202 // profitable to do so. 203 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) { 204 if (I->hasOneUse() && 205 cheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) { 206 Value *newEI0 = 207 Builder.CreateExtractElement(BO->getOperand(0), EI.getOperand(1), 208 EI.getName()+".lhs"); 209 Value *newEI1 = 210 Builder.CreateExtractElement(BO->getOperand(1), EI.getOperand(1), 211 EI.getName()+".rhs"); 212 return BinaryOperator::CreateWithCopiedFlags(BO->getOpcode(), 213 newEI0, newEI1, BO); 214 } 215 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) { 216 // Extracting the inserted element? 217 if (IE->getOperand(2) == EI.getOperand(1)) 218 return replaceInstUsesWith(EI, IE->getOperand(1)); 219 // If the inserted and extracted elements are constants, they must not 220 // be the same value, extract from the pre-inserted value instead. 221 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) { 222 Worklist.AddValue(EI.getOperand(0)); 223 EI.setOperand(0, IE->getOperand(0)); 224 return &EI; 225 } 226 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) { 227 // If this is extracting an element from a shufflevector, figure out where 228 // it came from and extract from the appropriate input element instead. 229 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) { 230 int SrcIdx = SVI->getMaskValue(Elt->getZExtValue()); 231 Value *Src; 232 unsigned LHSWidth = 233 SVI->getOperand(0)->getType()->getVectorNumElements(); 234 235 if (SrcIdx < 0) 236 return replaceInstUsesWith(EI, UndefValue::get(EI.getType())); 237 if (SrcIdx < (int)LHSWidth) 238 Src = SVI->getOperand(0); 239 else { 240 SrcIdx -= LHSWidth; 241 Src = SVI->getOperand(1); 242 } 243 Type *Int32Ty = Type::getInt32Ty(EI.getContext()); 244 return ExtractElementInst::Create(Src, 245 ConstantInt::get(Int32Ty, 246 SrcIdx, false)); 247 } 248 } else if (CastInst *CI = dyn_cast<CastInst>(I)) { 249 // Canonicalize extractelement(cast) -> cast(extractelement). 250 // Bitcasts can change the number of vector elements, and they cost 251 // nothing. 252 if (CI->hasOneUse() && (CI->getOpcode() != Instruction::BitCast)) { 253 Value *EE = Builder.CreateExtractElement(CI->getOperand(0), 254 EI.getIndexOperand()); 255 Worklist.AddValue(EE); 256 return CastInst::Create(CI->getOpcode(), EE, EI.getType()); 257 } 258 } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) { 259 if (SI->hasOneUse()) { 260 // TODO: For a select on vectors, it might be useful to do this if it 261 // has multiple extractelement uses. For vector select, that seems to 262 // fight the vectorizer. 263 264 // If we are extracting an element from a vector select or a select on 265 // vectors, create a select on the scalars extracted from the vector 266 // arguments. 267 Value *TrueVal = SI->getTrueValue(); 268 Value *FalseVal = SI->getFalseValue(); 269 270 Value *Cond = SI->getCondition(); 271 if (Cond->getType()->isVectorTy()) { 272 Cond = Builder.CreateExtractElement(Cond, 273 EI.getIndexOperand(), 274 Cond->getName() + ".elt"); 275 } 276 277 Value *V1Elem 278 = Builder.CreateExtractElement(TrueVal, 279 EI.getIndexOperand(), 280 TrueVal->getName() + ".elt"); 281 282 Value *V2Elem 283 = Builder.CreateExtractElement(FalseVal, 284 EI.getIndexOperand(), 285 FalseVal->getName() + ".elt"); 286 return SelectInst::Create(Cond, 287 V1Elem, 288 V2Elem, 289 SI->getName() + ".elt"); 290 } 291 } 292 } 293 return nullptr; 294 } 295 296 /// If V is a shuffle of values that ONLY returns elements from either LHS or 297 /// RHS, return the shuffle mask and true. Otherwise, return false. 298 static bool collectSingleShuffleElements(Value *V, Value *LHS, Value *RHS, 299 SmallVectorImpl<Constant*> &Mask) { 300 assert(LHS->getType() == RHS->getType() && 301 "Invalid CollectSingleShuffleElements"); 302 unsigned NumElts = V->getType()->getVectorNumElements(); 303 304 if (isa<UndefValue>(V)) { 305 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); 306 return true; 307 } 308 309 if (V == LHS) { 310 for (unsigned i = 0; i != NumElts; ++i) 311 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); 312 return true; 313 } 314 315 if (V == RHS) { 316 for (unsigned i = 0; i != NumElts; ++i) 317 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), 318 i+NumElts)); 319 return true; 320 } 321 322 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 323 // If this is an insert of an extract from some other vector, include it. 324 Value *VecOp = IEI->getOperand(0); 325 Value *ScalarOp = IEI->getOperand(1); 326 Value *IdxOp = IEI->getOperand(2); 327 328 if (!isa<ConstantInt>(IdxOp)) 329 return false; 330 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 331 332 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector. 333 // We can handle this if the vector we are inserting into is 334 // transitively ok. 335 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 336 // If so, update the mask to reflect the inserted undef. 337 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(V->getContext())); 338 return true; 339 } 340 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){ 341 if (isa<ConstantInt>(EI->getOperand(1))) { 342 unsigned ExtractedIdx = 343 cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 344 unsigned NumLHSElts = LHS->getType()->getVectorNumElements(); 345 346 // This must be extracting from either LHS or RHS. 347 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) { 348 // We can handle this if the vector we are inserting into is 349 // transitively ok. 350 if (collectSingleShuffleElements(VecOp, LHS, RHS, Mask)) { 351 // If so, update the mask to reflect the inserted value. 352 if (EI->getOperand(0) == LHS) { 353 Mask[InsertedIdx % NumElts] = 354 ConstantInt::get(Type::getInt32Ty(V->getContext()), 355 ExtractedIdx); 356 } else { 357 assert(EI->getOperand(0) == RHS); 358 Mask[InsertedIdx % NumElts] = 359 ConstantInt::get(Type::getInt32Ty(V->getContext()), 360 ExtractedIdx + NumLHSElts); 361 } 362 return true; 363 } 364 } 365 } 366 } 367 } 368 369 return false; 370 } 371 372 /// If we have insertion into a vector that is wider than the vector that we 373 /// are extracting from, try to widen the source vector to allow a single 374 /// shufflevector to replace one or more insert/extract pairs. 375 static void replaceExtractElements(InsertElementInst *InsElt, 376 ExtractElementInst *ExtElt, 377 InstCombiner &IC) { 378 VectorType *InsVecType = InsElt->getType(); 379 VectorType *ExtVecType = ExtElt->getVectorOperandType(); 380 unsigned NumInsElts = InsVecType->getVectorNumElements(); 381 unsigned NumExtElts = ExtVecType->getVectorNumElements(); 382 383 // The inserted-to vector must be wider than the extracted-from vector. 384 if (InsVecType->getElementType() != ExtVecType->getElementType() || 385 NumExtElts >= NumInsElts) 386 return; 387 388 // Create a shuffle mask to widen the extended-from vector using undefined 389 // values. The mask selects all of the values of the original vector followed 390 // by as many undefined values as needed to create a vector of the same length 391 // as the inserted-to vector. 392 SmallVector<Constant *, 16> ExtendMask; 393 IntegerType *IntType = Type::getInt32Ty(InsElt->getContext()); 394 for (unsigned i = 0; i < NumExtElts; ++i) 395 ExtendMask.push_back(ConstantInt::get(IntType, i)); 396 for (unsigned i = NumExtElts; i < NumInsElts; ++i) 397 ExtendMask.push_back(UndefValue::get(IntType)); 398 399 Value *ExtVecOp = ExtElt->getVectorOperand(); 400 auto *ExtVecOpInst = dyn_cast<Instruction>(ExtVecOp); 401 BasicBlock *InsertionBlock = (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 402 ? ExtVecOpInst->getParent() 403 : ExtElt->getParent(); 404 405 // TODO: This restriction matches the basic block check below when creating 406 // new extractelement instructions. If that limitation is removed, this one 407 // could also be removed. But for now, we just bail out to ensure that we 408 // will replace the extractelement instruction that is feeding our 409 // insertelement instruction. This allows the insertelement to then be 410 // replaced by a shufflevector. If the insertelement is not replaced, we can 411 // induce infinite looping because there's an optimization for extractelement 412 // that will delete our widening shuffle. This would trigger another attempt 413 // here to create that shuffle, and we spin forever. 414 if (InsertionBlock != InsElt->getParent()) 415 return; 416 417 // TODO: This restriction matches the check in visitInsertElementInst() and 418 // prevents an infinite loop caused by not turning the extract/insert pair 419 // into a shuffle. We really should not need either check, but we're lacking 420 // folds for shufflevectors because we're afraid to generate shuffle masks 421 // that the backend can't handle. 422 if (InsElt->hasOneUse() && isa<InsertElementInst>(InsElt->user_back())) 423 return; 424 425 auto *WideVec = new ShuffleVectorInst(ExtVecOp, UndefValue::get(ExtVecType), 426 ConstantVector::get(ExtendMask)); 427 428 // Insert the new shuffle after the vector operand of the extract is defined 429 // (as long as it's not a PHI) or at the start of the basic block of the 430 // extract, so any subsequent extracts in the same basic block can use it. 431 // TODO: Insert before the earliest ExtractElementInst that is replaced. 432 if (ExtVecOpInst && !isa<PHINode>(ExtVecOpInst)) 433 WideVec->insertAfter(ExtVecOpInst); 434 else 435 IC.InsertNewInstWith(WideVec, *ExtElt->getParent()->getFirstInsertionPt()); 436 437 // Replace extracts from the original narrow vector with extracts from the new 438 // wide vector. 439 for (User *U : ExtVecOp->users()) { 440 ExtractElementInst *OldExt = dyn_cast<ExtractElementInst>(U); 441 if (!OldExt || OldExt->getParent() != WideVec->getParent()) 442 continue; 443 auto *NewExt = ExtractElementInst::Create(WideVec, OldExt->getOperand(1)); 444 NewExt->insertAfter(OldExt); 445 IC.replaceInstUsesWith(*OldExt, NewExt); 446 } 447 } 448 449 /// We are building a shuffle to create V, which is a sequence of insertelement, 450 /// extractelement pairs. If PermittedRHS is set, then we must either use it or 451 /// not rely on the second vector source. Return a std::pair containing the 452 /// left and right vectors of the proposed shuffle (or 0), and set the Mask 453 /// parameter as required. 454 /// 455 /// Note: we intentionally don't try to fold earlier shuffles since they have 456 /// often been chosen carefully to be efficiently implementable on the target. 457 typedef std::pair<Value *, Value *> ShuffleOps; 458 459 static ShuffleOps collectShuffleElements(Value *V, 460 SmallVectorImpl<Constant *> &Mask, 461 Value *PermittedRHS, 462 InstCombiner &IC) { 463 assert(V->getType()->isVectorTy() && "Invalid shuffle!"); 464 unsigned NumElts = V->getType()->getVectorNumElements(); 465 466 if (isa<UndefValue>(V)) { 467 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(V->getContext()))); 468 return std::make_pair( 469 PermittedRHS ? UndefValue::get(PermittedRHS->getType()) : V, nullptr); 470 } 471 472 if (isa<ConstantAggregateZero>(V)) { 473 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(V->getContext()),0)); 474 return std::make_pair(V, nullptr); 475 } 476 477 if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) { 478 // If this is an insert of an extract from some other vector, include it. 479 Value *VecOp = IEI->getOperand(0); 480 Value *ScalarOp = IEI->getOperand(1); 481 Value *IdxOp = IEI->getOperand(2); 482 483 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { 484 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { 485 unsigned ExtractedIdx = 486 cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 487 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 488 489 // Either the extracted from or inserted into vector must be RHSVec, 490 // otherwise we'd end up with a shuffle of three inputs. 491 if (EI->getOperand(0) == PermittedRHS || PermittedRHS == nullptr) { 492 Value *RHS = EI->getOperand(0); 493 ShuffleOps LR = collectShuffleElements(VecOp, Mask, RHS, IC); 494 assert(LR.second == nullptr || LR.second == RHS); 495 496 if (LR.first->getType() != RHS->getType()) { 497 // Although we are giving up for now, see if we can create extracts 498 // that match the inserts for another round of combining. 499 replaceExtractElements(IEI, EI, IC); 500 501 // We tried our best, but we can't find anything compatible with RHS 502 // further up the chain. Return a trivial shuffle. 503 for (unsigned i = 0; i < NumElts; ++i) 504 Mask[i] = ConstantInt::get(Type::getInt32Ty(V->getContext()), i); 505 return std::make_pair(V, nullptr); 506 } 507 508 unsigned NumLHSElts = RHS->getType()->getVectorNumElements(); 509 Mask[InsertedIdx % NumElts] = 510 ConstantInt::get(Type::getInt32Ty(V->getContext()), 511 NumLHSElts+ExtractedIdx); 512 return std::make_pair(LR.first, RHS); 513 } 514 515 if (VecOp == PermittedRHS) { 516 // We've gone as far as we can: anything on the other side of the 517 // extractelement will already have been converted into a shuffle. 518 unsigned NumLHSElts = 519 EI->getOperand(0)->getType()->getVectorNumElements(); 520 for (unsigned i = 0; i != NumElts; ++i) 521 Mask.push_back(ConstantInt::get( 522 Type::getInt32Ty(V->getContext()), 523 i == InsertedIdx ? ExtractedIdx : NumLHSElts + i)); 524 return std::make_pair(EI->getOperand(0), PermittedRHS); 525 } 526 527 // If this insertelement is a chain that comes from exactly these two 528 // vectors, return the vector and the effective shuffle. 529 if (EI->getOperand(0)->getType() == PermittedRHS->getType() && 530 collectSingleShuffleElements(IEI, EI->getOperand(0), PermittedRHS, 531 Mask)) 532 return std::make_pair(EI->getOperand(0), PermittedRHS); 533 } 534 } 535 } 536 537 // Otherwise, we can't do anything fancy. Return an identity vector. 538 for (unsigned i = 0; i != NumElts; ++i) 539 Mask.push_back(ConstantInt::get(Type::getInt32Ty(V->getContext()), i)); 540 return std::make_pair(V, nullptr); 541 } 542 543 /// Try to find redundant insertvalue instructions, like the following ones: 544 /// %0 = insertvalue { i8, i32 } undef, i8 %x, 0 545 /// %1 = insertvalue { i8, i32 } %0, i8 %y, 0 546 /// Here the second instruction inserts values at the same indices, as the 547 /// first one, making the first one redundant. 548 /// It should be transformed to: 549 /// %0 = insertvalue { i8, i32 } undef, i8 %y, 0 550 Instruction *InstCombiner::visitInsertValueInst(InsertValueInst &I) { 551 bool IsRedundant = false; 552 ArrayRef<unsigned int> FirstIndices = I.getIndices(); 553 554 // If there is a chain of insertvalue instructions (each of them except the 555 // last one has only one use and it's another insertvalue insn from this 556 // chain), check if any of the 'children' uses the same indices as the first 557 // instruction. In this case, the first one is redundant. 558 Value *V = &I; 559 unsigned Depth = 0; 560 while (V->hasOneUse() && Depth < 10) { 561 User *U = V->user_back(); 562 auto UserInsInst = dyn_cast<InsertValueInst>(U); 563 if (!UserInsInst || U->getOperand(0) != V) 564 break; 565 if (UserInsInst->getIndices() == FirstIndices) { 566 IsRedundant = true; 567 break; 568 } 569 V = UserInsInst; 570 Depth++; 571 } 572 573 if (IsRedundant) 574 return replaceInstUsesWith(I, I.getOperand(0)); 575 return nullptr; 576 } 577 578 static bool isShuffleEquivalentToSelect(ShuffleVectorInst &Shuf) { 579 int MaskSize = Shuf.getMask()->getType()->getVectorNumElements(); 580 int VecSize = Shuf.getOperand(0)->getType()->getVectorNumElements(); 581 582 // A vector select does not change the size of the operands. 583 if (MaskSize != VecSize) 584 return false; 585 586 // Each mask element must be undefined or choose a vector element from one of 587 // the source operands without crossing vector lanes. 588 for (int i = 0; i != MaskSize; ++i) { 589 int Elt = Shuf.getMaskValue(i); 590 if (Elt != -1 && Elt != i && Elt != i + VecSize) 591 return false; 592 } 593 594 return true; 595 } 596 597 // Turn a chain of inserts that splats a value into a canonical insert + shuffle 598 // splat. That is: 599 // insertelt(insertelt(insertelt(insertelt X, %k, 0), %k, 1), %k, 2) ... -> 600 // shufflevector(insertelt(X, %k, 0), undef, zero) 601 static Instruction *foldInsSequenceIntoBroadcast(InsertElementInst &InsElt) { 602 // We are interested in the last insert in a chain. So, if this insert 603 // has a single user, and that user is an insert, bail. 604 if (InsElt.hasOneUse() && isa<InsertElementInst>(InsElt.user_back())) 605 return nullptr; 606 607 VectorType *VT = cast<VectorType>(InsElt.getType()); 608 int NumElements = VT->getNumElements(); 609 610 // Do not try to do this for a one-element vector, since that's a nop, 611 // and will cause an inf-loop. 612 if (NumElements == 1) 613 return nullptr; 614 615 Value *SplatVal = InsElt.getOperand(1); 616 InsertElementInst *CurrIE = &InsElt; 617 SmallVector<bool, 16> ElementPresent(NumElements, false); 618 InsertElementInst *FirstIE = nullptr; 619 620 // Walk the chain backwards, keeping track of which indices we inserted into, 621 // until we hit something that isn't an insert of the splatted value. 622 while (CurrIE) { 623 ConstantInt *Idx = dyn_cast<ConstantInt>(CurrIE->getOperand(2)); 624 if (!Idx || CurrIE->getOperand(1) != SplatVal) 625 return nullptr; 626 627 InsertElementInst *NextIE = 628 dyn_cast<InsertElementInst>(CurrIE->getOperand(0)); 629 // Check none of the intermediate steps have any additional uses, except 630 // for the root insertelement instruction, which can be re-used, if it 631 // inserts at position 0. 632 if (CurrIE != &InsElt && 633 (!CurrIE->hasOneUse() && (NextIE != nullptr || !Idx->isZero()))) 634 return nullptr; 635 636 ElementPresent[Idx->getZExtValue()] = true; 637 FirstIE = CurrIE; 638 CurrIE = NextIE; 639 } 640 641 // Make sure we've seen an insert into every element. 642 if (llvm::any_of(ElementPresent, [](bool Present) { return !Present; })) 643 return nullptr; 644 645 // All right, create the insert + shuffle. 646 Instruction *InsertFirst; 647 if (cast<ConstantInt>(FirstIE->getOperand(2))->isZero()) 648 InsertFirst = FirstIE; 649 else 650 InsertFirst = InsertElementInst::Create( 651 UndefValue::get(VT), SplatVal, 652 ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 0), 653 "", &InsElt); 654 655 Constant *ZeroMask = ConstantAggregateZero::get( 656 VectorType::get(Type::getInt32Ty(InsElt.getContext()), NumElements)); 657 658 return new ShuffleVectorInst(InsertFirst, UndefValue::get(VT), ZeroMask); 659 } 660 661 /// If we have an insertelement instruction feeding into another insertelement 662 /// and the 2nd is inserting a constant into the vector, canonicalize that 663 /// constant insertion before the insertion of a variable: 664 /// 665 /// insertelement (insertelement X, Y, IdxC1), ScalarC, IdxC2 --> 666 /// insertelement (insertelement X, ScalarC, IdxC2), Y, IdxC1 667 /// 668 /// This has the potential of eliminating the 2nd insertelement instruction 669 /// via constant folding of the scalar constant into a vector constant. 670 static Instruction *hoistInsEltConst(InsertElementInst &InsElt2, 671 InstCombiner::BuilderTy &Builder) { 672 auto *InsElt1 = dyn_cast<InsertElementInst>(InsElt2.getOperand(0)); 673 if (!InsElt1 || !InsElt1->hasOneUse()) 674 return nullptr; 675 676 Value *X, *Y; 677 Constant *ScalarC; 678 ConstantInt *IdxC1, *IdxC2; 679 if (match(InsElt1->getOperand(0), m_Value(X)) && 680 match(InsElt1->getOperand(1), m_Value(Y)) && !isa<Constant>(Y) && 681 match(InsElt1->getOperand(2), m_ConstantInt(IdxC1)) && 682 match(InsElt2.getOperand(1), m_Constant(ScalarC)) && 683 match(InsElt2.getOperand(2), m_ConstantInt(IdxC2)) && IdxC1 != IdxC2) { 684 Value *NewInsElt1 = Builder.CreateInsertElement(X, ScalarC, IdxC2); 685 return InsertElementInst::Create(NewInsElt1, Y, IdxC1); 686 } 687 688 return nullptr; 689 } 690 691 /// insertelt (shufflevector X, CVec, Mask|insertelt X, C1, CIndex1), C, CIndex 692 /// --> shufflevector X, CVec', Mask' 693 static Instruction *foldConstantInsEltIntoShuffle(InsertElementInst &InsElt) { 694 auto *Inst = dyn_cast<Instruction>(InsElt.getOperand(0)); 695 // Bail out if the parent has more than one use. In that case, we'd be 696 // replacing the insertelt with a shuffle, and that's not a clear win. 697 if (!Inst || !Inst->hasOneUse()) 698 return nullptr; 699 if (auto *Shuf = dyn_cast<ShuffleVectorInst>(InsElt.getOperand(0))) { 700 // The shuffle must have a constant vector operand. The insertelt must have 701 // a constant scalar being inserted at a constant position in the vector. 702 Constant *ShufConstVec, *InsEltScalar; 703 uint64_t InsEltIndex; 704 if (!match(Shuf->getOperand(1), m_Constant(ShufConstVec)) || 705 !match(InsElt.getOperand(1), m_Constant(InsEltScalar)) || 706 !match(InsElt.getOperand(2), m_ConstantInt(InsEltIndex))) 707 return nullptr; 708 709 // Adding an element to an arbitrary shuffle could be expensive, but a 710 // shuffle that selects elements from vectors without crossing lanes is 711 // assumed cheap. 712 // If we're just adding a constant into that shuffle, it will still be 713 // cheap. 714 if (!isShuffleEquivalentToSelect(*Shuf)) 715 return nullptr; 716 717 // From the above 'select' check, we know that the mask has the same number 718 // of elements as the vector input operands. We also know that each constant 719 // input element is used in its lane and can not be used more than once by 720 // the shuffle. Therefore, replace the constant in the shuffle's constant 721 // vector with the insertelt constant. Replace the constant in the shuffle's 722 // mask vector with the insertelt index plus the length of the vector 723 // (because the constant vector operand of a shuffle is always the 2nd 724 // operand). 725 Constant *Mask = Shuf->getMask(); 726 unsigned NumElts = Mask->getType()->getVectorNumElements(); 727 SmallVector<Constant *, 16> NewShufElts(NumElts); 728 SmallVector<Constant *, 16> NewMaskElts(NumElts); 729 for (unsigned I = 0; I != NumElts; ++I) { 730 if (I == InsEltIndex) { 731 NewShufElts[I] = InsEltScalar; 732 Type *Int32Ty = Type::getInt32Ty(Shuf->getContext()); 733 NewMaskElts[I] = ConstantInt::get(Int32Ty, InsEltIndex + NumElts); 734 } else { 735 // Copy over the existing values. 736 NewShufElts[I] = ShufConstVec->getAggregateElement(I); 737 NewMaskElts[I] = Mask->getAggregateElement(I); 738 } 739 } 740 741 // Create new operands for a shuffle that includes the constant of the 742 // original insertelt. The old shuffle will be dead now. 743 return new ShuffleVectorInst(Shuf->getOperand(0), 744 ConstantVector::get(NewShufElts), 745 ConstantVector::get(NewMaskElts)); 746 } else if (auto *IEI = dyn_cast<InsertElementInst>(Inst)) { 747 // Transform sequences of insertelements ops with constant data/indexes into 748 // a single shuffle op. 749 unsigned NumElts = InsElt.getType()->getNumElements(); 750 751 uint64_t InsertIdx[2]; 752 Constant *Val[2]; 753 if (!match(InsElt.getOperand(2), m_ConstantInt(InsertIdx[0])) || 754 !match(InsElt.getOperand(1), m_Constant(Val[0])) || 755 !match(IEI->getOperand(2), m_ConstantInt(InsertIdx[1])) || 756 !match(IEI->getOperand(1), m_Constant(Val[1]))) 757 return nullptr; 758 SmallVector<Constant *, 16> Values(NumElts); 759 SmallVector<Constant *, 16> Mask(NumElts); 760 auto ValI = std::begin(Val); 761 // Generate new constant vector and mask. 762 // We have 2 values/masks from the insertelements instructions. Insert them 763 // into new value/mask vectors. 764 for (uint64_t I : InsertIdx) { 765 if (!Values[I]) { 766 assert(!Mask[I]); 767 Values[I] = *ValI; 768 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), 769 NumElts + I); 770 } 771 ++ValI; 772 } 773 // Remaining values are filled with 'undef' values. 774 for (unsigned I = 0; I < NumElts; ++I) { 775 if (!Values[I]) { 776 assert(!Mask[I]); 777 Values[I] = UndefValue::get(InsElt.getType()->getElementType()); 778 Mask[I] = ConstantInt::get(Type::getInt32Ty(InsElt.getContext()), I); 779 } 780 } 781 // Create new operands for a shuffle that includes the constant of the 782 // original insertelt. 783 return new ShuffleVectorInst(IEI->getOperand(0), 784 ConstantVector::get(Values), 785 ConstantVector::get(Mask)); 786 } 787 return nullptr; 788 } 789 790 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) { 791 Value *VecOp = IE.getOperand(0); 792 Value *ScalarOp = IE.getOperand(1); 793 Value *IdxOp = IE.getOperand(2); 794 795 // Inserting an undef or into an undefined place, remove this. 796 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp)) 797 replaceInstUsesWith(IE, VecOp); 798 799 // If the inserted element was extracted from some other vector, and if the 800 // indexes are constant, try to turn this into a shufflevector operation. 801 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) { 802 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp)) { 803 unsigned NumInsertVectorElts = IE.getType()->getNumElements(); 804 unsigned NumExtractVectorElts = 805 EI->getOperand(0)->getType()->getVectorNumElements(); 806 unsigned ExtractedIdx = 807 cast<ConstantInt>(EI->getOperand(1))->getZExtValue(); 808 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue(); 809 810 if (ExtractedIdx >= NumExtractVectorElts) // Out of range extract. 811 return replaceInstUsesWith(IE, VecOp); 812 813 if (InsertedIdx >= NumInsertVectorElts) // Out of range insert. 814 return replaceInstUsesWith(IE, UndefValue::get(IE.getType())); 815 816 // If we are extracting a value from a vector, then inserting it right 817 // back into the same place, just use the input vector. 818 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx) 819 return replaceInstUsesWith(IE, VecOp); 820 821 // If this insertelement isn't used by some other insertelement, turn it 822 // (and any insertelements it points to), into one big shuffle. 823 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.user_back())) { 824 SmallVector<Constant*, 16> Mask; 825 ShuffleOps LR = collectShuffleElements(&IE, Mask, nullptr, *this); 826 827 // The proposed shuffle may be trivial, in which case we shouldn't 828 // perform the combine. 829 if (LR.first != &IE && LR.second != &IE) { 830 // We now have a shuffle of LHS, RHS, Mask. 831 if (LR.second == nullptr) 832 LR.second = UndefValue::get(LR.first->getType()); 833 return new ShuffleVectorInst(LR.first, LR.second, 834 ConstantVector::get(Mask)); 835 } 836 } 837 } 838 } 839 840 unsigned VWidth = VecOp->getType()->getVectorNumElements(); 841 APInt UndefElts(VWidth, 0); 842 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 843 if (Value *V = SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts)) { 844 if (V != &IE) 845 return replaceInstUsesWith(IE, V); 846 return &IE; 847 } 848 849 if (Instruction *Shuf = foldConstantInsEltIntoShuffle(IE)) 850 return Shuf; 851 852 if (Instruction *NewInsElt = hoistInsEltConst(IE, Builder)) 853 return NewInsElt; 854 855 // Turn a sequence of inserts that broadcasts a scalar into a single 856 // insert + shufflevector. 857 if (Instruction *Broadcast = foldInsSequenceIntoBroadcast(IE)) 858 return Broadcast; 859 860 return nullptr; 861 } 862 863 /// Return true if we can evaluate the specified expression tree if the vector 864 /// elements were shuffled in a different order. 865 static bool CanEvaluateShuffled(Value *V, ArrayRef<int> Mask, 866 unsigned Depth = 5) { 867 // We can always reorder the elements of a constant. 868 if (isa<Constant>(V)) 869 return true; 870 871 // We won't reorder vector arguments. No IPO here. 872 Instruction *I = dyn_cast<Instruction>(V); 873 if (!I) return false; 874 875 // Two users may expect different orders of the elements. Don't try it. 876 if (!I->hasOneUse()) 877 return false; 878 879 if (Depth == 0) return false; 880 881 switch (I->getOpcode()) { 882 case Instruction::Add: 883 case Instruction::FAdd: 884 case Instruction::Sub: 885 case Instruction::FSub: 886 case Instruction::Mul: 887 case Instruction::FMul: 888 case Instruction::UDiv: 889 case Instruction::SDiv: 890 case Instruction::FDiv: 891 case Instruction::URem: 892 case Instruction::SRem: 893 case Instruction::FRem: 894 case Instruction::Shl: 895 case Instruction::LShr: 896 case Instruction::AShr: 897 case Instruction::And: 898 case Instruction::Or: 899 case Instruction::Xor: 900 case Instruction::ICmp: 901 case Instruction::FCmp: 902 case Instruction::Trunc: 903 case Instruction::ZExt: 904 case Instruction::SExt: 905 case Instruction::FPToUI: 906 case Instruction::FPToSI: 907 case Instruction::UIToFP: 908 case Instruction::SIToFP: 909 case Instruction::FPTrunc: 910 case Instruction::FPExt: 911 case Instruction::GetElementPtr: { 912 for (Value *Operand : I->operands()) { 913 if (!CanEvaluateShuffled(Operand, Mask, Depth-1)) 914 return false; 915 } 916 return true; 917 } 918 case Instruction::InsertElement: { 919 ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(2)); 920 if (!CI) return false; 921 int ElementNumber = CI->getLimitedValue(); 922 923 // Verify that 'CI' does not occur twice in Mask. A single 'insertelement' 924 // can't put an element into multiple indices. 925 bool SeenOnce = false; 926 for (int i = 0, e = Mask.size(); i != e; ++i) { 927 if (Mask[i] == ElementNumber) { 928 if (SeenOnce) 929 return false; 930 SeenOnce = true; 931 } 932 } 933 return CanEvaluateShuffled(I->getOperand(0), Mask, Depth-1); 934 } 935 } 936 return false; 937 } 938 939 /// Rebuild a new instruction just like 'I' but with the new operands given. 940 /// In the event of type mismatch, the type of the operands is correct. 941 static Value *buildNew(Instruction *I, ArrayRef<Value*> NewOps) { 942 // We don't want to use the IRBuilder here because we want the replacement 943 // instructions to appear next to 'I', not the builder's insertion point. 944 switch (I->getOpcode()) { 945 case Instruction::Add: 946 case Instruction::FAdd: 947 case Instruction::Sub: 948 case Instruction::FSub: 949 case Instruction::Mul: 950 case Instruction::FMul: 951 case Instruction::UDiv: 952 case Instruction::SDiv: 953 case Instruction::FDiv: 954 case Instruction::URem: 955 case Instruction::SRem: 956 case Instruction::FRem: 957 case Instruction::Shl: 958 case Instruction::LShr: 959 case Instruction::AShr: 960 case Instruction::And: 961 case Instruction::Or: 962 case Instruction::Xor: { 963 BinaryOperator *BO = cast<BinaryOperator>(I); 964 assert(NewOps.size() == 2 && "binary operator with #ops != 2"); 965 BinaryOperator *New = 966 BinaryOperator::Create(cast<BinaryOperator>(I)->getOpcode(), 967 NewOps[0], NewOps[1], "", BO); 968 if (isa<OverflowingBinaryOperator>(BO)) { 969 New->setHasNoUnsignedWrap(BO->hasNoUnsignedWrap()); 970 New->setHasNoSignedWrap(BO->hasNoSignedWrap()); 971 } 972 if (isa<PossiblyExactOperator>(BO)) { 973 New->setIsExact(BO->isExact()); 974 } 975 if (isa<FPMathOperator>(BO)) 976 New->copyFastMathFlags(I); 977 return New; 978 } 979 case Instruction::ICmp: 980 assert(NewOps.size() == 2 && "icmp with #ops != 2"); 981 return new ICmpInst(I, cast<ICmpInst>(I)->getPredicate(), 982 NewOps[0], NewOps[1]); 983 case Instruction::FCmp: 984 assert(NewOps.size() == 2 && "fcmp with #ops != 2"); 985 return new FCmpInst(I, cast<FCmpInst>(I)->getPredicate(), 986 NewOps[0], NewOps[1]); 987 case Instruction::Trunc: 988 case Instruction::ZExt: 989 case Instruction::SExt: 990 case Instruction::FPToUI: 991 case Instruction::FPToSI: 992 case Instruction::UIToFP: 993 case Instruction::SIToFP: 994 case Instruction::FPTrunc: 995 case Instruction::FPExt: { 996 // It's possible that the mask has a different number of elements from 997 // the original cast. We recompute the destination type to match the mask. 998 Type *DestTy = 999 VectorType::get(I->getType()->getScalarType(), 1000 NewOps[0]->getType()->getVectorNumElements()); 1001 assert(NewOps.size() == 1 && "cast with #ops != 1"); 1002 return CastInst::Create(cast<CastInst>(I)->getOpcode(), NewOps[0], DestTy, 1003 "", I); 1004 } 1005 case Instruction::GetElementPtr: { 1006 Value *Ptr = NewOps[0]; 1007 ArrayRef<Value*> Idx = NewOps.slice(1); 1008 GetElementPtrInst *GEP = GetElementPtrInst::Create( 1009 cast<GetElementPtrInst>(I)->getSourceElementType(), Ptr, Idx, "", I); 1010 GEP->setIsInBounds(cast<GetElementPtrInst>(I)->isInBounds()); 1011 return GEP; 1012 } 1013 } 1014 llvm_unreachable("failed to rebuild vector instructions"); 1015 } 1016 1017 Value * 1018 InstCombiner::EvaluateInDifferentElementOrder(Value *V, ArrayRef<int> Mask) { 1019 // Mask.size() does not need to be equal to the number of vector elements. 1020 1021 assert(V->getType()->isVectorTy() && "can't reorder non-vector elements"); 1022 if (isa<UndefValue>(V)) { 1023 return UndefValue::get(VectorType::get(V->getType()->getScalarType(), 1024 Mask.size())); 1025 } 1026 if (isa<ConstantAggregateZero>(V)) { 1027 return ConstantAggregateZero::get( 1028 VectorType::get(V->getType()->getScalarType(), 1029 Mask.size())); 1030 } 1031 if (Constant *C = dyn_cast<Constant>(V)) { 1032 SmallVector<Constant *, 16> MaskValues; 1033 for (int i = 0, e = Mask.size(); i != e; ++i) { 1034 if (Mask[i] == -1) 1035 MaskValues.push_back(UndefValue::get(Builder.getInt32Ty())); 1036 else 1037 MaskValues.push_back(Builder.getInt32(Mask[i])); 1038 } 1039 return ConstantExpr::getShuffleVector(C, UndefValue::get(C->getType()), 1040 ConstantVector::get(MaskValues)); 1041 } 1042 1043 Instruction *I = cast<Instruction>(V); 1044 switch (I->getOpcode()) { 1045 case Instruction::Add: 1046 case Instruction::FAdd: 1047 case Instruction::Sub: 1048 case Instruction::FSub: 1049 case Instruction::Mul: 1050 case Instruction::FMul: 1051 case Instruction::UDiv: 1052 case Instruction::SDiv: 1053 case Instruction::FDiv: 1054 case Instruction::URem: 1055 case Instruction::SRem: 1056 case Instruction::FRem: 1057 case Instruction::Shl: 1058 case Instruction::LShr: 1059 case Instruction::AShr: 1060 case Instruction::And: 1061 case Instruction::Or: 1062 case Instruction::Xor: 1063 case Instruction::ICmp: 1064 case Instruction::FCmp: 1065 case Instruction::Trunc: 1066 case Instruction::ZExt: 1067 case Instruction::SExt: 1068 case Instruction::FPToUI: 1069 case Instruction::FPToSI: 1070 case Instruction::UIToFP: 1071 case Instruction::SIToFP: 1072 case Instruction::FPTrunc: 1073 case Instruction::FPExt: 1074 case Instruction::Select: 1075 case Instruction::GetElementPtr: { 1076 SmallVector<Value*, 8> NewOps; 1077 bool NeedsRebuild = (Mask.size() != I->getType()->getVectorNumElements()); 1078 for (int i = 0, e = I->getNumOperands(); i != e; ++i) { 1079 Value *V = EvaluateInDifferentElementOrder(I->getOperand(i), Mask); 1080 NewOps.push_back(V); 1081 NeedsRebuild |= (V != I->getOperand(i)); 1082 } 1083 if (NeedsRebuild) { 1084 return buildNew(I, NewOps); 1085 } 1086 return I; 1087 } 1088 case Instruction::InsertElement: { 1089 int Element = cast<ConstantInt>(I->getOperand(2))->getLimitedValue(); 1090 1091 // The insertelement was inserting at Element. Figure out which element 1092 // that becomes after shuffling. The answer is guaranteed to be unique 1093 // by CanEvaluateShuffled. 1094 bool Found = false; 1095 int Index = 0; 1096 for (int e = Mask.size(); Index != e; ++Index) { 1097 if (Mask[Index] == Element) { 1098 Found = true; 1099 break; 1100 } 1101 } 1102 1103 // If element is not in Mask, no need to handle the operand 1 (element to 1104 // be inserted). Just evaluate values in operand 0 according to Mask. 1105 if (!Found) 1106 return EvaluateInDifferentElementOrder(I->getOperand(0), Mask); 1107 1108 Value *V = EvaluateInDifferentElementOrder(I->getOperand(0), Mask); 1109 return InsertElementInst::Create(V, I->getOperand(1), 1110 Builder.getInt32(Index), "", I); 1111 } 1112 } 1113 llvm_unreachable("failed to reorder elements of vector instruction!"); 1114 } 1115 1116 static void recognizeIdentityMask(const SmallVectorImpl<int> &Mask, 1117 bool &isLHSID, bool &isRHSID) { 1118 isLHSID = isRHSID = true; 1119 1120 for (unsigned i = 0, e = Mask.size(); i != e; ++i) { 1121 if (Mask[i] < 0) continue; // Ignore undef values. 1122 // Is this an identity shuffle of the LHS value? 1123 isLHSID &= (Mask[i] == (int)i); 1124 1125 // Is this an identity shuffle of the RHS value? 1126 isRHSID &= (Mask[i]-e == i); 1127 } 1128 } 1129 1130 // Returns true if the shuffle is extracting a contiguous range of values from 1131 // LHS, for example: 1132 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 1133 // Input: |AA|BB|CC|DD|EE|FF|GG|HH|II|JJ|KK|LL|MM|NN|OO|PP| 1134 // Shuffles to: |EE|FF|GG|HH| 1135 // +--+--+--+--+ 1136 static bool isShuffleExtractingFromLHS(ShuffleVectorInst &SVI, 1137 SmallVector<int, 16> &Mask) { 1138 unsigned LHSElems = SVI.getOperand(0)->getType()->getVectorNumElements(); 1139 unsigned MaskElems = Mask.size(); 1140 unsigned BegIdx = Mask.front(); 1141 unsigned EndIdx = Mask.back(); 1142 if (BegIdx > EndIdx || EndIdx >= LHSElems || EndIdx - BegIdx != MaskElems - 1) 1143 return false; 1144 for (unsigned I = 0; I != MaskElems; ++I) 1145 if (static_cast<unsigned>(Mask[I]) != BegIdx + I) 1146 return false; 1147 return true; 1148 } 1149 1150 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) { 1151 Value *LHS = SVI.getOperand(0); 1152 Value *RHS = SVI.getOperand(1); 1153 SmallVector<int, 16> Mask = SVI.getShuffleMask(); 1154 Type *Int32Ty = Type::getInt32Ty(SVI.getContext()); 1155 1156 if (auto *V = SimplifyShuffleVectorInst( 1157 LHS, RHS, SVI.getMask(), SVI.getType(), SQ.getWithInstruction(&SVI))) 1158 return replaceInstUsesWith(SVI, V); 1159 1160 bool MadeChange = false; 1161 unsigned VWidth = SVI.getType()->getVectorNumElements(); 1162 1163 APInt UndefElts(VWidth, 0); 1164 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth)); 1165 if (Value *V = SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) { 1166 if (V != &SVI) 1167 return replaceInstUsesWith(SVI, V); 1168 return &SVI; 1169 } 1170 1171 unsigned LHSWidth = LHS->getType()->getVectorNumElements(); 1172 1173 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask') 1174 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask'). 1175 if (LHS == RHS || isa<UndefValue>(LHS)) { 1176 if (isa<UndefValue>(LHS) && LHS == RHS) { 1177 // shuffle(undef,undef,mask) -> undef. 1178 Value *Result = (VWidth == LHSWidth) 1179 ? LHS : UndefValue::get(SVI.getType()); 1180 return replaceInstUsesWith(SVI, Result); 1181 } 1182 1183 // Remap any references to RHS to use LHS. 1184 SmallVector<Constant*, 16> Elts; 1185 for (unsigned i = 0, e = LHSWidth; i != VWidth; ++i) { 1186 if (Mask[i] < 0) { 1187 Elts.push_back(UndefValue::get(Int32Ty)); 1188 continue; 1189 } 1190 1191 if ((Mask[i] >= (int)e && isa<UndefValue>(RHS)) || 1192 (Mask[i] < (int)e && isa<UndefValue>(LHS))) { 1193 Mask[i] = -1; // Turn into undef. 1194 Elts.push_back(UndefValue::get(Int32Ty)); 1195 } else { 1196 Mask[i] = Mask[i] % e; // Force to LHS. 1197 Elts.push_back(ConstantInt::get(Int32Ty, Mask[i])); 1198 } 1199 } 1200 SVI.setOperand(0, SVI.getOperand(1)); 1201 SVI.setOperand(1, UndefValue::get(RHS->getType())); 1202 SVI.setOperand(2, ConstantVector::get(Elts)); 1203 LHS = SVI.getOperand(0); 1204 RHS = SVI.getOperand(1); 1205 MadeChange = true; 1206 } 1207 1208 if (VWidth == LHSWidth) { 1209 // Analyze the shuffle, are the LHS or RHS and identity shuffles? 1210 bool isLHSID, isRHSID; 1211 recognizeIdentityMask(Mask, isLHSID, isRHSID); 1212 1213 // Eliminate identity shuffles. 1214 if (isLHSID) return replaceInstUsesWith(SVI, LHS); 1215 if (isRHSID) return replaceInstUsesWith(SVI, RHS); 1216 } 1217 1218 if (isa<UndefValue>(RHS) && CanEvaluateShuffled(LHS, Mask)) { 1219 Value *V = EvaluateInDifferentElementOrder(LHS, Mask); 1220 return replaceInstUsesWith(SVI, V); 1221 } 1222 1223 // SROA generates shuffle+bitcast when the extracted sub-vector is bitcast to 1224 // a non-vector type. We can instead bitcast the original vector followed by 1225 // an extract of the desired element: 1226 // 1227 // %sroa = shufflevector <16 x i8> %in, <16 x i8> undef, 1228 // <4 x i32> <i32 0, i32 1, i32 2, i32 3> 1229 // %1 = bitcast <4 x i8> %sroa to i32 1230 // Becomes: 1231 // %bc = bitcast <16 x i8> %in to <4 x i32> 1232 // %ext = extractelement <4 x i32> %bc, i32 0 1233 // 1234 // If the shuffle is extracting a contiguous range of values from the input 1235 // vector then each use which is a bitcast of the extracted size can be 1236 // replaced. This will work if the vector types are compatible, and the begin 1237 // index is aligned to a value in the casted vector type. If the begin index 1238 // isn't aligned then we can shuffle the original vector (keeping the same 1239 // vector type) before extracting. 1240 // 1241 // This code will bail out if the target type is fundamentally incompatible 1242 // with vectors of the source type. 1243 // 1244 // Example of <16 x i8>, target type i32: 1245 // Index range [4,8): v-----------v Will work. 1246 // +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ 1247 // <16 x i8>: | | | | | | | | | | | | | | | | | 1248 // <4 x i32>: | | | | | 1249 // +-----------+-----------+-----------+-----------+ 1250 // Index range [6,10): ^-----------^ Needs an extra shuffle. 1251 // Target type i40: ^--------------^ Won't work, bail. 1252 if (isShuffleExtractingFromLHS(SVI, Mask)) { 1253 Value *V = LHS; 1254 unsigned MaskElems = Mask.size(); 1255 VectorType *SrcTy = cast<VectorType>(V->getType()); 1256 unsigned VecBitWidth = SrcTy->getBitWidth(); 1257 unsigned SrcElemBitWidth = DL.getTypeSizeInBits(SrcTy->getElementType()); 1258 assert(SrcElemBitWidth && "vector elements must have a bitwidth"); 1259 unsigned SrcNumElems = SrcTy->getNumElements(); 1260 SmallVector<BitCastInst *, 8> BCs; 1261 DenseMap<Type *, Value *> NewBCs; 1262 for (User *U : SVI.users()) 1263 if (BitCastInst *BC = dyn_cast<BitCastInst>(U)) 1264 if (!BC->use_empty()) 1265 // Only visit bitcasts that weren't previously handled. 1266 BCs.push_back(BC); 1267 for (BitCastInst *BC : BCs) { 1268 unsigned BegIdx = Mask.front(); 1269 Type *TgtTy = BC->getDestTy(); 1270 unsigned TgtElemBitWidth = DL.getTypeSizeInBits(TgtTy); 1271 if (!TgtElemBitWidth) 1272 continue; 1273 unsigned TgtNumElems = VecBitWidth / TgtElemBitWidth; 1274 bool VecBitWidthsEqual = VecBitWidth == TgtNumElems * TgtElemBitWidth; 1275 bool BegIsAligned = 0 == ((SrcElemBitWidth * BegIdx) % TgtElemBitWidth); 1276 if (!VecBitWidthsEqual) 1277 continue; 1278 if (!VectorType::isValidElementType(TgtTy)) 1279 continue; 1280 VectorType *CastSrcTy = VectorType::get(TgtTy, TgtNumElems); 1281 if (!BegIsAligned) { 1282 // Shuffle the input so [0,NumElements) contains the output, and 1283 // [NumElems,SrcNumElems) is undef. 1284 SmallVector<Constant *, 16> ShuffleMask(SrcNumElems, 1285 UndefValue::get(Int32Ty)); 1286 for (unsigned I = 0, E = MaskElems, Idx = BegIdx; I != E; ++Idx, ++I) 1287 ShuffleMask[I] = ConstantInt::get(Int32Ty, Idx); 1288 V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()), 1289 ConstantVector::get(ShuffleMask), 1290 SVI.getName() + ".extract"); 1291 BegIdx = 0; 1292 } 1293 unsigned SrcElemsPerTgtElem = TgtElemBitWidth / SrcElemBitWidth; 1294 assert(SrcElemsPerTgtElem); 1295 BegIdx /= SrcElemsPerTgtElem; 1296 bool BCAlreadyExists = NewBCs.find(CastSrcTy) != NewBCs.end(); 1297 auto *NewBC = 1298 BCAlreadyExists 1299 ? NewBCs[CastSrcTy] 1300 : Builder.CreateBitCast(V, CastSrcTy, SVI.getName() + ".bc"); 1301 if (!BCAlreadyExists) 1302 NewBCs[CastSrcTy] = NewBC; 1303 auto *Ext = Builder.CreateExtractElement( 1304 NewBC, ConstantInt::get(Int32Ty, BegIdx), SVI.getName() + ".extract"); 1305 // The shufflevector isn't being replaced: the bitcast that used it 1306 // is. InstCombine will visit the newly-created instructions. 1307 replaceInstUsesWith(*BC, Ext); 1308 MadeChange = true; 1309 } 1310 } 1311 1312 // If the LHS is a shufflevector itself, see if we can combine it with this 1313 // one without producing an unusual shuffle. 1314 // Cases that might be simplified: 1315 // 1. 1316 // x1=shuffle(v1,v2,mask1) 1317 // x=shuffle(x1,undef,mask) 1318 // ==> 1319 // x=shuffle(v1,undef,newMask) 1320 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : -1 1321 // 2. 1322 // x1=shuffle(v1,undef,mask1) 1323 // x=shuffle(x1,x2,mask) 1324 // where v1.size() == mask1.size() 1325 // ==> 1326 // x=shuffle(v1,x2,newMask) 1327 // newMask[i] = (mask[i] < x1.size()) ? mask1[mask[i]] : mask[i] 1328 // 3. 1329 // x2=shuffle(v2,undef,mask2) 1330 // x=shuffle(x1,x2,mask) 1331 // where v2.size() == mask2.size() 1332 // ==> 1333 // x=shuffle(x1,v2,newMask) 1334 // newMask[i] = (mask[i] < x1.size()) 1335 // ? mask[i] : mask2[mask[i]-x1.size()]+x1.size() 1336 // 4. 1337 // x1=shuffle(v1,undef,mask1) 1338 // x2=shuffle(v2,undef,mask2) 1339 // x=shuffle(x1,x2,mask) 1340 // where v1.size() == v2.size() 1341 // ==> 1342 // x=shuffle(v1,v2,newMask) 1343 // newMask[i] = (mask[i] < x1.size()) 1344 // ? mask1[mask[i]] : mask2[mask[i]-x1.size()]+v1.size() 1345 // 1346 // Here we are really conservative: 1347 // we are absolutely afraid of producing a shuffle mask not in the input 1348 // program, because the code gen may not be smart enough to turn a merged 1349 // shuffle into two specific shuffles: it may produce worse code. As such, 1350 // we only merge two shuffles if the result is either a splat or one of the 1351 // input shuffle masks. In this case, merging the shuffles just removes 1352 // one instruction, which we know is safe. This is good for things like 1353 // turning: (splat(splat)) -> splat, or 1354 // merge(V[0..n], V[n+1..2n]) -> V[0..2n] 1355 ShuffleVectorInst* LHSShuffle = dyn_cast<ShuffleVectorInst>(LHS); 1356 ShuffleVectorInst* RHSShuffle = dyn_cast<ShuffleVectorInst>(RHS); 1357 if (LHSShuffle) 1358 if (!isa<UndefValue>(LHSShuffle->getOperand(1)) && !isa<UndefValue>(RHS)) 1359 LHSShuffle = nullptr; 1360 if (RHSShuffle) 1361 if (!isa<UndefValue>(RHSShuffle->getOperand(1))) 1362 RHSShuffle = nullptr; 1363 if (!LHSShuffle && !RHSShuffle) 1364 return MadeChange ? &SVI : nullptr; 1365 1366 Value* LHSOp0 = nullptr; 1367 Value* LHSOp1 = nullptr; 1368 Value* RHSOp0 = nullptr; 1369 unsigned LHSOp0Width = 0; 1370 unsigned RHSOp0Width = 0; 1371 if (LHSShuffle) { 1372 LHSOp0 = LHSShuffle->getOperand(0); 1373 LHSOp1 = LHSShuffle->getOperand(1); 1374 LHSOp0Width = LHSOp0->getType()->getVectorNumElements(); 1375 } 1376 if (RHSShuffle) { 1377 RHSOp0 = RHSShuffle->getOperand(0); 1378 RHSOp0Width = RHSOp0->getType()->getVectorNumElements(); 1379 } 1380 Value* newLHS = LHS; 1381 Value* newRHS = RHS; 1382 if (LHSShuffle) { 1383 // case 1 1384 if (isa<UndefValue>(RHS)) { 1385 newLHS = LHSOp0; 1386 newRHS = LHSOp1; 1387 } 1388 // case 2 or 4 1389 else if (LHSOp0Width == LHSWidth) { 1390 newLHS = LHSOp0; 1391 } 1392 } 1393 // case 3 or 4 1394 if (RHSShuffle && RHSOp0Width == LHSWidth) { 1395 newRHS = RHSOp0; 1396 } 1397 // case 4 1398 if (LHSOp0 == RHSOp0) { 1399 newLHS = LHSOp0; 1400 newRHS = nullptr; 1401 } 1402 1403 if (newLHS == LHS && newRHS == RHS) 1404 return MadeChange ? &SVI : nullptr; 1405 1406 SmallVector<int, 16> LHSMask; 1407 SmallVector<int, 16> RHSMask; 1408 if (newLHS != LHS) 1409 LHSMask = LHSShuffle->getShuffleMask(); 1410 if (RHSShuffle && newRHS != RHS) 1411 RHSMask = RHSShuffle->getShuffleMask(); 1412 1413 unsigned newLHSWidth = (newLHS != LHS) ? LHSOp0Width : LHSWidth; 1414 SmallVector<int, 16> newMask; 1415 bool isSplat = true; 1416 int SplatElt = -1; 1417 // Create a new mask for the new ShuffleVectorInst so that the new 1418 // ShuffleVectorInst is equivalent to the original one. 1419 for (unsigned i = 0; i < VWidth; ++i) { 1420 int eltMask; 1421 if (Mask[i] < 0) { 1422 // This element is an undef value. 1423 eltMask = -1; 1424 } else if (Mask[i] < (int)LHSWidth) { 1425 // This element is from left hand side vector operand. 1426 // 1427 // If LHS is going to be replaced (case 1, 2, or 4), calculate the 1428 // new mask value for the element. 1429 if (newLHS != LHS) { 1430 eltMask = LHSMask[Mask[i]]; 1431 // If the value selected is an undef value, explicitly specify it 1432 // with a -1 mask value. 1433 if (eltMask >= (int)LHSOp0Width && isa<UndefValue>(LHSOp1)) 1434 eltMask = -1; 1435 } else 1436 eltMask = Mask[i]; 1437 } else { 1438 // This element is from right hand side vector operand 1439 // 1440 // If the value selected is an undef value, explicitly specify it 1441 // with a -1 mask value. (case 1) 1442 if (isa<UndefValue>(RHS)) 1443 eltMask = -1; 1444 // If RHS is going to be replaced (case 3 or 4), calculate the 1445 // new mask value for the element. 1446 else if (newRHS != RHS) { 1447 eltMask = RHSMask[Mask[i]-LHSWidth]; 1448 // If the value selected is an undef value, explicitly specify it 1449 // with a -1 mask value. 1450 if (eltMask >= (int)RHSOp0Width) { 1451 assert(isa<UndefValue>(RHSShuffle->getOperand(1)) 1452 && "should have been check above"); 1453 eltMask = -1; 1454 } 1455 } else 1456 eltMask = Mask[i]-LHSWidth; 1457 1458 // If LHS's width is changed, shift the mask value accordingly. 1459 // If newRHS == NULL, i.e. LHSOp0 == RHSOp0, we want to remap any 1460 // references from RHSOp0 to LHSOp0, so we don't need to shift the mask. 1461 // If newRHS == newLHS, we want to remap any references from newRHS to 1462 // newLHS so that we can properly identify splats that may occur due to 1463 // obfuscation across the two vectors. 1464 if (eltMask >= 0 && newRHS != nullptr && newLHS != newRHS) 1465 eltMask += newLHSWidth; 1466 } 1467 1468 // Check if this could still be a splat. 1469 if (eltMask >= 0) { 1470 if (SplatElt >= 0 && SplatElt != eltMask) 1471 isSplat = false; 1472 SplatElt = eltMask; 1473 } 1474 1475 newMask.push_back(eltMask); 1476 } 1477 1478 // If the result mask is equal to one of the original shuffle masks, 1479 // or is a splat, do the replacement. 1480 if (isSplat || newMask == LHSMask || newMask == RHSMask || newMask == Mask) { 1481 SmallVector<Constant*, 16> Elts; 1482 for (unsigned i = 0, e = newMask.size(); i != e; ++i) { 1483 if (newMask[i] < 0) { 1484 Elts.push_back(UndefValue::get(Int32Ty)); 1485 } else { 1486 Elts.push_back(ConstantInt::get(Int32Ty, newMask[i])); 1487 } 1488 } 1489 if (!newRHS) 1490 newRHS = UndefValue::get(newLHS->getType()); 1491 return new ShuffleVectorInst(newLHS, newRHS, ConstantVector::get(Elts)); 1492 } 1493 1494 // If the result mask is an identity, replace uses of this instruction with 1495 // corresponding argument. 1496 bool isLHSID, isRHSID; 1497 recognizeIdentityMask(newMask, isLHSID, isRHSID); 1498 if (isLHSID && VWidth == LHSOp0Width) return replaceInstUsesWith(SVI, newLHS); 1499 if (isRHSID && VWidth == RHSOp0Width) return replaceInstUsesWith(SVI, newRHS); 1500 1501 return MadeChange ? &SVI : nullptr; 1502 } 1503