1 //===------- VectorCombine.cpp - Optimize partial vector operations -------===// 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 pass optimizes scalar/vector interactions using target cost models. The 10 // transforms implemented here may not fit in traditional loop-based or SLP 11 // vectorization passes. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/Transforms/Vectorize/VectorCombine.h" 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/Analysis/BasicAliasAnalysis.h" 18 #include "llvm/Analysis/GlobalsModRef.h" 19 #include "llvm/Analysis/Loads.h" 20 #include "llvm/Analysis/TargetTransformInfo.h" 21 #include "llvm/Analysis/ValueTracking.h" 22 #include "llvm/Analysis/VectorUtils.h" 23 #include "llvm/IR/Dominators.h" 24 #include "llvm/IR/Function.h" 25 #include "llvm/IR/IRBuilder.h" 26 #include "llvm/IR/PatternMatch.h" 27 #include "llvm/InitializePasses.h" 28 #include "llvm/Pass.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Transforms/Utils/Local.h" 31 #include "llvm/Transforms/Vectorize.h" 32 33 using namespace llvm; 34 using namespace llvm::PatternMatch; 35 36 #define DEBUG_TYPE "vector-combine" 37 STATISTIC(NumVecLoad, "Number of vector loads formed"); 38 STATISTIC(NumVecCmp, "Number of vector compares formed"); 39 STATISTIC(NumVecBO, "Number of vector binops formed"); 40 STATISTIC(NumVecCmpBO, "Number of vector compare + binop formed"); 41 STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast"); 42 STATISTIC(NumScalarBO, "Number of scalar binops formed"); 43 STATISTIC(NumScalarCmp, "Number of scalar compares formed"); 44 45 static cl::opt<bool> DisableVectorCombine( 46 "disable-vector-combine", cl::init(false), cl::Hidden, 47 cl::desc("Disable all vector combine transforms")); 48 49 static cl::opt<bool> DisableBinopExtractShuffle( 50 "disable-binop-extract-shuffle", cl::init(false), cl::Hidden, 51 cl::desc("Disable binop extract to shuffle transforms")); 52 53 static const unsigned InvalidIndex = std::numeric_limits<unsigned>::max(); 54 55 namespace { 56 class VectorCombine { 57 public: 58 VectorCombine(Function &F, const TargetTransformInfo &TTI, 59 const DominatorTree &DT) 60 : F(F), Builder(F.getContext()), TTI(TTI), DT(DT) {} 61 62 bool run(); 63 64 private: 65 Function &F; 66 IRBuilder<> Builder; 67 const TargetTransformInfo &TTI; 68 const DominatorTree &DT; 69 70 bool vectorizeLoadInsert(Instruction &I); 71 ExtractElementInst *getShuffleExtract(ExtractElementInst *Ext0, 72 ExtractElementInst *Ext1, 73 unsigned PreferredExtractIndex) const; 74 bool isExtractExtractCheap(ExtractElementInst *Ext0, ExtractElementInst *Ext1, 75 unsigned Opcode, 76 ExtractElementInst *&ConvertToShuffle, 77 unsigned PreferredExtractIndex); 78 void foldExtExtCmp(ExtractElementInst *Ext0, ExtractElementInst *Ext1, 79 Instruction &I); 80 void foldExtExtBinop(ExtractElementInst *Ext0, ExtractElementInst *Ext1, 81 Instruction &I); 82 bool foldExtractExtract(Instruction &I); 83 bool foldBitcastShuf(Instruction &I); 84 bool scalarizeBinopOrCmp(Instruction &I); 85 bool foldExtractedCmps(Instruction &I); 86 }; 87 } // namespace 88 89 static void replaceValue(Value &Old, Value &New) { 90 Old.replaceAllUsesWith(&New); 91 New.takeName(&Old); 92 } 93 94 bool VectorCombine::vectorizeLoadInsert(Instruction &I) { 95 // Match insert of scalar load. 96 Value *Scalar; 97 if (!match(&I, m_InsertElt(m_Undef(), m_Value(Scalar), m_ZeroInt()))) 98 return false; 99 auto *Load = dyn_cast<LoadInst>(Scalar); 100 Type *ScalarTy = Scalar->getType(); 101 // Do not vectorize scalar load (widening) if atomic/volatile or under 102 // asan/hwasan/memtag/tsan. The widened load may load data from dirty regions 103 // or create data races non-existent in the source. 104 if (!Load || !Load->isSimple() || 105 Load->getFunction()->hasFnAttribute(Attribute::SanitizeMemTag) || 106 mustSuppressSpeculation(*Load)) 107 return false; 108 auto *Ty = dyn_cast<FixedVectorType>(I.getType()); 109 if (!Ty) 110 return false; 111 112 // TODO: Extend this to match GEP with constant offsets. 113 Value *PtrOp = Load->getPointerOperand()->stripPointerCasts(); 114 assert(isa<PointerType>(PtrOp->getType()) && "Expected a pointer type"); 115 116 unsigned MinVectorSize = TTI.getMinVectorRegisterBitWidth(); 117 uint64_t ScalarSize = ScalarTy->getPrimitiveSizeInBits(); 118 if (!ScalarSize || !MinVectorSize || MinVectorSize % ScalarSize != 0) 119 return false; 120 121 // Check safety of replacing the scalar load with a larger vector load. 122 unsigned MinVecNumElts = MinVectorSize / ScalarSize; 123 auto *MinVecTy = VectorType::get(ScalarTy, MinVecNumElts, false); 124 Align Alignment = Load->getAlign(); 125 const DataLayout &DL = I.getModule()->getDataLayout(); 126 if (!isSafeToLoadUnconditionally(PtrOp, MinVecTy, Alignment, DL, Load, &DT)) 127 return false; 128 129 unsigned AS = Load->getPointerAddressSpace(); 130 131 // Original pattern: insertelt undef, load [free casts of] ScalarPtr, 0 132 int OldCost = TTI.getMemoryOpCost(Instruction::Load, ScalarTy, Alignment, AS); 133 APInt DemandedElts = APInt::getOneBitSet(MinVecNumElts, 0); 134 OldCost += TTI.getScalarizationOverhead(MinVecTy, DemandedElts, true, false); 135 136 // New pattern: load VecPtr 137 int NewCost = TTI.getMemoryOpCost(Instruction::Load, MinVecTy, Alignment, AS); 138 139 // We can aggressively convert to the vector form because the backend can 140 // invert this transform if it does not result in a performance win. 141 if (OldCost < NewCost) 142 return false; 143 144 // It is safe and potentially profitable to load a vector directly: 145 // inselt undef, load Scalar, 0 --> load VecPtr 146 IRBuilder<> Builder(Load); 147 Value *CastedPtr = Builder.CreateBitCast(PtrOp, MinVecTy->getPointerTo(AS)); 148 Value *VecLd = Builder.CreateAlignedLoad(MinVecTy, CastedPtr, Alignment); 149 150 // If the insert type does not match the target's minimum vector type, 151 // use an identity shuffle to shrink/grow the vector. 152 if (Ty != MinVecTy) { 153 unsigned OutputNumElts = Ty->getNumElements(); 154 SmallVector<int, 16> Mask(OutputNumElts, UndefMaskElem); 155 for (unsigned i = 0; i < OutputNumElts && i < MinVecNumElts; ++i) 156 Mask[i] = i; 157 VecLd = Builder.CreateShuffleVector(VecLd, UndefValue::get(MinVecTy), Mask); 158 } 159 replaceValue(I, *VecLd); 160 ++NumVecLoad; 161 return true; 162 } 163 164 /// Determine which, if any, of the inputs should be replaced by a shuffle 165 /// followed by extract from a different index. 166 ExtractElementInst *VectorCombine::getShuffleExtract( 167 ExtractElementInst *Ext0, ExtractElementInst *Ext1, 168 unsigned PreferredExtractIndex = InvalidIndex) const { 169 assert(isa<ConstantInt>(Ext0->getIndexOperand()) && 170 isa<ConstantInt>(Ext1->getIndexOperand()) && 171 "Expected constant extract indexes"); 172 173 unsigned Index0 = cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue(); 174 unsigned Index1 = cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue(); 175 176 // If the extract indexes are identical, no shuffle is needed. 177 if (Index0 == Index1) 178 return nullptr; 179 180 Type *VecTy = Ext0->getVectorOperand()->getType(); 181 assert(VecTy == Ext1->getVectorOperand()->getType() && "Need matching types"); 182 int Cost0 = TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0); 183 int Cost1 = TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1); 184 185 // We are extracting from 2 different indexes, so one operand must be shuffled 186 // before performing a vector operation and/or extract. The more expensive 187 // extract will be replaced by a shuffle. 188 if (Cost0 > Cost1) 189 return Ext0; 190 if (Cost1 > Cost0) 191 return Ext1; 192 193 // If the costs are equal and there is a preferred extract index, shuffle the 194 // opposite operand. 195 if (PreferredExtractIndex == Index0) 196 return Ext1; 197 if (PreferredExtractIndex == Index1) 198 return Ext0; 199 200 // Otherwise, replace the extract with the higher index. 201 return Index0 > Index1 ? Ext0 : Ext1; 202 } 203 204 /// Compare the relative costs of 2 extracts followed by scalar operation vs. 205 /// vector operation(s) followed by extract. Return true if the existing 206 /// instructions are cheaper than a vector alternative. Otherwise, return false 207 /// and if one of the extracts should be transformed to a shufflevector, set 208 /// \p ConvertToShuffle to that extract instruction. 209 bool VectorCombine::isExtractExtractCheap(ExtractElementInst *Ext0, 210 ExtractElementInst *Ext1, 211 unsigned Opcode, 212 ExtractElementInst *&ConvertToShuffle, 213 unsigned PreferredExtractIndex) { 214 assert(isa<ConstantInt>(Ext0->getOperand(1)) && 215 isa<ConstantInt>(Ext1->getOperand(1)) && 216 "Expected constant extract indexes"); 217 Type *ScalarTy = Ext0->getType(); 218 auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType()); 219 int ScalarOpCost, VectorOpCost; 220 221 // Get cost estimates for scalar and vector versions of the operation. 222 bool IsBinOp = Instruction::isBinaryOp(Opcode); 223 if (IsBinOp) { 224 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy); 225 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy); 226 } else { 227 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) && 228 "Expected a compare"); 229 ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy, 230 CmpInst::makeCmpResultType(ScalarTy)); 231 VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy, 232 CmpInst::makeCmpResultType(VecTy)); 233 } 234 235 // Get cost estimates for the extract elements. These costs will factor into 236 // both sequences. 237 unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue(); 238 unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue(); 239 240 int Extract0Cost = 241 TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext0Index); 242 int Extract1Cost = 243 TTI.getVectorInstrCost(Instruction::ExtractElement, VecTy, Ext1Index); 244 245 // A more expensive extract will always be replaced by a splat shuffle. 246 // For example, if Ext0 is more expensive: 247 // opcode (extelt V0, Ext0), (ext V1, Ext1) --> 248 // extelt (opcode (splat V0, Ext0), V1), Ext1 249 // TODO: Evaluate whether that always results in lowest cost. Alternatively, 250 // check the cost of creating a broadcast shuffle and shuffling both 251 // operands to element 0. 252 int CheapExtractCost = std::min(Extract0Cost, Extract1Cost); 253 254 // Extra uses of the extracts mean that we include those costs in the 255 // vector total because those instructions will not be eliminated. 256 int OldCost, NewCost; 257 if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) { 258 // Handle a special case. If the 2 extracts are identical, adjust the 259 // formulas to account for that. The extra use charge allows for either the 260 // CSE'd pattern or an unoptimized form with identical values: 261 // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C 262 bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2) 263 : !Ext0->hasOneUse() || !Ext1->hasOneUse(); 264 OldCost = CheapExtractCost + ScalarOpCost; 265 NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost; 266 } else { 267 // Handle the general case. Each extract is actually a different value: 268 // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C 269 OldCost = Extract0Cost + Extract1Cost + ScalarOpCost; 270 NewCost = VectorOpCost + CheapExtractCost + 271 !Ext0->hasOneUse() * Extract0Cost + 272 !Ext1->hasOneUse() * Extract1Cost; 273 } 274 275 ConvertToShuffle = getShuffleExtract(Ext0, Ext1, PreferredExtractIndex); 276 if (ConvertToShuffle) { 277 if (IsBinOp && DisableBinopExtractShuffle) 278 return true; 279 280 // If we are extracting from 2 different indexes, then one operand must be 281 // shuffled before performing the vector operation. The shuffle mask is 282 // undefined except for 1 lane that is being translated to the remaining 283 // extraction lane. Therefore, it is a splat shuffle. Ex: 284 // ShufMask = { undef, undef, 0, undef } 285 // TODO: The cost model has an option for a "broadcast" shuffle 286 // (splat-from-element-0), but no option for a more general splat. 287 NewCost += 288 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy); 289 } 290 291 // Aggressively form a vector op if the cost is equal because the transform 292 // may enable further optimization. 293 // Codegen can reverse this transform (scalarize) if it was not profitable. 294 return OldCost < NewCost; 295 } 296 297 /// Create a shuffle that translates (shifts) 1 element from the input vector 298 /// to a new element location. 299 static Value *createShiftShuffle(Value *Vec, unsigned OldIndex, 300 unsigned NewIndex, IRBuilder<> &Builder) { 301 // The shuffle mask is undefined except for 1 lane that is being translated 302 // to the new element index. Example for OldIndex == 2 and NewIndex == 0: 303 // ShufMask = { 2, undef, undef, undef } 304 auto *VecTy = cast<FixedVectorType>(Vec->getType()); 305 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), UndefMaskElem); 306 ShufMask[NewIndex] = OldIndex; 307 Value *Undef = UndefValue::get(VecTy); 308 return Builder.CreateShuffleVector(Vec, Undef, ShufMask, "shift"); 309 } 310 311 /// Given an extract element instruction with constant index operand, shuffle 312 /// the source vector (shift the scalar element) to a NewIndex for extraction. 313 /// Return null if the input can be constant folded, so that we are not creating 314 /// unnecessary instructions. 315 static ExtractElementInst *translateExtract(ExtractElementInst *ExtElt, 316 unsigned NewIndex, 317 IRBuilder<> &Builder) { 318 // If the extract can be constant-folded, this code is unsimplified. Defer 319 // to other passes to handle that. 320 Value *X = ExtElt->getVectorOperand(); 321 Value *C = ExtElt->getIndexOperand(); 322 assert(isa<ConstantInt>(C) && "Expected a constant index operand"); 323 if (isa<Constant>(X)) 324 return nullptr; 325 326 Value *Shuf = createShiftShuffle(X, cast<ConstantInt>(C)->getZExtValue(), 327 NewIndex, Builder); 328 return cast<ExtractElementInst>(Builder.CreateExtractElement(Shuf, NewIndex)); 329 } 330 331 /// Try to reduce extract element costs by converting scalar compares to vector 332 /// compares followed by extract. 333 /// cmp (ext0 V0, C), (ext1 V1, C) 334 void VectorCombine::foldExtExtCmp(ExtractElementInst *Ext0, 335 ExtractElementInst *Ext1, Instruction &I) { 336 assert(isa<CmpInst>(&I) && "Expected a compare"); 337 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() == 338 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() && 339 "Expected matching constant extract indexes"); 340 341 // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C 342 ++NumVecCmp; 343 CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate(); 344 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand(); 345 Value *VecCmp = Builder.CreateCmp(Pred, V0, V1); 346 Value *NewExt = Builder.CreateExtractElement(VecCmp, Ext0->getIndexOperand()); 347 replaceValue(I, *NewExt); 348 } 349 350 /// Try to reduce extract element costs by converting scalar binops to vector 351 /// binops followed by extract. 352 /// bo (ext0 V0, C), (ext1 V1, C) 353 void VectorCombine::foldExtExtBinop(ExtractElementInst *Ext0, 354 ExtractElementInst *Ext1, Instruction &I) { 355 assert(isa<BinaryOperator>(&I) && "Expected a binary operator"); 356 assert(cast<ConstantInt>(Ext0->getIndexOperand())->getZExtValue() == 357 cast<ConstantInt>(Ext1->getIndexOperand())->getZExtValue() && 358 "Expected matching constant extract indexes"); 359 360 // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C 361 ++NumVecBO; 362 Value *V0 = Ext0->getVectorOperand(), *V1 = Ext1->getVectorOperand(); 363 Value *VecBO = 364 Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1); 365 366 // All IR flags are safe to back-propagate because any potential poison 367 // created in unused vector elements is discarded by the extract. 368 if (auto *VecBOInst = dyn_cast<Instruction>(VecBO)) 369 VecBOInst->copyIRFlags(&I); 370 371 Value *NewExt = Builder.CreateExtractElement(VecBO, Ext0->getIndexOperand()); 372 replaceValue(I, *NewExt); 373 } 374 375 /// Match an instruction with extracted vector operands. 376 bool VectorCombine::foldExtractExtract(Instruction &I) { 377 // It is not safe to transform things like div, urem, etc. because we may 378 // create undefined behavior when executing those on unknown vector elements. 379 if (!isSafeToSpeculativelyExecute(&I)) 380 return false; 381 382 Instruction *I0, *I1; 383 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE; 384 if (!match(&I, m_Cmp(Pred, m_Instruction(I0), m_Instruction(I1))) && 385 !match(&I, m_BinOp(m_Instruction(I0), m_Instruction(I1)))) 386 return false; 387 388 Value *V0, *V1; 389 uint64_t C0, C1; 390 if (!match(I0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) || 391 !match(I1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) || 392 V0->getType() != V1->getType()) 393 return false; 394 395 // If the scalar value 'I' is going to be re-inserted into a vector, then try 396 // to create an extract to that same element. The extract/insert can be 397 // reduced to a "select shuffle". 398 // TODO: If we add a larger pattern match that starts from an insert, this 399 // probably becomes unnecessary. 400 auto *Ext0 = cast<ExtractElementInst>(I0); 401 auto *Ext1 = cast<ExtractElementInst>(I1); 402 uint64_t InsertIndex = InvalidIndex; 403 if (I.hasOneUse()) 404 match(I.user_back(), 405 m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex))); 406 407 ExtractElementInst *ExtractToChange; 408 if (isExtractExtractCheap(Ext0, Ext1, I.getOpcode(), ExtractToChange, 409 InsertIndex)) 410 return false; 411 412 if (ExtractToChange) { 413 unsigned CheapExtractIdx = ExtractToChange == Ext0 ? C1 : C0; 414 ExtractElementInst *NewExtract = 415 translateExtract(ExtractToChange, CheapExtractIdx, Builder); 416 if (!NewExtract) 417 return false; 418 if (ExtractToChange == Ext0) 419 Ext0 = NewExtract; 420 else 421 Ext1 = NewExtract; 422 } 423 424 if (Pred != CmpInst::BAD_ICMP_PREDICATE) 425 foldExtExtCmp(Ext0, Ext1, I); 426 else 427 foldExtExtBinop(Ext0, Ext1, I); 428 429 return true; 430 } 431 432 /// If this is a bitcast of a shuffle, try to bitcast the source vector to the 433 /// destination type followed by shuffle. This can enable further transforms by 434 /// moving bitcasts or shuffles together. 435 bool VectorCombine::foldBitcastShuf(Instruction &I) { 436 Value *V; 437 ArrayRef<int> Mask; 438 if (!match(&I, m_BitCast( 439 m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask)))))) 440 return false; 441 442 // 1) Do not fold bitcast shuffle for scalable type. First, shuffle cost for 443 // scalable type is unknown; Second, we cannot reason if the narrowed shuffle 444 // mask for scalable type is a splat or not. 445 // 2) Disallow non-vector casts and length-changing shuffles. 446 // TODO: We could allow any shuffle. 447 auto *DestTy = dyn_cast<FixedVectorType>(I.getType()); 448 auto *SrcTy = dyn_cast<FixedVectorType>(V->getType()); 449 if (!SrcTy || !DestTy || I.getOperand(0)->getType() != SrcTy) 450 return false; 451 452 // The new shuffle must not cost more than the old shuffle. The bitcast is 453 // moved ahead of the shuffle, so assume that it has the same cost as before. 454 if (TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, DestTy) > 455 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy)) 456 return false; 457 458 unsigned DestNumElts = DestTy->getNumElements(); 459 unsigned SrcNumElts = SrcTy->getNumElements(); 460 SmallVector<int, 16> NewMask; 461 if (SrcNumElts <= DestNumElts) { 462 // The bitcast is from wide to narrow/equal elements. The shuffle mask can 463 // always be expanded to the equivalent form choosing narrower elements. 464 assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask"); 465 unsigned ScaleFactor = DestNumElts / SrcNumElts; 466 narrowShuffleMaskElts(ScaleFactor, Mask, NewMask); 467 } else { 468 // The bitcast is from narrow elements to wide elements. The shuffle mask 469 // must choose consecutive elements to allow casting first. 470 assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask"); 471 unsigned ScaleFactor = SrcNumElts / DestNumElts; 472 if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask)) 473 return false; 474 } 475 // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC' 476 ++NumShufOfBitcast; 477 Value *CastV = Builder.CreateBitCast(V, DestTy); 478 Value *Shuf = 479 Builder.CreateShuffleVector(CastV, UndefValue::get(DestTy), NewMask); 480 replaceValue(I, *Shuf); 481 return true; 482 } 483 484 /// Match a vector binop or compare instruction with at least one inserted 485 /// scalar operand and convert to scalar binop/cmp followed by insertelement. 486 bool VectorCombine::scalarizeBinopOrCmp(Instruction &I) { 487 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE; 488 Value *Ins0, *Ins1; 489 if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1))) && 490 !match(&I, m_Cmp(Pred, m_Value(Ins0), m_Value(Ins1)))) 491 return false; 492 493 // Do not convert the vector condition of a vector select into a scalar 494 // condition. That may cause problems for codegen because of differences in 495 // boolean formats and register-file transfers. 496 // TODO: Can we account for that in the cost model? 497 bool IsCmp = Pred != CmpInst::Predicate::BAD_ICMP_PREDICATE; 498 if (IsCmp) 499 for (User *U : I.users()) 500 if (match(U, m_Select(m_Specific(&I), m_Value(), m_Value()))) 501 return false; 502 503 // Match against one or both scalar values being inserted into constant 504 // vectors: 505 // vec_op VecC0, (inselt VecC1, V1, Index) 506 // vec_op (inselt VecC0, V0, Index), VecC1 507 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) 508 // TODO: Deal with mismatched index constants and variable indexes? 509 Constant *VecC0 = nullptr, *VecC1 = nullptr; 510 Value *V0 = nullptr, *V1 = nullptr; 511 uint64_t Index0 = 0, Index1 = 0; 512 if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0), 513 m_ConstantInt(Index0))) && 514 !match(Ins0, m_Constant(VecC0))) 515 return false; 516 if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1), 517 m_ConstantInt(Index1))) && 518 !match(Ins1, m_Constant(VecC1))) 519 return false; 520 521 bool IsConst0 = !V0; 522 bool IsConst1 = !V1; 523 if (IsConst0 && IsConst1) 524 return false; 525 if (!IsConst0 && !IsConst1 && Index0 != Index1) 526 return false; 527 528 // Bail for single insertion if it is a load. 529 // TODO: Handle this once getVectorInstrCost can cost for load/stores. 530 auto *I0 = dyn_cast_or_null<Instruction>(V0); 531 auto *I1 = dyn_cast_or_null<Instruction>(V1); 532 if ((IsConst0 && I1 && I1->mayReadFromMemory()) || 533 (IsConst1 && I0 && I0->mayReadFromMemory())) 534 return false; 535 536 uint64_t Index = IsConst0 ? Index1 : Index0; 537 Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType(); 538 Type *VecTy = I.getType(); 539 assert(VecTy->isVectorTy() && 540 (IsConst0 || IsConst1 || V0->getType() == V1->getType()) && 541 (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy() || 542 ScalarTy->isPointerTy()) && 543 "Unexpected types for insert element into binop or cmp"); 544 545 unsigned Opcode = I.getOpcode(); 546 int ScalarOpCost, VectorOpCost; 547 if (IsCmp) { 548 ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy); 549 VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy); 550 } else { 551 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy); 552 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy); 553 } 554 555 // Get cost estimate for the insert element. This cost will factor into 556 // both sequences. 557 int InsertCost = 558 TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index); 559 int OldCost = (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + 560 VectorOpCost; 561 int NewCost = ScalarOpCost + InsertCost + 562 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) + 563 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost); 564 565 // We want to scalarize unless the vector variant actually has lower cost. 566 if (OldCost < NewCost) 567 return false; 568 569 // vec_op (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) --> 570 // inselt NewVecC, (scalar_op V0, V1), Index 571 if (IsCmp) 572 ++NumScalarCmp; 573 else 574 ++NumScalarBO; 575 576 // For constant cases, extract the scalar element, this should constant fold. 577 if (IsConst0) 578 V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index)); 579 if (IsConst1) 580 V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index)); 581 582 Value *Scalar = 583 IsCmp ? Builder.CreateCmp(Pred, V0, V1) 584 : Builder.CreateBinOp((Instruction::BinaryOps)Opcode, V0, V1); 585 586 Scalar->setName(I.getName() + ".scalar"); 587 588 // All IR flags are safe to back-propagate. There is no potential for extra 589 // poison to be created by the scalar instruction. 590 if (auto *ScalarInst = dyn_cast<Instruction>(Scalar)) 591 ScalarInst->copyIRFlags(&I); 592 593 // Fold the vector constants in the original vectors into a new base vector. 594 Constant *NewVecC = IsCmp ? ConstantExpr::getCompare(Pred, VecC0, VecC1) 595 : ConstantExpr::get(Opcode, VecC0, VecC1); 596 Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index); 597 replaceValue(I, *Insert); 598 return true; 599 } 600 601 /// Try to combine a scalar binop + 2 scalar compares of extracted elements of 602 /// a vector into vector operations followed by extract. Note: The SLP pass 603 /// may miss this pattern because of implementation problems. 604 bool VectorCombine::foldExtractedCmps(Instruction &I) { 605 // We are looking for a scalar binop of booleans. 606 // binop i1 (cmp Pred I0, C0), (cmp Pred I1, C1) 607 if (!I.isBinaryOp() || !I.getType()->isIntegerTy(1)) 608 return false; 609 610 // The compare predicates should match, and each compare should have a 611 // constant operand. 612 // TODO: Relax the one-use constraints. 613 Value *B0 = I.getOperand(0), *B1 = I.getOperand(1); 614 Instruction *I0, *I1; 615 Constant *C0, *C1; 616 CmpInst::Predicate P0, P1; 617 if (!match(B0, m_OneUse(m_Cmp(P0, m_Instruction(I0), m_Constant(C0)))) || 618 !match(B1, m_OneUse(m_Cmp(P1, m_Instruction(I1), m_Constant(C1)))) || 619 P0 != P1) 620 return false; 621 622 // The compare operands must be extracts of the same vector with constant 623 // extract indexes. 624 // TODO: Relax the one-use constraints. 625 Value *X; 626 uint64_t Index0, Index1; 627 if (!match(I0, m_OneUse(m_ExtractElt(m_Value(X), m_ConstantInt(Index0)))) || 628 !match(I1, m_OneUse(m_ExtractElt(m_Specific(X), m_ConstantInt(Index1))))) 629 return false; 630 631 auto *Ext0 = cast<ExtractElementInst>(I0); 632 auto *Ext1 = cast<ExtractElementInst>(I1); 633 ExtractElementInst *ConvertToShuf = getShuffleExtract(Ext0, Ext1); 634 if (!ConvertToShuf) 635 return false; 636 637 // The original scalar pattern is: 638 // binop i1 (cmp Pred (ext X, Index0), C0), (cmp Pred (ext X, Index1), C1) 639 CmpInst::Predicate Pred = P0; 640 unsigned CmpOpcode = CmpInst::isFPPredicate(Pred) ? Instruction::FCmp 641 : Instruction::ICmp; 642 auto *VecTy = dyn_cast<FixedVectorType>(X->getType()); 643 if (!VecTy) 644 return false; 645 646 int OldCost = TTI.getVectorInstrCost(Ext0->getOpcode(), VecTy, Index0); 647 OldCost += TTI.getVectorInstrCost(Ext1->getOpcode(), VecTy, Index1); 648 OldCost += TTI.getCmpSelInstrCost(CmpOpcode, I0->getType()) * 2; 649 OldCost += TTI.getArithmeticInstrCost(I.getOpcode(), I.getType()); 650 651 // The proposed vector pattern is: 652 // vcmp = cmp Pred X, VecC 653 // ext (binop vNi1 vcmp, (shuffle vcmp, Index1)), Index0 654 int CheapIndex = ConvertToShuf == Ext0 ? Index1 : Index0; 655 int ExpensiveIndex = ConvertToShuf == Ext0 ? Index0 : Index1; 656 auto *CmpTy = cast<FixedVectorType>(CmpInst::makeCmpResultType(X->getType())); 657 int NewCost = TTI.getCmpSelInstrCost(CmpOpcode, X->getType()); 658 NewCost += 659 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, CmpTy); 660 NewCost += TTI.getArithmeticInstrCost(I.getOpcode(), CmpTy); 661 NewCost += TTI.getVectorInstrCost(Ext0->getOpcode(), CmpTy, CheapIndex); 662 663 // Aggressively form vector ops if the cost is equal because the transform 664 // may enable further optimization. 665 // Codegen can reverse this transform (scalarize) if it was not profitable. 666 if (OldCost < NewCost) 667 return false; 668 669 // Create a vector constant from the 2 scalar constants. 670 SmallVector<Constant *, 32> CmpC(VecTy->getNumElements(), 671 UndefValue::get(VecTy->getElementType())); 672 CmpC[Index0] = C0; 673 CmpC[Index1] = C1; 674 Value *VCmp = Builder.CreateCmp(Pred, X, ConstantVector::get(CmpC)); 675 676 Value *Shuf = createShiftShuffle(VCmp, ExpensiveIndex, CheapIndex, Builder); 677 Value *VecLogic = Builder.CreateBinOp(cast<BinaryOperator>(I).getOpcode(), 678 VCmp, Shuf); 679 Value *NewExt = Builder.CreateExtractElement(VecLogic, CheapIndex); 680 replaceValue(I, *NewExt); 681 ++NumVecCmpBO; 682 return true; 683 } 684 685 /// This is the entry point for all transforms. Pass manager differences are 686 /// handled in the callers of this function. 687 bool VectorCombine::run() { 688 if (DisableVectorCombine) 689 return false; 690 691 // Don't attempt vectorization if the target does not support vectors. 692 if (!TTI.getNumberOfRegisters(TTI.getRegisterClassForType(/*Vector*/ true))) 693 return false; 694 695 bool MadeChange = false; 696 for (BasicBlock &BB : F) { 697 // Ignore unreachable basic blocks. 698 if (!DT.isReachableFromEntry(&BB)) 699 continue; 700 // Do not delete instructions under here and invalidate the iterator. 701 // Walk the block forwards to enable simple iterative chains of transforms. 702 // TODO: It could be more efficient to remove dead instructions 703 // iteratively in this loop rather than waiting until the end. 704 for (Instruction &I : BB) { 705 if (isa<DbgInfoIntrinsic>(I)) 706 continue; 707 Builder.SetInsertPoint(&I); 708 MadeChange |= vectorizeLoadInsert(I); 709 MadeChange |= foldExtractExtract(I); 710 MadeChange |= foldBitcastShuf(I); 711 MadeChange |= scalarizeBinopOrCmp(I); 712 MadeChange |= foldExtractedCmps(I); 713 } 714 } 715 716 // We're done with transforms, so remove dead instructions. 717 if (MadeChange) 718 for (BasicBlock &BB : F) 719 SimplifyInstructionsInBlock(&BB); 720 721 return MadeChange; 722 } 723 724 // Pass manager boilerplate below here. 725 726 namespace { 727 class VectorCombineLegacyPass : public FunctionPass { 728 public: 729 static char ID; 730 VectorCombineLegacyPass() : FunctionPass(ID) { 731 initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry()); 732 } 733 734 void getAnalysisUsage(AnalysisUsage &AU) const override { 735 AU.addRequired<DominatorTreeWrapperPass>(); 736 AU.addRequired<TargetTransformInfoWrapperPass>(); 737 AU.setPreservesCFG(); 738 AU.addPreserved<DominatorTreeWrapperPass>(); 739 AU.addPreserved<GlobalsAAWrapperPass>(); 740 AU.addPreserved<AAResultsWrapperPass>(); 741 AU.addPreserved<BasicAAWrapperPass>(); 742 FunctionPass::getAnalysisUsage(AU); 743 } 744 745 bool runOnFunction(Function &F) override { 746 if (skipFunction(F)) 747 return false; 748 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 749 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 750 VectorCombine Combiner(F, TTI, DT); 751 return Combiner.run(); 752 } 753 }; 754 } // namespace 755 756 char VectorCombineLegacyPass::ID = 0; 757 INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine", 758 "Optimize scalar/vector ops", false, 759 false) 760 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 761 INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine", 762 "Optimize scalar/vector ops", false, false) 763 Pass *llvm::createVectorCombinePass() { 764 return new VectorCombineLegacyPass(); 765 } 766 767 PreservedAnalyses VectorCombinePass::run(Function &F, 768 FunctionAnalysisManager &FAM) { 769 TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F); 770 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F); 771 VectorCombine Combiner(F, TTI, DT); 772 if (!Combiner.run()) 773 return PreservedAnalyses::all(); 774 PreservedAnalyses PA; 775 PA.preserveSet<CFGAnalyses>(); 776 PA.preserve<GlobalsAA>(); 777 PA.preserve<AAManager>(); 778 PA.preserve<BasicAA>(); 779 return PA; 780 } 781