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