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/TargetTransformInfo.h" 20 #include "llvm/Analysis/ValueTracking.h" 21 #include "llvm/Analysis/VectorUtils.h" 22 #include "llvm/IR/Dominators.h" 23 #include "llvm/IR/Function.h" 24 #include "llvm/IR/IRBuilder.h" 25 #include "llvm/IR/PatternMatch.h" 26 #include "llvm/InitializePasses.h" 27 #include "llvm/Pass.h" 28 #include "llvm/Support/CommandLine.h" 29 #include "llvm/Transforms/Utils/Local.h" 30 #include "llvm/Transforms/Vectorize.h" 31 32 using namespace llvm; 33 using namespace llvm::PatternMatch; 34 35 #define DEBUG_TYPE "vector-combine" 36 STATISTIC(NumVecCmp, "Number of vector compares formed"); 37 STATISTIC(NumVecBO, "Number of vector binops formed"); 38 STATISTIC(NumShufOfBitcast, "Number of shuffles moved after bitcast"); 39 STATISTIC(NumScalarBO, "Number of scalar binops formed"); 40 41 static cl::opt<bool> DisableVectorCombine( 42 "disable-vector-combine", cl::init(false), cl::Hidden, 43 cl::desc("Disable all vector combine transforms")); 44 45 static cl::opt<bool> DisableBinopExtractShuffle( 46 "disable-binop-extract-shuffle", cl::init(false), cl::Hidden, 47 cl::desc("Disable binop extract to shuffle transforms")); 48 49 50 /// Compare the relative costs of 2 extracts followed by scalar operation vs. 51 /// vector operation(s) followed by extract. Return true if the existing 52 /// instructions are cheaper than a vector alternative. Otherwise, return false 53 /// and if one of the extracts should be transformed to a shufflevector, set 54 /// \p ConvertToShuffle to that extract instruction. 55 static bool isExtractExtractCheap(Instruction *Ext0, Instruction *Ext1, 56 unsigned Opcode, 57 const TargetTransformInfo &TTI, 58 Instruction *&ConvertToShuffle, 59 unsigned PreferredExtractIndex) { 60 assert(isa<ConstantInt>(Ext0->getOperand(1)) && 61 isa<ConstantInt>(Ext1->getOperand(1)) && 62 "Expected constant extract indexes"); 63 Type *ScalarTy = Ext0->getType(); 64 auto *VecTy = cast<VectorType>(Ext0->getOperand(0)->getType()); 65 int ScalarOpCost, VectorOpCost; 66 67 // Get cost estimates for scalar and vector versions of the operation. 68 bool IsBinOp = Instruction::isBinaryOp(Opcode); 69 if (IsBinOp) { 70 ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy); 71 VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy); 72 } else { 73 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) && 74 "Expected a compare"); 75 ScalarOpCost = TTI.getCmpSelInstrCost(Opcode, ScalarTy, 76 CmpInst::makeCmpResultType(ScalarTy)); 77 VectorOpCost = TTI.getCmpSelInstrCost(Opcode, VecTy, 78 CmpInst::makeCmpResultType(VecTy)); 79 } 80 81 // Get cost estimates for the extract elements. These costs will factor into 82 // both sequences. 83 unsigned Ext0Index = cast<ConstantInt>(Ext0->getOperand(1))->getZExtValue(); 84 unsigned Ext1Index = cast<ConstantInt>(Ext1->getOperand(1))->getZExtValue(); 85 86 int Extract0Cost = TTI.getVectorInstrCost(Instruction::ExtractElement, 87 VecTy, Ext0Index); 88 int Extract1Cost = TTI.getVectorInstrCost(Instruction::ExtractElement, 89 VecTy, Ext1Index); 90 91 // A more expensive extract will always be replaced by a splat shuffle. 92 // For example, if Ext0 is more expensive: 93 // opcode (extelt V0, Ext0), (ext V1, Ext1) --> 94 // extelt (opcode (splat V0, Ext0), V1), Ext1 95 // TODO: Evaluate whether that always results in lowest cost. Alternatively, 96 // check the cost of creating a broadcast shuffle and shuffling both 97 // operands to element 0. 98 int CheapExtractCost = std::min(Extract0Cost, Extract1Cost); 99 100 // Extra uses of the extracts mean that we include those costs in the 101 // vector total because those instructions will not be eliminated. 102 int OldCost, NewCost; 103 if (Ext0->getOperand(0) == Ext1->getOperand(0) && Ext0Index == Ext1Index) { 104 // Handle a special case. If the 2 extracts are identical, adjust the 105 // formulas to account for that. The extra use charge allows for either the 106 // CSE'd pattern or an unoptimized form with identical values: 107 // opcode (extelt V, C), (extelt V, C) --> extelt (opcode V, V), C 108 bool HasUseTax = Ext0 == Ext1 ? !Ext0->hasNUses(2) 109 : !Ext0->hasOneUse() || !Ext1->hasOneUse(); 110 OldCost = CheapExtractCost + ScalarOpCost; 111 NewCost = VectorOpCost + CheapExtractCost + HasUseTax * CheapExtractCost; 112 } else { 113 // Handle the general case. Each extract is actually a different value: 114 // opcode (extelt V0, C0), (extelt V1, C1) --> extelt (opcode V0, V1), C 115 OldCost = Extract0Cost + Extract1Cost + ScalarOpCost; 116 NewCost = VectorOpCost + CheapExtractCost + 117 !Ext0->hasOneUse() * Extract0Cost + 118 !Ext1->hasOneUse() * Extract1Cost; 119 } 120 121 if (Ext0Index == Ext1Index) { 122 // If the extract indexes are identical, no shuffle is needed. 123 ConvertToShuffle = nullptr; 124 } else { 125 if (IsBinOp && DisableBinopExtractShuffle) 126 return true; 127 128 // If we are extracting from 2 different indexes, then one operand must be 129 // shuffled before performing the vector operation. The shuffle mask is 130 // undefined except for 1 lane that is being translated to the remaining 131 // extraction lane. Therefore, it is a splat shuffle. Ex: 132 // ShufMask = { undef, undef, 0, undef } 133 // TODO: The cost model has an option for a "broadcast" shuffle 134 // (splat-from-element-0), but no option for a more general splat. 135 NewCost += 136 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy); 137 138 // The more expensive extract will be replaced by a shuffle. If the costs 139 // are equal and there is a preferred extract index, shuffle the opposite 140 // operand. Otherwise, replace the extract with the higher index. 141 if (Extract0Cost > Extract1Cost) 142 ConvertToShuffle = Ext0; 143 else if (Extract1Cost > Extract0Cost) 144 ConvertToShuffle = Ext1; 145 else if (PreferredExtractIndex == Ext0Index) 146 ConvertToShuffle = Ext1; 147 else if (PreferredExtractIndex == Ext1Index) 148 ConvertToShuffle = Ext0; 149 else 150 ConvertToShuffle = Ext0Index > Ext1Index ? Ext0 : Ext1; 151 } 152 153 // Aggressively form a vector op if the cost is equal because the transform 154 // may enable further optimization. 155 // Codegen can reverse this transform (scalarize) if it was not profitable. 156 return OldCost < NewCost; 157 } 158 159 /// Try to reduce extract element costs by converting scalar compares to vector 160 /// compares followed by extract. 161 /// cmp (ext0 V0, C), (ext1 V1, C) 162 static void foldExtExtCmp(Instruction *Ext0, Instruction *Ext1, 163 Instruction &I) { 164 assert(isa<CmpInst>(&I) && "Expected a compare"); 165 166 // cmp Pred (extelt V0, C), (extelt V1, C) --> extelt (cmp Pred V0, V1), C 167 ++NumVecCmp; 168 IRBuilder<> Builder(&I); 169 CmpInst::Predicate Pred = cast<CmpInst>(&I)->getPredicate(); 170 Value *V0 = Ext0->getOperand(0), *V1 = Ext1->getOperand(0); 171 Value *VecCmp = 172 Ext0->getType()->isFloatingPointTy() ? Builder.CreateFCmp(Pred, V0, V1) 173 : Builder.CreateICmp(Pred, V0, V1); 174 Value *Extract = Builder.CreateExtractElement(VecCmp, Ext0->getOperand(1)); 175 I.replaceAllUsesWith(Extract); 176 } 177 178 /// Try to reduce extract element costs by converting scalar binops to vector 179 /// binops followed by extract. 180 /// bo (ext0 V0, C), (ext1 V1, C) 181 static void foldExtExtBinop(Instruction *Ext0, Instruction *Ext1, 182 Instruction &I) { 183 assert(isa<BinaryOperator>(&I) && "Expected a binary operator"); 184 185 // bo (extelt V0, C), (extelt V1, C) --> extelt (bo V0, V1), C 186 ++NumVecBO; 187 IRBuilder<> Builder(&I); 188 Value *V0 = Ext0->getOperand(0), *V1 = Ext1->getOperand(0); 189 Value *VecBO = 190 Builder.CreateBinOp(cast<BinaryOperator>(&I)->getOpcode(), V0, V1); 191 192 // All IR flags are safe to back-propagate because any potential poison 193 // created in unused vector elements is discarded by the extract. 194 if (auto *VecBOInst = dyn_cast<Instruction>(VecBO)) 195 VecBOInst->copyIRFlags(&I); 196 197 Value *Extract = Builder.CreateExtractElement(VecBO, Ext0->getOperand(1)); 198 I.replaceAllUsesWith(Extract); 199 } 200 201 /// Match an instruction with extracted vector operands. 202 static bool foldExtractExtract(Instruction &I, const TargetTransformInfo &TTI) { 203 // It is not safe to transform things like div, urem, etc. because we may 204 // create undefined behavior when executing those on unknown vector elements. 205 if (!isSafeToSpeculativelyExecute(&I)) 206 return false; 207 208 Instruction *Ext0, *Ext1; 209 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE; 210 if (!match(&I, m_Cmp(Pred, m_Instruction(Ext0), m_Instruction(Ext1))) && 211 !match(&I, m_BinOp(m_Instruction(Ext0), m_Instruction(Ext1)))) 212 return false; 213 214 Value *V0, *V1; 215 uint64_t C0, C1; 216 if (!match(Ext0, m_ExtractElt(m_Value(V0), m_ConstantInt(C0))) || 217 !match(Ext1, m_ExtractElt(m_Value(V1), m_ConstantInt(C1))) || 218 V0->getType() != V1->getType()) 219 return false; 220 221 // If the scalar value 'I' is going to be re-inserted into a vector, then try 222 // to create an extract to that same element. The extract/insert can be 223 // reduced to a "select shuffle". 224 // TODO: If we add a larger pattern match that starts from an insert, this 225 // probably becomes unnecessary. 226 uint64_t InsertIndex = std::numeric_limits<uint64_t>::max(); 227 if (I.hasOneUse()) 228 match(I.user_back(), 229 m_InsertElt(m_Value(), m_Value(), m_ConstantInt(InsertIndex))); 230 231 Instruction *ConvertToShuffle; 232 if (isExtractExtractCheap(Ext0, Ext1, I.getOpcode(), TTI, ConvertToShuffle, 233 InsertIndex)) 234 return false; 235 236 if (ConvertToShuffle) { 237 // The shuffle mask is undefined except for 1 lane that is being translated 238 // to the cheap extraction lane. Example: 239 // ShufMask = { 2, undef, undef, undef } 240 uint64_t SplatIndex = ConvertToShuffle == Ext0 ? C0 : C1; 241 uint64_t CheapExtIndex = ConvertToShuffle == Ext0 ? C1 : C0; 242 auto *VecTy = cast<VectorType>(V0->getType()); 243 SmallVector<int, 32> ShufMask(VecTy->getNumElements(), -1); 244 ShufMask[CheapExtIndex] = SplatIndex; 245 IRBuilder<> Builder(ConvertToShuffle); 246 247 // extelt X, C --> extelt (splat X), C' 248 Value *Shuf = Builder.CreateShuffleVector(ConvertToShuffle->getOperand(0), 249 UndefValue::get(VecTy), ShufMask); 250 Value *NewExt = Builder.CreateExtractElement(Shuf, CheapExtIndex); 251 if (ConvertToShuffle == Ext0) 252 Ext0 = cast<Instruction>(NewExt); 253 else 254 Ext1 = cast<Instruction>(NewExt); 255 } 256 257 if (Pred != CmpInst::BAD_ICMP_PREDICATE) 258 foldExtExtCmp(Ext0, Ext1, I); 259 else 260 foldExtExtBinop(Ext0, Ext1, I); 261 262 return true; 263 } 264 265 /// If this is a bitcast of a shuffle, try to bitcast the source vector to the 266 /// destination type followed by shuffle. This can enable further transforms by 267 /// moving bitcasts or shuffles together. 268 static bool foldBitcastShuf(Instruction &I, const TargetTransformInfo &TTI) { 269 Value *V; 270 ArrayRef<int> Mask; 271 if (!match(&I, m_BitCast( 272 m_OneUse(m_Shuffle(m_Value(V), m_Undef(), m_Mask(Mask)))))) 273 return false; 274 275 // Disallow non-vector casts and length-changing shuffles. 276 // TODO: We could allow any shuffle. 277 auto *DestTy = dyn_cast<VectorType>(I.getType()); 278 auto *SrcTy = cast<VectorType>(V->getType()); 279 if (!DestTy || I.getOperand(0)->getType() != SrcTy) 280 return false; 281 282 // The new shuffle must not cost more than the old shuffle. The bitcast is 283 // moved ahead of the shuffle, so assume that it has the same cost as before. 284 if (TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, DestTy) > 285 TTI.getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, SrcTy)) 286 return false; 287 288 unsigned DestNumElts = DestTy->getNumElements(); 289 unsigned SrcNumElts = SrcTy->getNumElements(); 290 SmallVector<int, 16> NewMask; 291 if (SrcNumElts <= DestNumElts) { 292 // The bitcast is from wide to narrow/equal elements. The shuffle mask can 293 // always be expanded to the equivalent form choosing narrower elements. 294 assert(DestNumElts % SrcNumElts == 0 && "Unexpected shuffle mask"); 295 unsigned ScaleFactor = DestNumElts / SrcNumElts; 296 narrowShuffleMaskElts(ScaleFactor, Mask, NewMask); 297 } else { 298 // The bitcast is from narrow elements to wide elements. The shuffle mask 299 // must choose consecutive elements to allow casting first. 300 assert(SrcNumElts % DestNumElts == 0 && "Unexpected shuffle mask"); 301 unsigned ScaleFactor = SrcNumElts / DestNumElts; 302 if (!widenShuffleMaskElts(ScaleFactor, Mask, NewMask)) 303 return false; 304 } 305 // bitcast (shuf V, MaskC) --> shuf (bitcast V), MaskC' 306 ++NumShufOfBitcast; 307 IRBuilder<> Builder(&I); 308 Value *CastV = Builder.CreateBitCast(V, DestTy); 309 Value *Shuf = 310 Builder.CreateShuffleVector(CastV, UndefValue::get(DestTy), NewMask); 311 I.replaceAllUsesWith(Shuf); 312 return true; 313 } 314 315 /// Match a vector binop instruction with inserted scalar operands and convert 316 /// to scalar binop followed by insertelement. 317 static bool scalarizeBinop(Instruction &I, const TargetTransformInfo &TTI) { 318 Value *Ins0, *Ins1; 319 if (!match(&I, m_BinOp(m_Value(Ins0), m_Value(Ins1)))) 320 return false; 321 322 // Match against one or both scalar values being inserted into constant 323 // vectors: 324 // vec_bo VecC0, (inselt VecC1, V1, Index) 325 // vec_bo (inselt VecC0, V0, Index), VecC1 326 // vec_bo (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) 327 // TODO: Deal with mismatched index constants and variable indexes? 328 Constant *VecC0 = nullptr, *VecC1 = nullptr; 329 Value *V0 = nullptr, *V1 = nullptr; 330 uint64_t Index0 = 0, Index1 = 0; 331 if (!match(Ins0, m_InsertElt(m_Constant(VecC0), m_Value(V0), 332 m_ConstantInt(Index0))) && 333 !match(Ins0, m_Constant(VecC0))) 334 return false; 335 if (!match(Ins1, m_InsertElt(m_Constant(VecC1), m_Value(V1), 336 m_ConstantInt(Index1))) && 337 !match(Ins1, m_Constant(VecC1))) 338 return false; 339 340 bool IsConst0 = !V0; 341 bool IsConst1 = !V1; 342 if (IsConst0 && IsConst1) 343 return false; 344 if (!IsConst0 && !IsConst1 && Index0 != Index1) 345 return false; 346 347 // Bail for single insertion if it is a load. 348 // TODO: Handle this once getVectorInstrCost can cost for load/stores. 349 auto *I0 = dyn_cast_or_null<Instruction>(V0); 350 auto *I1 = dyn_cast_or_null<Instruction>(V1); 351 if ((IsConst0 && I1 && I1->mayReadFromMemory()) || 352 (IsConst1 && I0 && I0->mayReadFromMemory())) 353 return false; 354 355 uint64_t Index = IsConst0 ? Index1 : Index0; 356 Type *ScalarTy = IsConst0 ? V1->getType() : V0->getType(); 357 Type *VecTy = I.getType(); 358 assert(VecTy->isVectorTy() && 359 (IsConst0 || IsConst1 || V0->getType() == V1->getType()) && 360 (ScalarTy->isIntegerTy() || ScalarTy->isFloatingPointTy()) && 361 "Unexpected types for insert into binop"); 362 363 Instruction::BinaryOps Opcode = cast<BinaryOperator>(&I)->getOpcode(); 364 int ScalarOpCost = TTI.getArithmeticInstrCost(Opcode, ScalarTy); 365 int VectorOpCost = TTI.getArithmeticInstrCost(Opcode, VecTy); 366 367 // Get cost estimate for the insert element. This cost will factor into 368 // both sequences. 369 int InsertCost = 370 TTI.getVectorInstrCost(Instruction::InsertElement, VecTy, Index); 371 int OldCost = (IsConst0 ? 0 : InsertCost) + (IsConst1 ? 0 : InsertCost) + 372 VectorOpCost; 373 int NewCost = ScalarOpCost + InsertCost + 374 (IsConst0 ? 0 : !Ins0->hasOneUse() * InsertCost) + 375 (IsConst1 ? 0 : !Ins1->hasOneUse() * InsertCost); 376 377 // We want to scalarize unless the vector variant actually has lower cost. 378 if (OldCost < NewCost) 379 return false; 380 381 // vec_bo (inselt VecC0, V0, Index), (inselt VecC1, V1, Index) --> 382 // inselt NewVecC, (scalar_bo V0, V1), Index 383 ++NumScalarBO; 384 IRBuilder<> Builder(&I); 385 386 // For constant cases, extract the scalar element, this should constant fold. 387 if (IsConst0) 388 V0 = ConstantExpr::getExtractElement(VecC0, Builder.getInt64(Index)); 389 if (IsConst1) 390 V1 = ConstantExpr::getExtractElement(VecC1, Builder.getInt64(Index)); 391 392 Value *Scalar = Builder.CreateBinOp(Opcode, V0, V1, I.getName() + ".scalar"); 393 394 // All IR flags are safe to back-propagate. There is no potential for extra 395 // poison to be created by the scalar instruction. 396 if (auto *ScalarInst = dyn_cast<Instruction>(Scalar)) 397 ScalarInst->copyIRFlags(&I); 398 399 // Fold the vector constants in the original vectors into a new base vector. 400 Constant *NewVecC = ConstantExpr::get(Opcode, VecC0, VecC1); 401 Value *Insert = Builder.CreateInsertElement(NewVecC, Scalar, Index); 402 I.replaceAllUsesWith(Insert); 403 Insert->takeName(&I); 404 return true; 405 } 406 407 /// This is the entry point for all transforms. Pass manager differences are 408 /// handled in the callers of this function. 409 static bool runImpl(Function &F, const TargetTransformInfo &TTI, 410 const DominatorTree &DT) { 411 if (DisableVectorCombine) 412 return false; 413 414 bool MadeChange = false; 415 for (BasicBlock &BB : F) { 416 // Ignore unreachable basic blocks. 417 if (!DT.isReachableFromEntry(&BB)) 418 continue; 419 // Do not delete instructions under here and invalidate the iterator. 420 // Walk the block forwards to enable simple iterative chains of transforms. 421 // TODO: It could be more efficient to remove dead instructions 422 // iteratively in this loop rather than waiting until the end. 423 for (Instruction &I : BB) { 424 if (isa<DbgInfoIntrinsic>(I)) 425 continue; 426 MadeChange |= foldExtractExtract(I, TTI); 427 MadeChange |= foldBitcastShuf(I, TTI); 428 MadeChange |= scalarizeBinop(I, TTI); 429 } 430 } 431 432 // We're done with transforms, so remove dead instructions. 433 if (MadeChange) 434 for (BasicBlock &BB : F) 435 SimplifyInstructionsInBlock(&BB); 436 437 return MadeChange; 438 } 439 440 // Pass manager boilerplate below here. 441 442 namespace { 443 class VectorCombineLegacyPass : public FunctionPass { 444 public: 445 static char ID; 446 VectorCombineLegacyPass() : FunctionPass(ID) { 447 initializeVectorCombineLegacyPassPass(*PassRegistry::getPassRegistry()); 448 } 449 450 void getAnalysisUsage(AnalysisUsage &AU) const override { 451 AU.addRequired<DominatorTreeWrapperPass>(); 452 AU.addRequired<TargetTransformInfoWrapperPass>(); 453 AU.setPreservesCFG(); 454 AU.addPreserved<DominatorTreeWrapperPass>(); 455 AU.addPreserved<GlobalsAAWrapperPass>(); 456 AU.addPreserved<AAResultsWrapperPass>(); 457 AU.addPreserved<BasicAAWrapperPass>(); 458 FunctionPass::getAnalysisUsage(AU); 459 } 460 461 bool runOnFunction(Function &F) override { 462 if (skipFunction(F)) 463 return false; 464 auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 465 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 466 return runImpl(F, TTI, DT); 467 } 468 }; 469 } // namespace 470 471 char VectorCombineLegacyPass::ID = 0; 472 INITIALIZE_PASS_BEGIN(VectorCombineLegacyPass, "vector-combine", 473 "Optimize scalar/vector ops", false, 474 false) 475 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 476 INITIALIZE_PASS_END(VectorCombineLegacyPass, "vector-combine", 477 "Optimize scalar/vector ops", false, false) 478 Pass *llvm::createVectorCombinePass() { 479 return new VectorCombineLegacyPass(); 480 } 481 482 PreservedAnalyses VectorCombinePass::run(Function &F, 483 FunctionAnalysisManager &FAM) { 484 TargetTransformInfo &TTI = FAM.getResult<TargetIRAnalysis>(F); 485 DominatorTree &DT = FAM.getResult<DominatorTreeAnalysis>(F); 486 if (!runImpl(F, TTI, DT)) 487 return PreservedAnalyses::all(); 488 PreservedAnalyses PA; 489 PA.preserveSet<CFGAnalyses>(); 490 PA.preserve<GlobalsAA>(); 491 PA.preserve<AAManager>(); 492 PA.preserve<BasicAA>(); 493 return PA; 494 } 495