1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===// 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 implements the Bottom Up SLP vectorizer. It detects consecutive 10 // stores that can be put together into vector-stores. Next, it attempts to 11 // construct vectorizable tree using the use-def chains. If a profitable tree 12 // was found, the SLP vectorizer performs vectorization on the tree. 13 // 14 // The pass is inspired by the work described in the paper: 15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/DenseSet.h" 22 #include "llvm/ADT/Optional.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/PriorityQueue.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SetOperations.h" 27 #include "llvm/ADT/SetVector.h" 28 #include "llvm/ADT/SmallBitVector.h" 29 #include "llvm/ADT/SmallPtrSet.h" 30 #include "llvm/ADT/SmallSet.h" 31 #include "llvm/ADT/SmallString.h" 32 #include "llvm/ADT/Statistic.h" 33 #include "llvm/ADT/iterator.h" 34 #include "llvm/ADT/iterator_range.h" 35 #include "llvm/Analysis/AliasAnalysis.h" 36 #include "llvm/Analysis/AssumptionCache.h" 37 #include "llvm/Analysis/CodeMetrics.h" 38 #include "llvm/Analysis/DemandedBits.h" 39 #include "llvm/Analysis/GlobalsModRef.h" 40 #include "llvm/Analysis/IVDescriptors.h" 41 #include "llvm/Analysis/LoopAccessAnalysis.h" 42 #include "llvm/Analysis/LoopInfo.h" 43 #include "llvm/Analysis/MemoryLocation.h" 44 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 45 #include "llvm/Analysis/ScalarEvolution.h" 46 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 47 #include "llvm/Analysis/TargetLibraryInfo.h" 48 #include "llvm/Analysis/TargetTransformInfo.h" 49 #include "llvm/Analysis/ValueTracking.h" 50 #include "llvm/Analysis/VectorUtils.h" 51 #include "llvm/IR/Attributes.h" 52 #include "llvm/IR/BasicBlock.h" 53 #include "llvm/IR/Constant.h" 54 #include "llvm/IR/Constants.h" 55 #include "llvm/IR/DataLayout.h" 56 #include "llvm/IR/DebugLoc.h" 57 #include "llvm/IR/DerivedTypes.h" 58 #include "llvm/IR/Dominators.h" 59 #include "llvm/IR/Function.h" 60 #include "llvm/IR/IRBuilder.h" 61 #include "llvm/IR/InstrTypes.h" 62 #include "llvm/IR/Instruction.h" 63 #include "llvm/IR/Instructions.h" 64 #include "llvm/IR/IntrinsicInst.h" 65 #include "llvm/IR/Intrinsics.h" 66 #include "llvm/IR/Module.h" 67 #include "llvm/IR/NoFolder.h" 68 #include "llvm/IR/Operator.h" 69 #include "llvm/IR/PatternMatch.h" 70 #include "llvm/IR/Type.h" 71 #include "llvm/IR/Use.h" 72 #include "llvm/IR/User.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/IR/ValueHandle.h" 75 #include "llvm/IR/Verifier.h" 76 #include "llvm/InitializePasses.h" 77 #include "llvm/Pass.h" 78 #include "llvm/Support/Casting.h" 79 #include "llvm/Support/CommandLine.h" 80 #include "llvm/Support/Compiler.h" 81 #include "llvm/Support/DOTGraphTraits.h" 82 #include "llvm/Support/Debug.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/GraphWriter.h" 85 #include "llvm/Support/InstructionCost.h" 86 #include "llvm/Support/KnownBits.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include "llvm/Transforms/Utils/InjectTLIMappings.h" 90 #include "llvm/Transforms/Utils/LoopUtils.h" 91 #include "llvm/Transforms/Vectorize.h" 92 #include <algorithm> 93 #include <cassert> 94 #include <cstdint> 95 #include <iterator> 96 #include <memory> 97 #include <set> 98 #include <string> 99 #include <tuple> 100 #include <utility> 101 #include <vector> 102 103 using namespace llvm; 104 using namespace llvm::PatternMatch; 105 using namespace slpvectorizer; 106 107 #define SV_NAME "slp-vectorizer" 108 #define DEBUG_TYPE "SLP" 109 110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated"); 111 112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden, 113 cl::desc("Run the SLP vectorization passes")); 114 115 static cl::opt<int> 116 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden, 117 cl::desc("Only vectorize if you gain more than this " 118 "number ")); 119 120 static cl::opt<bool> 121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden, 122 cl::desc("Attempt to vectorize horizontal reductions")); 123 124 static cl::opt<bool> ShouldStartVectorizeHorAtStore( 125 "slp-vectorize-hor-store", cl::init(false), cl::Hidden, 126 cl::desc( 127 "Attempt to vectorize horizontal reductions feeding into a store")); 128 129 static cl::opt<int> 130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden, 131 cl::desc("Attempt to vectorize for this register size in bits")); 132 133 static cl::opt<unsigned> 134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden, 135 cl::desc("Maximum SLP vectorization factor (0=unlimited)")); 136 137 static cl::opt<int> 138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden, 139 cl::desc("Maximum depth of the lookup for consecutive stores.")); 140 141 /// Limits the size of scheduling regions in a block. 142 /// It avoid long compile times for _very_ large blocks where vector 143 /// instructions are spread over a wide range. 144 /// This limit is way higher than needed by real-world functions. 145 static cl::opt<int> 146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden, 147 cl::desc("Limit the size of the SLP scheduling region per block")); 148 149 static cl::opt<int> MinVectorRegSizeOption( 150 "slp-min-reg-size", cl::init(128), cl::Hidden, 151 cl::desc("Attempt to vectorize for this register size in bits")); 152 153 static cl::opt<unsigned> RecursionMaxDepth( 154 "slp-recursion-max-depth", cl::init(12), cl::Hidden, 155 cl::desc("Limit the recursion depth when building a vectorizable tree")); 156 157 static cl::opt<unsigned> MinTreeSize( 158 "slp-min-tree-size", cl::init(3), cl::Hidden, 159 cl::desc("Only vectorize small trees if they are fully vectorizable")); 160 161 // The maximum depth that the look-ahead score heuristic will explore. 162 // The higher this value, the higher the compilation time overhead. 163 static cl::opt<int> LookAheadMaxDepth( 164 "slp-max-look-ahead-depth", cl::init(2), cl::Hidden, 165 cl::desc("The maximum look-ahead depth for operand reordering scores")); 166 167 static cl::opt<bool> 168 ViewSLPTree("view-slp-tree", cl::Hidden, 169 cl::desc("Display the SLP trees with Graphviz")); 170 171 // Limit the number of alias checks. The limit is chosen so that 172 // it has no negative effect on the llvm benchmarks. 173 static const unsigned AliasedCheckLimit = 10; 174 175 // Another limit for the alias checks: The maximum distance between load/store 176 // instructions where alias checks are done. 177 // This limit is useful for very large basic blocks. 178 static const unsigned MaxMemDepDistance = 160; 179 180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling 181 /// regions to be handled. 182 static const int MinScheduleRegionSize = 16; 183 184 /// Predicate for the element types that the SLP vectorizer supports. 185 /// 186 /// The most important thing to filter here are types which are invalid in LLVM 187 /// vectors. We also filter target specific types which have absolutely no 188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just 189 /// avoids spending time checking the cost model and realizing that they will 190 /// be inevitably scalarized. 191 static bool isValidElementType(Type *Ty) { 192 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() && 193 !Ty->isPPC_FP128Ty(); 194 } 195 196 /// \returns True if the value is a constant (but not globals/constant 197 /// expressions). 198 static bool isConstant(Value *V) { 199 return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V); 200 } 201 202 /// Checks if \p V is one of vector-like instructions, i.e. undef, 203 /// insertelement/extractelement with constant indices for fixed vector type or 204 /// extractvalue instruction. 205 static bool isVectorLikeInstWithConstOps(Value *V) { 206 if (!isa<InsertElementInst, ExtractElementInst>(V) && 207 !isa<ExtractValueInst, UndefValue>(V)) 208 return false; 209 auto *I = dyn_cast<Instruction>(V); 210 if (!I || isa<ExtractValueInst>(I)) 211 return true; 212 if (!isa<FixedVectorType>(I->getOperand(0)->getType())) 213 return false; 214 if (isa<ExtractElementInst>(I)) 215 return isConstant(I->getOperand(1)); 216 assert(isa<InsertElementInst>(V) && "Expected only insertelement."); 217 return isConstant(I->getOperand(2)); 218 } 219 220 /// \returns true if all of the instructions in \p VL are in the same block or 221 /// false otherwise. 222 static bool allSameBlock(ArrayRef<Value *> VL) { 223 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 224 if (!I0) 225 return false; 226 if (all_of(VL, isVectorLikeInstWithConstOps)) 227 return true; 228 229 BasicBlock *BB = I0->getParent(); 230 for (int I = 1, E = VL.size(); I < E; I++) { 231 auto *II = dyn_cast<Instruction>(VL[I]); 232 if (!II) 233 return false; 234 235 if (BB != II->getParent()) 236 return false; 237 } 238 return true; 239 } 240 241 /// \returns True if all of the values in \p VL are constants (but not 242 /// globals/constant expressions). 243 static bool allConstant(ArrayRef<Value *> VL) { 244 // Constant expressions and globals can't be vectorized like normal integer/FP 245 // constants. 246 return all_of(VL, isConstant); 247 } 248 249 /// \returns True if all of the values in \p VL are identical or some of them 250 /// are UndefValue. 251 static bool isSplat(ArrayRef<Value *> VL) { 252 Value *FirstNonUndef = nullptr; 253 for (Value *V : VL) { 254 if (isa<UndefValue>(V)) 255 continue; 256 if (!FirstNonUndef) { 257 FirstNonUndef = V; 258 continue; 259 } 260 if (V != FirstNonUndef) 261 return false; 262 } 263 return FirstNonUndef != nullptr; 264 } 265 266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator. 267 static bool isCommutative(Instruction *I) { 268 if (auto *Cmp = dyn_cast<CmpInst>(I)) 269 return Cmp->isCommutative(); 270 if (auto *BO = dyn_cast<BinaryOperator>(I)) 271 return BO->isCommutative(); 272 // TODO: This should check for generic Instruction::isCommutative(), but 273 // we need to confirm that the caller code correctly handles Intrinsics 274 // for example (does not have 2 operands). 275 return false; 276 } 277 278 /// Checks if the given value is actually an undefined constant vector. 279 static bool isUndefVector(const Value *V) { 280 if (isa<UndefValue>(V)) 281 return true; 282 auto *C = dyn_cast<Constant>(V); 283 if (!C) 284 return false; 285 if (!C->containsUndefOrPoisonElement()) 286 return false; 287 auto *VecTy = dyn_cast<FixedVectorType>(C->getType()); 288 if (!VecTy) 289 return false; 290 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) { 291 if (Constant *Elem = C->getAggregateElement(I)) 292 if (!isa<UndefValue>(Elem)) 293 return false; 294 } 295 return true; 296 } 297 298 /// Checks if the vector of instructions can be represented as a shuffle, like: 299 /// %x0 = extractelement <4 x i8> %x, i32 0 300 /// %x3 = extractelement <4 x i8> %x, i32 3 301 /// %y1 = extractelement <4 x i8> %y, i32 1 302 /// %y2 = extractelement <4 x i8> %y, i32 2 303 /// %x0x0 = mul i8 %x0, %x0 304 /// %x3x3 = mul i8 %x3, %x3 305 /// %y1y1 = mul i8 %y1, %y1 306 /// %y2y2 = mul i8 %y2, %y2 307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0 308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1 309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2 310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3 311 /// ret <4 x i8> %ins4 312 /// can be transformed into: 313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5, 314 /// i32 6> 315 /// %2 = mul <4 x i8> %1, %1 316 /// ret <4 x i8> %2 317 /// We convert this initially to something like: 318 /// %x0 = extractelement <4 x i8> %x, i32 0 319 /// %x3 = extractelement <4 x i8> %x, i32 3 320 /// %y1 = extractelement <4 x i8> %y, i32 1 321 /// %y2 = extractelement <4 x i8> %y, i32 2 322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0 323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1 324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2 325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3 326 /// %5 = mul <4 x i8> %4, %4 327 /// %6 = extractelement <4 x i8> %5, i32 0 328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0 329 /// %7 = extractelement <4 x i8> %5, i32 1 330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1 331 /// %8 = extractelement <4 x i8> %5, i32 2 332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2 333 /// %9 = extractelement <4 x i8> %5, i32 3 334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3 335 /// ret <4 x i8> %ins4 336 /// InstCombiner transforms this into a shuffle and vector mul 337 /// Mask will return the Shuffle Mask equivalent to the extracted elements. 338 /// TODO: Can we split off and reuse the shuffle mask detection from 339 /// TargetTransformInfo::getInstructionThroughput? 340 static Optional<TargetTransformInfo::ShuffleKind> 341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) { 342 const auto *It = 343 find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); }); 344 if (It == VL.end()) 345 return None; 346 auto *EI0 = cast<ExtractElementInst>(*It); 347 if (isa<ScalableVectorType>(EI0->getVectorOperandType())) 348 return None; 349 unsigned Size = 350 cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements(); 351 Value *Vec1 = nullptr; 352 Value *Vec2 = nullptr; 353 enum ShuffleMode { Unknown, Select, Permute }; 354 ShuffleMode CommonShuffleMode = Unknown; 355 Mask.assign(VL.size(), UndefMaskElem); 356 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 357 // Undef can be represented as an undef element in a vector. 358 if (isa<UndefValue>(VL[I])) 359 continue; 360 auto *EI = cast<ExtractElementInst>(VL[I]); 361 if (isa<ScalableVectorType>(EI->getVectorOperandType())) 362 return None; 363 auto *Vec = EI->getVectorOperand(); 364 // We can extractelement from undef or poison vector. 365 if (isUndefVector(Vec)) 366 continue; 367 // All vector operands must have the same number of vector elements. 368 if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size) 369 return None; 370 if (isa<UndefValue>(EI->getIndexOperand())) 371 continue; 372 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand()); 373 if (!Idx) 374 return None; 375 // Undefined behavior if Idx is negative or >= Size. 376 if (Idx->getValue().uge(Size)) 377 continue; 378 unsigned IntIdx = Idx->getValue().getZExtValue(); 379 Mask[I] = IntIdx; 380 // For correct shuffling we have to have at most 2 different vector operands 381 // in all extractelement instructions. 382 if (!Vec1 || Vec1 == Vec) { 383 Vec1 = Vec; 384 } else if (!Vec2 || Vec2 == Vec) { 385 Vec2 = Vec; 386 Mask[I] += Size; 387 } else { 388 return None; 389 } 390 if (CommonShuffleMode == Permute) 391 continue; 392 // If the extract index is not the same as the operation number, it is a 393 // permutation. 394 if (IntIdx != I) { 395 CommonShuffleMode = Permute; 396 continue; 397 } 398 CommonShuffleMode = Select; 399 } 400 // If we're not crossing lanes in different vectors, consider it as blending. 401 if (CommonShuffleMode == Select && Vec2) 402 return TargetTransformInfo::SK_Select; 403 // If Vec2 was never used, we have a permutation of a single vector, otherwise 404 // we have permutation of 2 vectors. 405 return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc 406 : TargetTransformInfo::SK_PermuteSingleSrc; 407 } 408 409 namespace { 410 411 /// Main data required for vectorization of instructions. 412 struct InstructionsState { 413 /// The very first instruction in the list with the main opcode. 414 Value *OpValue = nullptr; 415 416 /// The main/alternate instruction. 417 Instruction *MainOp = nullptr; 418 Instruction *AltOp = nullptr; 419 420 /// The main/alternate opcodes for the list of instructions. 421 unsigned getOpcode() const { 422 return MainOp ? MainOp->getOpcode() : 0; 423 } 424 425 unsigned getAltOpcode() const { 426 return AltOp ? AltOp->getOpcode() : 0; 427 } 428 429 /// Some of the instructions in the list have alternate opcodes. 430 bool isAltShuffle() const { return AltOp != MainOp; } 431 432 bool isOpcodeOrAlt(Instruction *I) const { 433 unsigned CheckedOpcode = I->getOpcode(); 434 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode; 435 } 436 437 InstructionsState() = delete; 438 InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp) 439 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {} 440 }; 441 442 } // end anonymous namespace 443 444 /// Chooses the correct key for scheduling data. If \p Op has the same (or 445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p 446 /// OpValue. 447 static Value *isOneOf(const InstructionsState &S, Value *Op) { 448 auto *I = dyn_cast<Instruction>(Op); 449 if (I && S.isOpcodeOrAlt(I)) 450 return Op; 451 return S.OpValue; 452 } 453 454 /// \returns true if \p Opcode is allowed as part of of the main/alternate 455 /// instruction for SLP vectorization. 456 /// 457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the 458 /// "shuffled out" lane would result in division by zero. 459 static bool isValidForAlternation(unsigned Opcode) { 460 if (Instruction::isIntDivRem(Opcode)) 461 return false; 462 463 return true; 464 } 465 466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 467 unsigned BaseIndex = 0); 468 469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e. 470 /// compatible instructions or constants, or just some other regular values. 471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0, 472 Value *Op1) { 473 return (isConstant(BaseOp0) && isConstant(Op0)) || 474 (isConstant(BaseOp1) && isConstant(Op1)) || 475 (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) && 476 !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) || 477 getSameOpcode({BaseOp0, Op0}).getOpcode() || 478 getSameOpcode({BaseOp1, Op1}).getOpcode(); 479 } 480 481 /// \returns analysis of the Instructions in \p VL described in 482 /// InstructionsState, the Opcode that we suppose the whole list 483 /// could be vectorized even if its structure is diverse. 484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 485 unsigned BaseIndex) { 486 // Make sure these are all Instructions. 487 if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); })) 488 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 489 490 bool IsCastOp = isa<CastInst>(VL[BaseIndex]); 491 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]); 492 bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]); 493 CmpInst::Predicate BasePred = 494 IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate() 495 : CmpInst::BAD_ICMP_PREDICATE; 496 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode(); 497 unsigned AltOpcode = Opcode; 498 unsigned AltIndex = BaseIndex; 499 500 // Check for one alternate opcode from another BinaryOperator. 501 // TODO - generalize to support all operators (types, calls etc.). 502 for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) { 503 unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode(); 504 if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) { 505 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 506 continue; 507 if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) && 508 isValidForAlternation(Opcode)) { 509 AltOpcode = InstOpcode; 510 AltIndex = Cnt; 511 continue; 512 } 513 } else if (IsCastOp && isa<CastInst>(VL[Cnt])) { 514 Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType(); 515 Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType(); 516 if (Ty0 == Ty1) { 517 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 518 continue; 519 if (Opcode == AltOpcode) { 520 assert(isValidForAlternation(Opcode) && 521 isValidForAlternation(InstOpcode) && 522 "Cast isn't safe for alternation, logic needs to be updated!"); 523 AltOpcode = InstOpcode; 524 AltIndex = Cnt; 525 continue; 526 } 527 } 528 } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) { 529 auto *BaseInst = cast<Instruction>(VL[BaseIndex]); 530 auto *Inst = cast<Instruction>(VL[Cnt]); 531 Type *Ty0 = BaseInst->getOperand(0)->getType(); 532 Type *Ty1 = Inst->getOperand(0)->getType(); 533 if (Ty0 == Ty1) { 534 Value *BaseOp0 = BaseInst->getOperand(0); 535 Value *BaseOp1 = BaseInst->getOperand(1); 536 Value *Op0 = Inst->getOperand(0); 537 Value *Op1 = Inst->getOperand(1); 538 CmpInst::Predicate CurrentPred = 539 cast<CmpInst>(VL[Cnt])->getPredicate(); 540 CmpInst::Predicate SwappedCurrentPred = 541 CmpInst::getSwappedPredicate(CurrentPred); 542 // Check for compatible operands. If the corresponding operands are not 543 // compatible - need to perform alternate vectorization. 544 if (InstOpcode == Opcode) { 545 if (BasePred == CurrentPred && 546 areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1)) 547 continue; 548 if (BasePred == SwappedCurrentPred && 549 areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0)) 550 continue; 551 if (E == 2 && 552 (BasePred == CurrentPred || BasePred == SwappedCurrentPred)) 553 continue; 554 auto *AltInst = cast<CmpInst>(VL[AltIndex]); 555 CmpInst::Predicate AltPred = AltInst->getPredicate(); 556 Value *AltOp0 = AltInst->getOperand(0); 557 Value *AltOp1 = AltInst->getOperand(1); 558 // Check if operands are compatible with alternate operands. 559 if (AltPred == CurrentPred && 560 areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1)) 561 continue; 562 if (AltPred == SwappedCurrentPred && 563 areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0)) 564 continue; 565 } 566 if (BaseIndex == AltIndex && BasePred != CurrentPred) { 567 assert(isValidForAlternation(Opcode) && 568 isValidForAlternation(InstOpcode) && 569 "Cast isn't safe for alternation, logic needs to be updated!"); 570 AltIndex = Cnt; 571 continue; 572 } 573 auto *AltInst = cast<CmpInst>(VL[AltIndex]); 574 CmpInst::Predicate AltPred = AltInst->getPredicate(); 575 if (BasePred == CurrentPred || BasePred == SwappedCurrentPred || 576 AltPred == CurrentPred || AltPred == SwappedCurrentPred) 577 continue; 578 } 579 } else if (InstOpcode == Opcode || InstOpcode == AltOpcode) 580 continue; 581 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 582 } 583 584 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]), 585 cast<Instruction>(VL[AltIndex])); 586 } 587 588 /// \returns true if all of the values in \p VL have the same type or false 589 /// otherwise. 590 static bool allSameType(ArrayRef<Value *> VL) { 591 Type *Ty = VL[0]->getType(); 592 for (int i = 1, e = VL.size(); i < e; i++) 593 if (VL[i]->getType() != Ty) 594 return false; 595 596 return true; 597 } 598 599 /// \returns True if Extract{Value,Element} instruction extracts element Idx. 600 static Optional<unsigned> getExtractIndex(Instruction *E) { 601 unsigned Opcode = E->getOpcode(); 602 assert((Opcode == Instruction::ExtractElement || 603 Opcode == Instruction::ExtractValue) && 604 "Expected extractelement or extractvalue instruction."); 605 if (Opcode == Instruction::ExtractElement) { 606 auto *CI = dyn_cast<ConstantInt>(E->getOperand(1)); 607 if (!CI) 608 return None; 609 return CI->getZExtValue(); 610 } 611 ExtractValueInst *EI = cast<ExtractValueInst>(E); 612 if (EI->getNumIndices() != 1) 613 return None; 614 return *EI->idx_begin(); 615 } 616 617 /// \returns True if in-tree use also needs extract. This refers to 618 /// possible scalar operand in vectorized instruction. 619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, 620 TargetLibraryInfo *TLI) { 621 unsigned Opcode = UserInst->getOpcode(); 622 switch (Opcode) { 623 case Instruction::Load: { 624 LoadInst *LI = cast<LoadInst>(UserInst); 625 return (LI->getPointerOperand() == Scalar); 626 } 627 case Instruction::Store: { 628 StoreInst *SI = cast<StoreInst>(UserInst); 629 return (SI->getPointerOperand() == Scalar); 630 } 631 case Instruction::Call: { 632 CallInst *CI = cast<CallInst>(UserInst); 633 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 634 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 635 if (hasVectorInstrinsicScalarOpd(ID, i)) 636 return (CI->getArgOperand(i) == Scalar); 637 } 638 LLVM_FALLTHROUGH; 639 } 640 default: 641 return false; 642 } 643 } 644 645 /// \returns the AA location that is being access by the instruction. 646 static MemoryLocation getLocation(Instruction *I) { 647 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 648 return MemoryLocation::get(SI); 649 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 650 return MemoryLocation::get(LI); 651 return MemoryLocation(); 652 } 653 654 /// \returns True if the instruction is not a volatile or atomic load/store. 655 static bool isSimple(Instruction *I) { 656 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 657 return LI->isSimple(); 658 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 659 return SI->isSimple(); 660 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) 661 return !MI->isVolatile(); 662 return true; 663 } 664 665 /// Shuffles \p Mask in accordance with the given \p SubMask. 666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) { 667 if (SubMask.empty()) 668 return; 669 if (Mask.empty()) { 670 Mask.append(SubMask.begin(), SubMask.end()); 671 return; 672 } 673 SmallVector<int> NewMask(SubMask.size(), UndefMaskElem); 674 int TermValue = std::min(Mask.size(), SubMask.size()); 675 for (int I = 0, E = SubMask.size(); I < E; ++I) { 676 if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem || 677 Mask[SubMask[I]] >= TermValue) 678 continue; 679 NewMask[I] = Mask[SubMask[I]]; 680 } 681 Mask.swap(NewMask); 682 } 683 684 /// Order may have elements assigned special value (size) which is out of 685 /// bounds. Such indices only appear on places which correspond to undef values 686 /// (see canReuseExtract for details) and used in order to avoid undef values 687 /// have effect on operands ordering. 688 /// The first loop below simply finds all unused indices and then the next loop 689 /// nest assigns these indices for undef values positions. 690 /// As an example below Order has two undef positions and they have assigned 691 /// values 3 and 7 respectively: 692 /// before: 6 9 5 4 9 2 1 0 693 /// after: 6 3 5 4 7 2 1 0 694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) { 695 const unsigned Sz = Order.size(); 696 SmallBitVector UnusedIndices(Sz, /*t=*/true); 697 SmallBitVector MaskedIndices(Sz); 698 for (unsigned I = 0; I < Sz; ++I) { 699 if (Order[I] < Sz) 700 UnusedIndices.reset(Order[I]); 701 else 702 MaskedIndices.set(I); 703 } 704 if (MaskedIndices.none()) 705 return; 706 assert(UnusedIndices.count() == MaskedIndices.count() && 707 "Non-synced masked/available indices."); 708 int Idx = UnusedIndices.find_first(); 709 int MIdx = MaskedIndices.find_first(); 710 while (MIdx >= 0) { 711 assert(Idx >= 0 && "Indices must be synced."); 712 Order[MIdx] = Idx; 713 Idx = UnusedIndices.find_next(Idx); 714 MIdx = MaskedIndices.find_next(MIdx); 715 } 716 } 717 718 namespace llvm { 719 720 static void inversePermutation(ArrayRef<unsigned> Indices, 721 SmallVectorImpl<int> &Mask) { 722 Mask.clear(); 723 const unsigned E = Indices.size(); 724 Mask.resize(E, UndefMaskElem); 725 for (unsigned I = 0; I < E; ++I) 726 Mask[Indices[I]] = I; 727 } 728 729 /// \returns inserting index of InsertElement or InsertValue instruction, 730 /// using Offset as base offset for index. 731 static Optional<unsigned> getInsertIndex(Value *InsertInst, 732 unsigned Offset = 0) { 733 int Index = Offset; 734 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) { 735 if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) { 736 auto *VT = cast<FixedVectorType>(IE->getType()); 737 if (CI->getValue().uge(VT->getNumElements())) 738 return None; 739 Index *= VT->getNumElements(); 740 Index += CI->getZExtValue(); 741 return Index; 742 } 743 return None; 744 } 745 746 auto *IV = cast<InsertValueInst>(InsertInst); 747 Type *CurrentType = IV->getType(); 748 for (unsigned I : IV->indices()) { 749 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 750 Index *= ST->getNumElements(); 751 CurrentType = ST->getElementType(I); 752 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 753 Index *= AT->getNumElements(); 754 CurrentType = AT->getElementType(); 755 } else { 756 return None; 757 } 758 Index += I; 759 } 760 return Index; 761 } 762 763 /// Reorders the list of scalars in accordance with the given \p Mask. 764 static void reorderScalars(SmallVectorImpl<Value *> &Scalars, 765 ArrayRef<int> Mask) { 766 assert(!Mask.empty() && "Expected non-empty mask."); 767 SmallVector<Value *> Prev(Scalars.size(), 768 UndefValue::get(Scalars.front()->getType())); 769 Prev.swap(Scalars); 770 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 771 if (Mask[I] != UndefMaskElem) 772 Scalars[Mask[I]] = Prev[I]; 773 } 774 775 namespace slpvectorizer { 776 777 /// Bottom Up SLP Vectorizer. 778 class BoUpSLP { 779 struct TreeEntry; 780 struct ScheduleData; 781 782 public: 783 using ValueList = SmallVector<Value *, 8>; 784 using InstrList = SmallVector<Instruction *, 16>; 785 using ValueSet = SmallPtrSet<Value *, 16>; 786 using StoreList = SmallVector<StoreInst *, 8>; 787 using ExtraValueToDebugLocsMap = 788 MapVector<Value *, SmallVector<Instruction *, 2>>; 789 using OrdersType = SmallVector<unsigned, 4>; 790 791 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, 792 TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li, 793 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB, 794 const DataLayout *DL, OptimizationRemarkEmitter *ORE) 795 : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC), 796 DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) { 797 CodeMetrics::collectEphemeralValues(F, AC, EphValues); 798 // Use the vector register size specified by the target unless overridden 799 // by a command-line option. 800 // TODO: It would be better to limit the vectorization factor based on 801 // data type rather than just register size. For example, x86 AVX has 802 // 256-bit registers, but it does not support integer operations 803 // at that width (that requires AVX2). 804 if (MaxVectorRegSizeOption.getNumOccurrences()) 805 MaxVecRegSize = MaxVectorRegSizeOption; 806 else 807 MaxVecRegSize = 808 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) 809 .getFixedSize(); 810 811 if (MinVectorRegSizeOption.getNumOccurrences()) 812 MinVecRegSize = MinVectorRegSizeOption; 813 else 814 MinVecRegSize = TTI->getMinVectorRegisterBitWidth(); 815 } 816 817 /// Vectorize the tree that starts with the elements in \p VL. 818 /// Returns the vectorized root. 819 Value *vectorizeTree(); 820 821 /// Vectorize the tree but with the list of externally used values \p 822 /// ExternallyUsedValues. Values in this MapVector can be replaced but the 823 /// generated extractvalue instructions. 824 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues); 825 826 /// \returns the cost incurred by unwanted spills and fills, caused by 827 /// holding live values over call sites. 828 InstructionCost getSpillCost() const; 829 830 /// \returns the vectorization cost of the subtree that starts at \p VL. 831 /// A negative number means that this is profitable. 832 InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None); 833 834 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for 835 /// the purpose of scheduling and extraction in the \p UserIgnoreLst. 836 void buildTree(ArrayRef<Value *> Roots, 837 ArrayRef<Value *> UserIgnoreLst = None); 838 839 /// Builds external uses of the vectorized scalars, i.e. the list of 840 /// vectorized scalars to be extracted, their lanes and their scalar users. \p 841 /// ExternallyUsedValues contains additional list of external uses to handle 842 /// vectorization of reductions. 843 void 844 buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {}); 845 846 /// Clear the internal data structures that are created by 'buildTree'. 847 void deleteTree() { 848 VectorizableTree.clear(); 849 ScalarToTreeEntry.clear(); 850 MustGather.clear(); 851 ExternalUses.clear(); 852 for (auto &Iter : BlocksSchedules) { 853 BlockScheduling *BS = Iter.second.get(); 854 BS->clear(); 855 } 856 MinBWs.clear(); 857 InstrElementSize.clear(); 858 } 859 860 unsigned getTreeSize() const { return VectorizableTree.size(); } 861 862 /// Perform LICM and CSE on the newly generated gather sequences. 863 void optimizeGatherSequence(); 864 865 /// Checks if the specified gather tree entry \p TE can be represented as a 866 /// shuffled vector entry + (possibly) permutation with other gathers. It 867 /// implements the checks only for possibly ordered scalars (Loads, 868 /// ExtractElement, ExtractValue), which can be part of the graph. 869 Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE); 870 871 /// Gets reordering data for the given tree entry. If the entry is vectorized 872 /// - just return ReorderIndices, otherwise check if the scalars can be 873 /// reordered and return the most optimal order. 874 /// \param TopToBottom If true, include the order of vectorized stores and 875 /// insertelement nodes, otherwise skip them. 876 Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom); 877 878 /// Reorders the current graph to the most profitable order starting from the 879 /// root node to the leaf nodes. The best order is chosen only from the nodes 880 /// of the same size (vectorization factor). Smaller nodes are considered 881 /// parts of subgraph with smaller VF and they are reordered independently. We 882 /// can make it because we still need to extend smaller nodes to the wider VF 883 /// and we can merge reordering shuffles with the widening shuffles. 884 void reorderTopToBottom(); 885 886 /// Reorders the current graph to the most profitable order starting from 887 /// leaves to the root. It allows to rotate small subgraphs and reduce the 888 /// number of reshuffles if the leaf nodes use the same order. In this case we 889 /// can merge the orders and just shuffle user node instead of shuffling its 890 /// operands. Plus, even the leaf nodes have different orders, it allows to 891 /// sink reordering in the graph closer to the root node and merge it later 892 /// during analysis. 893 void reorderBottomToTop(bool IgnoreReorder = false); 894 895 /// \return The vector element size in bits to use when vectorizing the 896 /// expression tree ending at \p V. If V is a store, the size is the width of 897 /// the stored value. Otherwise, the size is the width of the largest loaded 898 /// value reaching V. This method is used by the vectorizer to calculate 899 /// vectorization factors. 900 unsigned getVectorElementSize(Value *V); 901 902 /// Compute the minimum type sizes required to represent the entries in a 903 /// vectorizable tree. 904 void computeMinimumValueSizes(); 905 906 // \returns maximum vector register size as set by TTI or overridden by cl::opt. 907 unsigned getMaxVecRegSize() const { 908 return MaxVecRegSize; 909 } 910 911 // \returns minimum vector register size as set by cl::opt. 912 unsigned getMinVecRegSize() const { 913 return MinVecRegSize; 914 } 915 916 unsigned getMinVF(unsigned Sz) const { 917 return std::max(2U, getMinVecRegSize() / Sz); 918 } 919 920 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const { 921 unsigned MaxVF = MaxVFOption.getNumOccurrences() ? 922 MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode); 923 return MaxVF ? MaxVF : UINT_MAX; 924 } 925 926 /// Check if homogeneous aggregate is isomorphic to some VectorType. 927 /// Accepts homogeneous multidimensional aggregate of scalars/vectors like 928 /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> }, 929 /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on. 930 /// 931 /// \returns number of elements in vector if isomorphism exists, 0 otherwise. 932 unsigned canMapToVector(Type *T, const DataLayout &DL) const; 933 934 /// \returns True if the VectorizableTree is both tiny and not fully 935 /// vectorizable. We do not vectorize such trees. 936 bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const; 937 938 /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values 939 /// can be load combined in the backend. Load combining may not be allowed in 940 /// the IR optimizer, so we do not want to alter the pattern. For example, 941 /// partially transforming a scalar bswap() pattern into vector code is 942 /// effectively impossible for the backend to undo. 943 /// TODO: If load combining is allowed in the IR optimizer, this analysis 944 /// may not be necessary. 945 bool isLoadCombineReductionCandidate(RecurKind RdxKind) const; 946 947 /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values 948 /// can be load combined in the backend. Load combining may not be allowed in 949 /// the IR optimizer, so we do not want to alter the pattern. For example, 950 /// partially transforming a scalar bswap() pattern into vector code is 951 /// effectively impossible for the backend to undo. 952 /// TODO: If load combining is allowed in the IR optimizer, this analysis 953 /// may not be necessary. 954 bool isLoadCombineCandidate() const; 955 956 OptimizationRemarkEmitter *getORE() { return ORE; } 957 958 /// This structure holds any data we need about the edges being traversed 959 /// during buildTree_rec(). We keep track of: 960 /// (i) the user TreeEntry index, and 961 /// (ii) the index of the edge. 962 struct EdgeInfo { 963 EdgeInfo() = default; 964 EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx) 965 : UserTE(UserTE), EdgeIdx(EdgeIdx) {} 966 /// The user TreeEntry. 967 TreeEntry *UserTE = nullptr; 968 /// The operand index of the use. 969 unsigned EdgeIdx = UINT_MAX; 970 #ifndef NDEBUG 971 friend inline raw_ostream &operator<<(raw_ostream &OS, 972 const BoUpSLP::EdgeInfo &EI) { 973 EI.dump(OS); 974 return OS; 975 } 976 /// Debug print. 977 void dump(raw_ostream &OS) const { 978 OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null") 979 << " EdgeIdx:" << EdgeIdx << "}"; 980 } 981 LLVM_DUMP_METHOD void dump() const { dump(dbgs()); } 982 #endif 983 }; 984 985 /// A helper data structure to hold the operands of a vector of instructions. 986 /// This supports a fixed vector length for all operand vectors. 987 class VLOperands { 988 /// For each operand we need (i) the value, and (ii) the opcode that it 989 /// would be attached to if the expression was in a left-linearized form. 990 /// This is required to avoid illegal operand reordering. 991 /// For example: 992 /// \verbatim 993 /// 0 Op1 994 /// |/ 995 /// Op1 Op2 Linearized + Op2 996 /// \ / ----------> |/ 997 /// - - 998 /// 999 /// Op1 - Op2 (0 + Op1) - Op2 1000 /// \endverbatim 1001 /// 1002 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'. 1003 /// 1004 /// Another way to think of this is to track all the operations across the 1005 /// path from the operand all the way to the root of the tree and to 1006 /// calculate the operation that corresponds to this path. For example, the 1007 /// path from Op2 to the root crosses the RHS of the '-', therefore the 1008 /// corresponding operation is a '-' (which matches the one in the 1009 /// linearized tree, as shown above). 1010 /// 1011 /// For lack of a better term, we refer to this operation as Accumulated 1012 /// Path Operation (APO). 1013 struct OperandData { 1014 OperandData() = default; 1015 OperandData(Value *V, bool APO, bool IsUsed) 1016 : V(V), APO(APO), IsUsed(IsUsed) {} 1017 /// The operand value. 1018 Value *V = nullptr; 1019 /// TreeEntries only allow a single opcode, or an alternate sequence of 1020 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the 1021 /// APO. It is set to 'true' if 'V' is attached to an inverse operation 1022 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise 1023 /// (e.g., Add/Mul) 1024 bool APO = false; 1025 /// Helper data for the reordering function. 1026 bool IsUsed = false; 1027 }; 1028 1029 /// During operand reordering, we are trying to select the operand at lane 1030 /// that matches best with the operand at the neighboring lane. Our 1031 /// selection is based on the type of value we are looking for. For example, 1032 /// if the neighboring lane has a load, we need to look for a load that is 1033 /// accessing a consecutive address. These strategies are summarized in the 1034 /// 'ReorderingMode' enumerator. 1035 enum class ReorderingMode { 1036 Load, ///< Matching loads to consecutive memory addresses 1037 Opcode, ///< Matching instructions based on opcode (same or alternate) 1038 Constant, ///< Matching constants 1039 Splat, ///< Matching the same instruction multiple times (broadcast) 1040 Failed, ///< We failed to create a vectorizable group 1041 }; 1042 1043 using OperandDataVec = SmallVector<OperandData, 2>; 1044 1045 /// A vector of operand vectors. 1046 SmallVector<OperandDataVec, 4> OpsVec; 1047 1048 const DataLayout &DL; 1049 ScalarEvolution &SE; 1050 const BoUpSLP &R; 1051 1052 /// \returns the operand data at \p OpIdx and \p Lane. 1053 OperandData &getData(unsigned OpIdx, unsigned Lane) { 1054 return OpsVec[OpIdx][Lane]; 1055 } 1056 1057 /// \returns the operand data at \p OpIdx and \p Lane. Const version. 1058 const OperandData &getData(unsigned OpIdx, unsigned Lane) const { 1059 return OpsVec[OpIdx][Lane]; 1060 } 1061 1062 /// Clears the used flag for all entries. 1063 void clearUsed() { 1064 for (unsigned OpIdx = 0, NumOperands = getNumOperands(); 1065 OpIdx != NumOperands; ++OpIdx) 1066 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes; 1067 ++Lane) 1068 OpsVec[OpIdx][Lane].IsUsed = false; 1069 } 1070 1071 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2. 1072 void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) { 1073 std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]); 1074 } 1075 1076 // The hard-coded scores listed here are not very important, though it shall 1077 // be higher for better matches to improve the resulting cost. When 1078 // computing the scores of matching one sub-tree with another, we are 1079 // basically counting the number of values that are matching. So even if all 1080 // scores are set to 1, we would still get a decent matching result. 1081 // However, sometimes we have to break ties. For example we may have to 1082 // choose between matching loads vs matching opcodes. This is what these 1083 // scores are helping us with: they provide the order of preference. Also, 1084 // this is important if the scalar is externally used or used in another 1085 // tree entry node in the different lane. 1086 1087 /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]). 1088 static const int ScoreConsecutiveLoads = 4; 1089 /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]). 1090 static const int ScoreReversedLoads = 3; 1091 /// ExtractElementInst from same vector and consecutive indexes. 1092 static const int ScoreConsecutiveExtracts = 4; 1093 /// ExtractElementInst from same vector and reversed indices. 1094 static const int ScoreReversedExtracts = 3; 1095 /// Constants. 1096 static const int ScoreConstants = 2; 1097 /// Instructions with the same opcode. 1098 static const int ScoreSameOpcode = 2; 1099 /// Instructions with alt opcodes (e.g, add + sub). 1100 static const int ScoreAltOpcodes = 1; 1101 /// Identical instructions (a.k.a. splat or broadcast). 1102 static const int ScoreSplat = 1; 1103 /// Matching with an undef is preferable to failing. 1104 static const int ScoreUndef = 1; 1105 /// Score for failing to find a decent match. 1106 static const int ScoreFail = 0; 1107 /// Score if all users are vectorized. 1108 static const int ScoreAllUserVectorized = 1; 1109 1110 /// \returns the score of placing \p V1 and \p V2 in consecutive lanes. 1111 /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p 1112 /// MainAltOps. 1113 static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL, 1114 ScalarEvolution &SE, int NumLanes, 1115 ArrayRef<Value *> MainAltOps) { 1116 if (V1 == V2) 1117 return VLOperands::ScoreSplat; 1118 1119 auto *LI1 = dyn_cast<LoadInst>(V1); 1120 auto *LI2 = dyn_cast<LoadInst>(V2); 1121 if (LI1 && LI2) { 1122 if (LI1->getParent() != LI2->getParent()) 1123 return VLOperands::ScoreFail; 1124 1125 Optional<int> Dist = getPointersDiff( 1126 LI1->getType(), LI1->getPointerOperand(), LI2->getType(), 1127 LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true); 1128 if (!Dist || *Dist == 0) 1129 return VLOperands::ScoreFail; 1130 // The distance is too large - still may be profitable to use masked 1131 // loads/gathers. 1132 if (std::abs(*Dist) > NumLanes / 2) 1133 return VLOperands::ScoreAltOpcodes; 1134 // This still will detect consecutive loads, but we might have "holes" 1135 // in some cases. It is ok for non-power-2 vectorization and may produce 1136 // better results. It should not affect current vectorization. 1137 return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads 1138 : VLOperands::ScoreReversedLoads; 1139 } 1140 1141 auto *C1 = dyn_cast<Constant>(V1); 1142 auto *C2 = dyn_cast<Constant>(V2); 1143 if (C1 && C2) 1144 return VLOperands::ScoreConstants; 1145 1146 // Extracts from consecutive indexes of the same vector better score as 1147 // the extracts could be optimized away. 1148 Value *EV1; 1149 ConstantInt *Ex1Idx; 1150 if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) { 1151 // Undefs are always profitable for extractelements. 1152 if (isa<UndefValue>(V2)) 1153 return VLOperands::ScoreConsecutiveExtracts; 1154 Value *EV2 = nullptr; 1155 ConstantInt *Ex2Idx = nullptr; 1156 if (match(V2, 1157 m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx), 1158 m_Undef())))) { 1159 // Undefs are always profitable for extractelements. 1160 if (!Ex2Idx) 1161 return VLOperands::ScoreConsecutiveExtracts; 1162 if (isUndefVector(EV2) && EV2->getType() == EV1->getType()) 1163 return VLOperands::ScoreConsecutiveExtracts; 1164 if (EV2 == EV1) { 1165 int Idx1 = Ex1Idx->getZExtValue(); 1166 int Idx2 = Ex2Idx->getZExtValue(); 1167 int Dist = Idx2 - Idx1; 1168 // The distance is too large - still may be profitable to use 1169 // shuffles. 1170 if (std::abs(Dist) == 0) 1171 return VLOperands::ScoreSplat; 1172 if (std::abs(Dist) > NumLanes / 2) 1173 return VLOperands::ScoreSameOpcode; 1174 return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts 1175 : VLOperands::ScoreReversedExtracts; 1176 } 1177 return VLOperands::ScoreAltOpcodes; 1178 } 1179 return VLOperands::ScoreFail; 1180 } 1181 1182 auto *I1 = dyn_cast<Instruction>(V1); 1183 auto *I2 = dyn_cast<Instruction>(V2); 1184 if (I1 && I2) { 1185 if (I1->getParent() != I2->getParent()) 1186 return VLOperands::ScoreFail; 1187 SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end()); 1188 Ops.push_back(I1); 1189 Ops.push_back(I2); 1190 InstructionsState S = getSameOpcode(Ops); 1191 // Note: Only consider instructions with <= 2 operands to avoid 1192 // complexity explosion. 1193 if (S.getOpcode() && 1194 (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() || 1195 !S.isAltShuffle()) && 1196 all_of(Ops, [&S](Value *V) { 1197 return cast<Instruction>(V)->getNumOperands() == 1198 S.MainOp->getNumOperands(); 1199 })) 1200 return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes 1201 : VLOperands::ScoreSameOpcode; 1202 } 1203 1204 if (isa<UndefValue>(V2)) 1205 return VLOperands::ScoreUndef; 1206 1207 return VLOperands::ScoreFail; 1208 } 1209 1210 /// \param Lane lane of the operands under analysis. 1211 /// \param OpIdx operand index in \p Lane lane we're looking the best 1212 /// candidate for. 1213 /// \param Idx operand index of the current candidate value. 1214 /// \returns The additional score due to possible broadcasting of the 1215 /// elements in the lane. It is more profitable to have power-of-2 unique 1216 /// elements in the lane, it will be vectorized with higher probability 1217 /// after removing duplicates. Currently the SLP vectorizer supports only 1218 /// vectorization of the power-of-2 number of unique scalars. 1219 int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { 1220 Value *IdxLaneV = getData(Idx, Lane).V; 1221 if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V) 1222 return 0; 1223 SmallPtrSet<Value *, 4> Uniques; 1224 for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) { 1225 if (Ln == Lane) 1226 continue; 1227 Value *OpIdxLnV = getData(OpIdx, Ln).V; 1228 if (!isa<Instruction>(OpIdxLnV)) 1229 return 0; 1230 Uniques.insert(OpIdxLnV); 1231 } 1232 int UniquesCount = Uniques.size(); 1233 int UniquesCntWithIdxLaneV = 1234 Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1; 1235 Value *OpIdxLaneV = getData(OpIdx, Lane).V; 1236 int UniquesCntWithOpIdxLaneV = 1237 Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1; 1238 if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV) 1239 return 0; 1240 return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) - 1241 UniquesCntWithOpIdxLaneV) - 1242 (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV); 1243 } 1244 1245 /// \param Lane lane of the operands under analysis. 1246 /// \param OpIdx operand index in \p Lane lane we're looking the best 1247 /// candidate for. 1248 /// \param Idx operand index of the current candidate value. 1249 /// \returns The additional score for the scalar which users are all 1250 /// vectorized. 1251 int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { 1252 Value *IdxLaneV = getData(Idx, Lane).V; 1253 Value *OpIdxLaneV = getData(OpIdx, Lane).V; 1254 // Do not care about number of uses for vector-like instructions 1255 // (extractelement/extractvalue with constant indices), they are extracts 1256 // themselves and already externally used. Vectorization of such 1257 // instructions does not add extra extractelement instruction, just may 1258 // remove it. 1259 if (isVectorLikeInstWithConstOps(IdxLaneV) && 1260 isVectorLikeInstWithConstOps(OpIdxLaneV)) 1261 return VLOperands::ScoreAllUserVectorized; 1262 auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV); 1263 if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV)) 1264 return 0; 1265 return R.areAllUsersVectorized(IdxLaneI, None) 1266 ? VLOperands::ScoreAllUserVectorized 1267 : 0; 1268 } 1269 1270 /// Go through the operands of \p LHS and \p RHS recursively until \p 1271 /// MaxLevel, and return the cummulative score. For example: 1272 /// \verbatim 1273 /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1] 1274 /// \ / \ / \ / \ / 1275 /// + + + + 1276 /// G1 G2 G3 G4 1277 /// \endverbatim 1278 /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at 1279 /// each level recursively, accumulating the score. It starts from matching 1280 /// the additions at level 0, then moves on to the loads (level 1). The 1281 /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and 1282 /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while 1283 /// {A[0],C[0]} has a score of VLOperands::ScoreFail. 1284 /// Please note that the order of the operands does not matter, as we 1285 /// evaluate the score of all profitable combinations of operands. In 1286 /// other words the score of G1 and G4 is the same as G1 and G2. This 1287 /// heuristic is based on ideas described in: 1288 /// Look-ahead SLP: Auto-vectorization in the presence of commutative 1289 /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha, 1290 /// Luís F. W. Góes 1291 int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel, 1292 ArrayRef<Value *> MainAltOps) { 1293 1294 // Get the shallow score of V1 and V2. 1295 int ShallowScoreAtThisLevel = 1296 getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps); 1297 1298 // If reached MaxLevel, 1299 // or if V1 and V2 are not instructions, 1300 // or if they are SPLAT, 1301 // or if they are not consecutive, 1302 // or if profitable to vectorize loads or extractelements, early return 1303 // the current cost. 1304 auto *I1 = dyn_cast<Instruction>(LHS); 1305 auto *I2 = dyn_cast<Instruction>(RHS); 1306 if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 || 1307 ShallowScoreAtThisLevel == VLOperands::ScoreFail || 1308 (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) || 1309 (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) || 1310 (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) && 1311 ShallowScoreAtThisLevel)) 1312 return ShallowScoreAtThisLevel; 1313 assert(I1 && I2 && "Should have early exited."); 1314 1315 // Contains the I2 operand indexes that got matched with I1 operands. 1316 SmallSet<unsigned, 4> Op2Used; 1317 1318 // Recursion towards the operands of I1 and I2. We are trying all possible 1319 // operand pairs, and keeping track of the best score. 1320 for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands(); 1321 OpIdx1 != NumOperands1; ++OpIdx1) { 1322 // Try to pair op1I with the best operand of I2. 1323 int MaxTmpScore = 0; 1324 unsigned MaxOpIdx2 = 0; 1325 bool FoundBest = false; 1326 // If I2 is commutative try all combinations. 1327 unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1; 1328 unsigned ToIdx = isCommutative(I2) 1329 ? I2->getNumOperands() 1330 : std::min(I2->getNumOperands(), OpIdx1 + 1); 1331 assert(FromIdx <= ToIdx && "Bad index"); 1332 for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) { 1333 // Skip operands already paired with OpIdx1. 1334 if (Op2Used.count(OpIdx2)) 1335 continue; 1336 // Recursively calculate the cost at each level 1337 int TmpScore = 1338 getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2), 1339 CurrLevel + 1, MaxLevel, None); 1340 // Look for the best score. 1341 if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) { 1342 MaxTmpScore = TmpScore; 1343 MaxOpIdx2 = OpIdx2; 1344 FoundBest = true; 1345 } 1346 } 1347 if (FoundBest) { 1348 // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it. 1349 Op2Used.insert(MaxOpIdx2); 1350 ShallowScoreAtThisLevel += MaxTmpScore; 1351 } 1352 } 1353 return ShallowScoreAtThisLevel; 1354 } 1355 1356 /// Score scaling factor for fully compatible instructions but with 1357 /// different number of external uses. Allows better selection of the 1358 /// instructions with less external uses. 1359 static const int ScoreScaleFactor = 10; 1360 1361 /// \Returns the look-ahead score, which tells us how much the sub-trees 1362 /// rooted at \p LHS and \p RHS match, the more they match the higher the 1363 /// score. This helps break ties in an informed way when we cannot decide on 1364 /// the order of the operands by just considering the immediate 1365 /// predecessors. 1366 int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps, 1367 int Lane, unsigned OpIdx, unsigned Idx, 1368 bool &IsUsed) { 1369 int Score = 1370 getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps); 1371 if (Score) { 1372 int SplatScore = getSplatScore(Lane, OpIdx, Idx); 1373 if (Score <= -SplatScore) { 1374 // Set the minimum score for splat-like sequence to avoid setting 1375 // failed state. 1376 Score = 1; 1377 } else { 1378 Score += SplatScore; 1379 // Scale score to see the difference between different operands 1380 // and similar operands but all vectorized/not all vectorized 1381 // uses. It does not affect actual selection of the best 1382 // compatible operand in general, just allows to select the 1383 // operand with all vectorized uses. 1384 Score *= ScoreScaleFactor; 1385 Score += getExternalUseScore(Lane, OpIdx, Idx); 1386 IsUsed = true; 1387 } 1388 } 1389 return Score; 1390 } 1391 1392 /// Best defined scores per lanes between the passes. Used to choose the 1393 /// best operand (with the highest score) between the passes. 1394 /// The key - {Operand Index, Lane}. 1395 /// The value - the best score between the passes for the lane and the 1396 /// operand. 1397 SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8> 1398 BestScoresPerLanes; 1399 1400 // Search all operands in Ops[*][Lane] for the one that matches best 1401 // Ops[OpIdx][LastLane] and return its opreand index. 1402 // If no good match can be found, return None. 1403 Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane, 1404 ArrayRef<ReorderingMode> ReorderingModes, 1405 ArrayRef<Value *> MainAltOps) { 1406 unsigned NumOperands = getNumOperands(); 1407 1408 // The operand of the previous lane at OpIdx. 1409 Value *OpLastLane = getData(OpIdx, LastLane).V; 1410 1411 // Our strategy mode for OpIdx. 1412 ReorderingMode RMode = ReorderingModes[OpIdx]; 1413 if (RMode == ReorderingMode::Failed) 1414 return None; 1415 1416 // The linearized opcode of the operand at OpIdx, Lane. 1417 bool OpIdxAPO = getData(OpIdx, Lane).APO; 1418 1419 // The best operand index and its score. 1420 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we 1421 // are using the score to differentiate between the two. 1422 struct BestOpData { 1423 Optional<unsigned> Idx = None; 1424 unsigned Score = 0; 1425 } BestOp; 1426 BestOp.Score = 1427 BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0) 1428 .first->second; 1429 1430 // Track if the operand must be marked as used. If the operand is set to 1431 // Score 1 explicitly (because of non power-of-2 unique scalars, we may 1432 // want to reestimate the operands again on the following iterations). 1433 bool IsUsed = 1434 RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant; 1435 // Iterate through all unused operands and look for the best. 1436 for (unsigned Idx = 0; Idx != NumOperands; ++Idx) { 1437 // Get the operand at Idx and Lane. 1438 OperandData &OpData = getData(Idx, Lane); 1439 Value *Op = OpData.V; 1440 bool OpAPO = OpData.APO; 1441 1442 // Skip already selected operands. 1443 if (OpData.IsUsed) 1444 continue; 1445 1446 // Skip if we are trying to move the operand to a position with a 1447 // different opcode in the linearized tree form. This would break the 1448 // semantics. 1449 if (OpAPO != OpIdxAPO) 1450 continue; 1451 1452 // Look for an operand that matches the current mode. 1453 switch (RMode) { 1454 case ReorderingMode::Load: 1455 case ReorderingMode::Constant: 1456 case ReorderingMode::Opcode: { 1457 bool LeftToRight = Lane > LastLane; 1458 Value *OpLeft = (LeftToRight) ? OpLastLane : Op; 1459 Value *OpRight = (LeftToRight) ? Op : OpLastLane; 1460 int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane, 1461 OpIdx, Idx, IsUsed); 1462 if (Score > static_cast<int>(BestOp.Score)) { 1463 BestOp.Idx = Idx; 1464 BestOp.Score = Score; 1465 BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score; 1466 } 1467 break; 1468 } 1469 case ReorderingMode::Splat: 1470 if (Op == OpLastLane) 1471 BestOp.Idx = Idx; 1472 break; 1473 case ReorderingMode::Failed: 1474 llvm_unreachable("Not expected Failed reordering mode."); 1475 } 1476 } 1477 1478 if (BestOp.Idx) { 1479 getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed; 1480 return BestOp.Idx; 1481 } 1482 // If we could not find a good match return None. 1483 return None; 1484 } 1485 1486 /// Helper for reorderOperandVecs. 1487 /// \returns the lane that we should start reordering from. This is the one 1488 /// which has the least number of operands that can freely move about or 1489 /// less profitable because it already has the most optimal set of operands. 1490 unsigned getBestLaneToStartReordering() const { 1491 unsigned Min = UINT_MAX; 1492 unsigned SameOpNumber = 0; 1493 // std::pair<unsigned, unsigned> is used to implement a simple voting 1494 // algorithm and choose the lane with the least number of operands that 1495 // can freely move about or less profitable because it already has the 1496 // most optimal set of operands. The first unsigned is a counter for 1497 // voting, the second unsigned is the counter of lanes with instructions 1498 // with same/alternate opcodes and same parent basic block. 1499 MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap; 1500 // Try to be closer to the original results, if we have multiple lanes 1501 // with same cost. If 2 lanes have the same cost, use the one with the 1502 // lowest index. 1503 for (int I = getNumLanes(); I > 0; --I) { 1504 unsigned Lane = I - 1; 1505 OperandsOrderData NumFreeOpsHash = 1506 getMaxNumOperandsThatCanBeReordered(Lane); 1507 // Compare the number of operands that can move and choose the one with 1508 // the least number. 1509 if (NumFreeOpsHash.NumOfAPOs < Min) { 1510 Min = NumFreeOpsHash.NumOfAPOs; 1511 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; 1512 HashMap.clear(); 1513 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1514 } else if (NumFreeOpsHash.NumOfAPOs == Min && 1515 NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) { 1516 // Select the most optimal lane in terms of number of operands that 1517 // should be moved around. 1518 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; 1519 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1520 } else if (NumFreeOpsHash.NumOfAPOs == Min && 1521 NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) { 1522 auto It = HashMap.find(NumFreeOpsHash.Hash); 1523 if (It == HashMap.end()) 1524 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1525 else 1526 ++It->second.first; 1527 } 1528 } 1529 // Select the lane with the minimum counter. 1530 unsigned BestLane = 0; 1531 unsigned CntMin = UINT_MAX; 1532 for (const auto &Data : reverse(HashMap)) { 1533 if (Data.second.first < CntMin) { 1534 CntMin = Data.second.first; 1535 BestLane = Data.second.second; 1536 } 1537 } 1538 return BestLane; 1539 } 1540 1541 /// Data structure that helps to reorder operands. 1542 struct OperandsOrderData { 1543 /// The best number of operands with the same APOs, which can be 1544 /// reordered. 1545 unsigned NumOfAPOs = UINT_MAX; 1546 /// Number of operands with the same/alternate instruction opcode and 1547 /// parent. 1548 unsigned NumOpsWithSameOpcodeParent = 0; 1549 /// Hash for the actual operands ordering. 1550 /// Used to count operands, actually their position id and opcode 1551 /// value. It is used in the voting mechanism to find the lane with the 1552 /// least number of operands that can freely move about or less profitable 1553 /// because it already has the most optimal set of operands. Can be 1554 /// replaced with SmallVector<unsigned> instead but hash code is faster 1555 /// and requires less memory. 1556 unsigned Hash = 0; 1557 }; 1558 /// \returns the maximum number of operands that are allowed to be reordered 1559 /// for \p Lane and the number of compatible instructions(with the same 1560 /// parent/opcode). This is used as a heuristic for selecting the first lane 1561 /// to start operand reordering. 1562 OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const { 1563 unsigned CntTrue = 0; 1564 unsigned NumOperands = getNumOperands(); 1565 // Operands with the same APO can be reordered. We therefore need to count 1566 // how many of them we have for each APO, like this: Cnt[APO] = x. 1567 // Since we only have two APOs, namely true and false, we can avoid using 1568 // a map. Instead we can simply count the number of operands that 1569 // correspond to one of them (in this case the 'true' APO), and calculate 1570 // the other by subtracting it from the total number of operands. 1571 // Operands with the same instruction opcode and parent are more 1572 // profitable since we don't need to move them in many cases, with a high 1573 // probability such lane already can be vectorized effectively. 1574 bool AllUndefs = true; 1575 unsigned NumOpsWithSameOpcodeParent = 0; 1576 Instruction *OpcodeI = nullptr; 1577 BasicBlock *Parent = nullptr; 1578 unsigned Hash = 0; 1579 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1580 const OperandData &OpData = getData(OpIdx, Lane); 1581 if (OpData.APO) 1582 ++CntTrue; 1583 // Use Boyer-Moore majority voting for finding the majority opcode and 1584 // the number of times it occurs. 1585 if (auto *I = dyn_cast<Instruction>(OpData.V)) { 1586 if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() || 1587 I->getParent() != Parent) { 1588 if (NumOpsWithSameOpcodeParent == 0) { 1589 NumOpsWithSameOpcodeParent = 1; 1590 OpcodeI = I; 1591 Parent = I->getParent(); 1592 } else { 1593 --NumOpsWithSameOpcodeParent; 1594 } 1595 } else { 1596 ++NumOpsWithSameOpcodeParent; 1597 } 1598 } 1599 Hash = hash_combine( 1600 Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1))); 1601 AllUndefs = AllUndefs && isa<UndefValue>(OpData.V); 1602 } 1603 if (AllUndefs) 1604 return {}; 1605 OperandsOrderData Data; 1606 Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue); 1607 Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent; 1608 Data.Hash = Hash; 1609 return Data; 1610 } 1611 1612 /// Go through the instructions in VL and append their operands. 1613 void appendOperandsOfVL(ArrayRef<Value *> VL) { 1614 assert(!VL.empty() && "Bad VL"); 1615 assert((empty() || VL.size() == getNumLanes()) && 1616 "Expected same number of lanes"); 1617 assert(isa<Instruction>(VL[0]) && "Expected instruction"); 1618 unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands(); 1619 OpsVec.resize(NumOperands); 1620 unsigned NumLanes = VL.size(); 1621 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1622 OpsVec[OpIdx].resize(NumLanes); 1623 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 1624 assert(isa<Instruction>(VL[Lane]) && "Expected instruction"); 1625 // Our tree has just 3 nodes: the root and two operands. 1626 // It is therefore trivial to get the APO. We only need to check the 1627 // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or 1628 // RHS operand. The LHS operand of both add and sub is never attached 1629 // to an inversese operation in the linearized form, therefore its APO 1630 // is false. The RHS is true only if VL[Lane] is an inverse operation. 1631 1632 // Since operand reordering is performed on groups of commutative 1633 // operations or alternating sequences (e.g., +, -), we can safely 1634 // tell the inverse operations by checking commutativity. 1635 bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane])); 1636 bool APO = (OpIdx == 0) ? false : IsInverseOperation; 1637 OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx), 1638 APO, false}; 1639 } 1640 } 1641 } 1642 1643 /// \returns the number of operands. 1644 unsigned getNumOperands() const { return OpsVec.size(); } 1645 1646 /// \returns the number of lanes. 1647 unsigned getNumLanes() const { return OpsVec[0].size(); } 1648 1649 /// \returns the operand value at \p OpIdx and \p Lane. 1650 Value *getValue(unsigned OpIdx, unsigned Lane) const { 1651 return getData(OpIdx, Lane).V; 1652 } 1653 1654 /// \returns true if the data structure is empty. 1655 bool empty() const { return OpsVec.empty(); } 1656 1657 /// Clears the data. 1658 void clear() { OpsVec.clear(); } 1659 1660 /// \Returns true if there are enough operands identical to \p Op to fill 1661 /// the whole vector. 1662 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow. 1663 bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) { 1664 bool OpAPO = getData(OpIdx, Lane).APO; 1665 for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) { 1666 if (Ln == Lane) 1667 continue; 1668 // This is set to true if we found a candidate for broadcast at Lane. 1669 bool FoundCandidate = false; 1670 for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) { 1671 OperandData &Data = getData(OpI, Ln); 1672 if (Data.APO != OpAPO || Data.IsUsed) 1673 continue; 1674 if (Data.V == Op) { 1675 FoundCandidate = true; 1676 Data.IsUsed = true; 1677 break; 1678 } 1679 } 1680 if (!FoundCandidate) 1681 return false; 1682 } 1683 return true; 1684 } 1685 1686 public: 1687 /// Initialize with all the operands of the instruction vector \p RootVL. 1688 VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL, 1689 ScalarEvolution &SE, const BoUpSLP &R) 1690 : DL(DL), SE(SE), R(R) { 1691 // Append all the operands of RootVL. 1692 appendOperandsOfVL(RootVL); 1693 } 1694 1695 /// \Returns a value vector with the operands across all lanes for the 1696 /// opearnd at \p OpIdx. 1697 ValueList getVL(unsigned OpIdx) const { 1698 ValueList OpVL(OpsVec[OpIdx].size()); 1699 assert(OpsVec[OpIdx].size() == getNumLanes() && 1700 "Expected same num of lanes across all operands"); 1701 for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane) 1702 OpVL[Lane] = OpsVec[OpIdx][Lane].V; 1703 return OpVL; 1704 } 1705 1706 // Performs operand reordering for 2 or more operands. 1707 // The original operands are in OrigOps[OpIdx][Lane]. 1708 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'. 1709 void reorder() { 1710 unsigned NumOperands = getNumOperands(); 1711 unsigned NumLanes = getNumLanes(); 1712 // Each operand has its own mode. We are using this mode to help us select 1713 // the instructions for each lane, so that they match best with the ones 1714 // we have selected so far. 1715 SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands); 1716 1717 // This is a greedy single-pass algorithm. We are going over each lane 1718 // once and deciding on the best order right away with no back-tracking. 1719 // However, in order to increase its effectiveness, we start with the lane 1720 // that has operands that can move the least. For example, given the 1721 // following lanes: 1722 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd 1723 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st 1724 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd 1725 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th 1726 // we will start at Lane 1, since the operands of the subtraction cannot 1727 // be reordered. Then we will visit the rest of the lanes in a circular 1728 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3. 1729 1730 // Find the first lane that we will start our search from. 1731 unsigned FirstLane = getBestLaneToStartReordering(); 1732 1733 // Initialize the modes. 1734 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1735 Value *OpLane0 = getValue(OpIdx, FirstLane); 1736 // Keep track if we have instructions with all the same opcode on one 1737 // side. 1738 if (isa<LoadInst>(OpLane0)) 1739 ReorderingModes[OpIdx] = ReorderingMode::Load; 1740 else if (isa<Instruction>(OpLane0)) { 1741 // Check if OpLane0 should be broadcast. 1742 if (shouldBroadcast(OpLane0, OpIdx, FirstLane)) 1743 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1744 else 1745 ReorderingModes[OpIdx] = ReorderingMode::Opcode; 1746 } 1747 else if (isa<Constant>(OpLane0)) 1748 ReorderingModes[OpIdx] = ReorderingMode::Constant; 1749 else if (isa<Argument>(OpLane0)) 1750 // Our best hope is a Splat. It may save some cost in some cases. 1751 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1752 else 1753 // NOTE: This should be unreachable. 1754 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1755 } 1756 1757 // Check that we don't have same operands. No need to reorder if operands 1758 // are just perfect diamond or shuffled diamond match. Do not do it only 1759 // for possible broadcasts or non-power of 2 number of scalars (just for 1760 // now). 1761 auto &&SkipReordering = [this]() { 1762 SmallPtrSet<Value *, 4> UniqueValues; 1763 ArrayRef<OperandData> Op0 = OpsVec.front(); 1764 for (const OperandData &Data : Op0) 1765 UniqueValues.insert(Data.V); 1766 for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) { 1767 if (any_of(Op, [&UniqueValues](const OperandData &Data) { 1768 return !UniqueValues.contains(Data.V); 1769 })) 1770 return false; 1771 } 1772 // TODO: Check if we can remove a check for non-power-2 number of 1773 // scalars after full support of non-power-2 vectorization. 1774 return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size()); 1775 }; 1776 1777 // If the initial strategy fails for any of the operand indexes, then we 1778 // perform reordering again in a second pass. This helps avoid assigning 1779 // high priority to the failed strategy, and should improve reordering for 1780 // the non-failed operand indexes. 1781 for (int Pass = 0; Pass != 2; ++Pass) { 1782 // Check if no need to reorder operands since they're are perfect or 1783 // shuffled diamond match. 1784 // Need to to do it to avoid extra external use cost counting for 1785 // shuffled matches, which may cause regressions. 1786 if (SkipReordering()) 1787 break; 1788 // Skip the second pass if the first pass did not fail. 1789 bool StrategyFailed = false; 1790 // Mark all operand data as free to use. 1791 clearUsed(); 1792 // We keep the original operand order for the FirstLane, so reorder the 1793 // rest of the lanes. We are visiting the nodes in a circular fashion, 1794 // using FirstLane as the center point and increasing the radius 1795 // distance. 1796 SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands); 1797 for (unsigned I = 0; I < NumOperands; ++I) 1798 MainAltOps[I].push_back(getData(I, FirstLane).V); 1799 1800 for (unsigned Distance = 1; Distance != NumLanes; ++Distance) { 1801 // Visit the lane on the right and then the lane on the left. 1802 for (int Direction : {+1, -1}) { 1803 int Lane = FirstLane + Direction * Distance; 1804 if (Lane < 0 || Lane >= (int)NumLanes) 1805 continue; 1806 int LastLane = Lane - Direction; 1807 assert(LastLane >= 0 && LastLane < (int)NumLanes && 1808 "Out of bounds"); 1809 // Look for a good match for each operand. 1810 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1811 // Search for the operand that matches SortedOps[OpIdx][Lane-1]. 1812 Optional<unsigned> BestIdx = getBestOperand( 1813 OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]); 1814 // By not selecting a value, we allow the operands that follow to 1815 // select a better matching value. We will get a non-null value in 1816 // the next run of getBestOperand(). 1817 if (BestIdx) { 1818 // Swap the current operand with the one returned by 1819 // getBestOperand(). 1820 swap(OpIdx, BestIdx.getValue(), Lane); 1821 } else { 1822 // We failed to find a best operand, set mode to 'Failed'. 1823 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1824 // Enable the second pass. 1825 StrategyFailed = true; 1826 } 1827 // Try to get the alternate opcode and follow it during analysis. 1828 if (MainAltOps[OpIdx].size() != 2) { 1829 OperandData &AltOp = getData(OpIdx, Lane); 1830 InstructionsState OpS = 1831 getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V}); 1832 if (OpS.getOpcode() && OpS.isAltShuffle()) 1833 MainAltOps[OpIdx].push_back(AltOp.V); 1834 } 1835 } 1836 } 1837 } 1838 // Skip second pass if the strategy did not fail. 1839 if (!StrategyFailed) 1840 break; 1841 } 1842 } 1843 1844 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1845 LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) { 1846 switch (RMode) { 1847 case ReorderingMode::Load: 1848 return "Load"; 1849 case ReorderingMode::Opcode: 1850 return "Opcode"; 1851 case ReorderingMode::Constant: 1852 return "Constant"; 1853 case ReorderingMode::Splat: 1854 return "Splat"; 1855 case ReorderingMode::Failed: 1856 return "Failed"; 1857 } 1858 llvm_unreachable("Unimplemented Reordering Type"); 1859 } 1860 1861 LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode, 1862 raw_ostream &OS) { 1863 return OS << getModeStr(RMode); 1864 } 1865 1866 /// Debug print. 1867 LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) { 1868 printMode(RMode, dbgs()); 1869 } 1870 1871 friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) { 1872 return printMode(RMode, OS); 1873 } 1874 1875 LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const { 1876 const unsigned Indent = 2; 1877 unsigned Cnt = 0; 1878 for (const OperandDataVec &OpDataVec : OpsVec) { 1879 OS << "Operand " << Cnt++ << "\n"; 1880 for (const OperandData &OpData : OpDataVec) { 1881 OS.indent(Indent) << "{"; 1882 if (Value *V = OpData.V) 1883 OS << *V; 1884 else 1885 OS << "null"; 1886 OS << ", APO:" << OpData.APO << "}\n"; 1887 } 1888 OS << "\n"; 1889 } 1890 return OS; 1891 } 1892 1893 /// Debug print. 1894 LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 1895 #endif 1896 }; 1897 1898 /// Checks if the instruction is marked for deletion. 1899 bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); } 1900 1901 /// Marks values operands for later deletion by replacing them with Undefs. 1902 void eraseInstructions(ArrayRef<Value *> AV); 1903 1904 ~BoUpSLP(); 1905 1906 private: 1907 /// Checks if all users of \p I are the part of the vectorization tree. 1908 bool areAllUsersVectorized(Instruction *I, 1909 ArrayRef<Value *> VectorizedVals) const; 1910 1911 /// \returns the cost of the vectorizable entry. 1912 InstructionCost getEntryCost(const TreeEntry *E, 1913 ArrayRef<Value *> VectorizedVals); 1914 1915 /// This is the recursive part of buildTree. 1916 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, 1917 const EdgeInfo &EI); 1918 1919 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can 1920 /// be vectorized to use the original vector (or aggregate "bitcast" to a 1921 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise 1922 /// returns false, setting \p CurrentOrder to either an empty vector or a 1923 /// non-identity permutation that allows to reuse extract instructions. 1924 bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 1925 SmallVectorImpl<unsigned> &CurrentOrder) const; 1926 1927 /// Vectorize a single entry in the tree. 1928 Value *vectorizeTree(TreeEntry *E); 1929 1930 /// Vectorize a single entry in the tree, starting in \p VL. 1931 Value *vectorizeTree(ArrayRef<Value *> VL); 1932 1933 /// \returns the scalarization cost for this type. Scalarization in this 1934 /// context means the creation of vectors from a group of scalars. If \p 1935 /// NeedToShuffle is true, need to add a cost of reshuffling some of the 1936 /// vector elements. 1937 InstructionCost getGatherCost(FixedVectorType *Ty, 1938 const APInt &ShuffledIndices, 1939 bool NeedToShuffle) const; 1940 1941 /// Checks if the gathered \p VL can be represented as shuffle(s) of previous 1942 /// tree entries. 1943 /// \returns ShuffleKind, if gathered values can be represented as shuffles of 1944 /// previous tree entries. \p Mask is filled with the shuffle mask. 1945 Optional<TargetTransformInfo::ShuffleKind> 1946 isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 1947 SmallVectorImpl<const TreeEntry *> &Entries); 1948 1949 /// \returns the scalarization cost for this list of values. Assuming that 1950 /// this subtree gets vectorized, we may need to extract the values from the 1951 /// roots. This method calculates the cost of extracting the values. 1952 InstructionCost getGatherCost(ArrayRef<Value *> VL) const; 1953 1954 /// Set the Builder insert point to one after the last instruction in 1955 /// the bundle 1956 void setInsertPointAfterBundle(const TreeEntry *E); 1957 1958 /// \returns a vector from a collection of scalars in \p VL. 1959 Value *gather(ArrayRef<Value *> VL); 1960 1961 /// \returns whether the VectorizableTree is fully vectorizable and will 1962 /// be beneficial even the tree height is tiny. 1963 bool isFullyVectorizableTinyTree(bool ForReduction) const; 1964 1965 /// Reorder commutative or alt operands to get better probability of 1966 /// generating vectorized code. 1967 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 1968 SmallVectorImpl<Value *> &Left, 1969 SmallVectorImpl<Value *> &Right, 1970 const DataLayout &DL, 1971 ScalarEvolution &SE, 1972 const BoUpSLP &R); 1973 struct TreeEntry { 1974 using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>; 1975 TreeEntry(VecTreeTy &Container) : Container(Container) {} 1976 1977 /// \returns true if the scalars in VL are equal to this entry. 1978 bool isSame(ArrayRef<Value *> VL) const { 1979 auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) { 1980 if (Mask.size() != VL.size() && VL.size() == Scalars.size()) 1981 return std::equal(VL.begin(), VL.end(), Scalars.begin()); 1982 return VL.size() == Mask.size() && 1983 std::equal(VL.begin(), VL.end(), Mask.begin(), 1984 [Scalars](Value *V, int Idx) { 1985 return (isa<UndefValue>(V) && 1986 Idx == UndefMaskElem) || 1987 (Idx != UndefMaskElem && V == Scalars[Idx]); 1988 }); 1989 }; 1990 if (!ReorderIndices.empty()) { 1991 // TODO: implement matching if the nodes are just reordered, still can 1992 // treat the vector as the same if the list of scalars matches VL 1993 // directly, without reordering. 1994 SmallVector<int> Mask; 1995 inversePermutation(ReorderIndices, Mask); 1996 if (VL.size() == Scalars.size()) 1997 return IsSame(Scalars, Mask); 1998 if (VL.size() == ReuseShuffleIndices.size()) { 1999 ::addMask(Mask, ReuseShuffleIndices); 2000 return IsSame(Scalars, Mask); 2001 } 2002 return false; 2003 } 2004 return IsSame(Scalars, ReuseShuffleIndices); 2005 } 2006 2007 /// \returns true if current entry has same operands as \p TE. 2008 bool hasEqualOperands(const TreeEntry &TE) const { 2009 if (TE.getNumOperands() != getNumOperands()) 2010 return false; 2011 SmallBitVector Used(getNumOperands()); 2012 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) { 2013 unsigned PrevCount = Used.count(); 2014 for (unsigned K = 0; K < E; ++K) { 2015 if (Used.test(K)) 2016 continue; 2017 if (getOperand(K) == TE.getOperand(I)) { 2018 Used.set(K); 2019 break; 2020 } 2021 } 2022 // Check if we actually found the matching operand. 2023 if (PrevCount == Used.count()) 2024 return false; 2025 } 2026 return true; 2027 } 2028 2029 /// \return Final vectorization factor for the node. Defined by the total 2030 /// number of vectorized scalars, including those, used several times in the 2031 /// entry and counted in the \a ReuseShuffleIndices, if any. 2032 unsigned getVectorFactor() const { 2033 if (!ReuseShuffleIndices.empty()) 2034 return ReuseShuffleIndices.size(); 2035 return Scalars.size(); 2036 }; 2037 2038 /// A vector of scalars. 2039 ValueList Scalars; 2040 2041 /// The Scalars are vectorized into this value. It is initialized to Null. 2042 Value *VectorizedValue = nullptr; 2043 2044 /// Do we need to gather this sequence or vectorize it 2045 /// (either with vector instruction or with scatter/gather 2046 /// intrinsics for store/load)? 2047 enum EntryState { Vectorize, ScatterVectorize, NeedToGather }; 2048 EntryState State; 2049 2050 /// Does this sequence require some shuffling? 2051 SmallVector<int, 4> ReuseShuffleIndices; 2052 2053 /// Does this entry require reordering? 2054 SmallVector<unsigned, 4> ReorderIndices; 2055 2056 /// Points back to the VectorizableTree. 2057 /// 2058 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has 2059 /// to be a pointer and needs to be able to initialize the child iterator. 2060 /// Thus we need a reference back to the container to translate the indices 2061 /// to entries. 2062 VecTreeTy &Container; 2063 2064 /// The TreeEntry index containing the user of this entry. We can actually 2065 /// have multiple users so the data structure is not truly a tree. 2066 SmallVector<EdgeInfo, 1> UserTreeIndices; 2067 2068 /// The index of this treeEntry in VectorizableTree. 2069 int Idx = -1; 2070 2071 private: 2072 /// The operands of each instruction in each lane Operands[op_index][lane]. 2073 /// Note: This helps avoid the replication of the code that performs the 2074 /// reordering of operands during buildTree_rec() and vectorizeTree(). 2075 SmallVector<ValueList, 2> Operands; 2076 2077 /// The main/alternate instruction. 2078 Instruction *MainOp = nullptr; 2079 Instruction *AltOp = nullptr; 2080 2081 public: 2082 /// Set this bundle's \p OpIdx'th operand to \p OpVL. 2083 void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) { 2084 if (Operands.size() < OpIdx + 1) 2085 Operands.resize(OpIdx + 1); 2086 assert(Operands[OpIdx].empty() && "Already resized?"); 2087 assert(OpVL.size() <= Scalars.size() && 2088 "Number of operands is greater than the number of scalars."); 2089 Operands[OpIdx].resize(OpVL.size()); 2090 copy(OpVL, Operands[OpIdx].begin()); 2091 } 2092 2093 /// Set the operands of this bundle in their original order. 2094 void setOperandsInOrder() { 2095 assert(Operands.empty() && "Already initialized?"); 2096 auto *I0 = cast<Instruction>(Scalars[0]); 2097 Operands.resize(I0->getNumOperands()); 2098 unsigned NumLanes = Scalars.size(); 2099 for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands(); 2100 OpIdx != NumOperands; ++OpIdx) { 2101 Operands[OpIdx].resize(NumLanes); 2102 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 2103 auto *I = cast<Instruction>(Scalars[Lane]); 2104 assert(I->getNumOperands() == NumOperands && 2105 "Expected same number of operands"); 2106 Operands[OpIdx][Lane] = I->getOperand(OpIdx); 2107 } 2108 } 2109 } 2110 2111 /// Reorders operands of the node to the given mask \p Mask. 2112 void reorderOperands(ArrayRef<int> Mask) { 2113 for (ValueList &Operand : Operands) 2114 reorderScalars(Operand, Mask); 2115 } 2116 2117 /// \returns the \p OpIdx operand of this TreeEntry. 2118 ValueList &getOperand(unsigned OpIdx) { 2119 assert(OpIdx < Operands.size() && "Off bounds"); 2120 return Operands[OpIdx]; 2121 } 2122 2123 /// \returns the \p OpIdx operand of this TreeEntry. 2124 ArrayRef<Value *> getOperand(unsigned OpIdx) const { 2125 assert(OpIdx < Operands.size() && "Off bounds"); 2126 return Operands[OpIdx]; 2127 } 2128 2129 /// \returns the number of operands. 2130 unsigned getNumOperands() const { return Operands.size(); } 2131 2132 /// \return the single \p OpIdx operand. 2133 Value *getSingleOperand(unsigned OpIdx) const { 2134 assert(OpIdx < Operands.size() && "Off bounds"); 2135 assert(!Operands[OpIdx].empty() && "No operand available"); 2136 return Operands[OpIdx][0]; 2137 } 2138 2139 /// Some of the instructions in the list have alternate opcodes. 2140 bool isAltShuffle() const { return MainOp != AltOp; } 2141 2142 bool isOpcodeOrAlt(Instruction *I) const { 2143 unsigned CheckedOpcode = I->getOpcode(); 2144 return (getOpcode() == CheckedOpcode || 2145 getAltOpcode() == CheckedOpcode); 2146 } 2147 2148 /// Chooses the correct key for scheduling data. If \p Op has the same (or 2149 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is 2150 /// \p OpValue. 2151 Value *isOneOf(Value *Op) const { 2152 auto *I = dyn_cast<Instruction>(Op); 2153 if (I && isOpcodeOrAlt(I)) 2154 return Op; 2155 return MainOp; 2156 } 2157 2158 void setOperations(const InstructionsState &S) { 2159 MainOp = S.MainOp; 2160 AltOp = S.AltOp; 2161 } 2162 2163 Instruction *getMainOp() const { 2164 return MainOp; 2165 } 2166 2167 Instruction *getAltOp() const { 2168 return AltOp; 2169 } 2170 2171 /// The main/alternate opcodes for the list of instructions. 2172 unsigned getOpcode() const { 2173 return MainOp ? MainOp->getOpcode() : 0; 2174 } 2175 2176 unsigned getAltOpcode() const { 2177 return AltOp ? AltOp->getOpcode() : 0; 2178 } 2179 2180 /// When ReuseReorderShuffleIndices is empty it just returns position of \p 2181 /// V within vector of Scalars. Otherwise, try to remap on its reuse index. 2182 int findLaneForValue(Value *V) const { 2183 unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V)); 2184 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 2185 if (!ReorderIndices.empty()) 2186 FoundLane = ReorderIndices[FoundLane]; 2187 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 2188 if (!ReuseShuffleIndices.empty()) { 2189 FoundLane = std::distance(ReuseShuffleIndices.begin(), 2190 find(ReuseShuffleIndices, FoundLane)); 2191 } 2192 return FoundLane; 2193 } 2194 2195 #ifndef NDEBUG 2196 /// Debug printer. 2197 LLVM_DUMP_METHOD void dump() const { 2198 dbgs() << Idx << ".\n"; 2199 for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) { 2200 dbgs() << "Operand " << OpI << ":\n"; 2201 for (const Value *V : Operands[OpI]) 2202 dbgs().indent(2) << *V << "\n"; 2203 } 2204 dbgs() << "Scalars: \n"; 2205 for (Value *V : Scalars) 2206 dbgs().indent(2) << *V << "\n"; 2207 dbgs() << "State: "; 2208 switch (State) { 2209 case Vectorize: 2210 dbgs() << "Vectorize\n"; 2211 break; 2212 case ScatterVectorize: 2213 dbgs() << "ScatterVectorize\n"; 2214 break; 2215 case NeedToGather: 2216 dbgs() << "NeedToGather\n"; 2217 break; 2218 } 2219 dbgs() << "MainOp: "; 2220 if (MainOp) 2221 dbgs() << *MainOp << "\n"; 2222 else 2223 dbgs() << "NULL\n"; 2224 dbgs() << "AltOp: "; 2225 if (AltOp) 2226 dbgs() << *AltOp << "\n"; 2227 else 2228 dbgs() << "NULL\n"; 2229 dbgs() << "VectorizedValue: "; 2230 if (VectorizedValue) 2231 dbgs() << *VectorizedValue << "\n"; 2232 else 2233 dbgs() << "NULL\n"; 2234 dbgs() << "ReuseShuffleIndices: "; 2235 if (ReuseShuffleIndices.empty()) 2236 dbgs() << "Empty"; 2237 else 2238 for (int ReuseIdx : ReuseShuffleIndices) 2239 dbgs() << ReuseIdx << ", "; 2240 dbgs() << "\n"; 2241 dbgs() << "ReorderIndices: "; 2242 for (unsigned ReorderIdx : ReorderIndices) 2243 dbgs() << ReorderIdx << ", "; 2244 dbgs() << "\n"; 2245 dbgs() << "UserTreeIndices: "; 2246 for (const auto &EInfo : UserTreeIndices) 2247 dbgs() << EInfo << ", "; 2248 dbgs() << "\n"; 2249 } 2250 #endif 2251 }; 2252 2253 #ifndef NDEBUG 2254 void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost, 2255 InstructionCost VecCost, 2256 InstructionCost ScalarCost) const { 2257 dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump(); 2258 dbgs() << "SLP: Costs:\n"; 2259 dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n"; 2260 dbgs() << "SLP: VectorCost = " << VecCost << "\n"; 2261 dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n"; 2262 dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = " << 2263 ReuseShuffleCost + VecCost - ScalarCost << "\n"; 2264 } 2265 #endif 2266 2267 /// Create a new VectorizableTree entry. 2268 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle, 2269 const InstructionsState &S, 2270 const EdgeInfo &UserTreeIdx, 2271 ArrayRef<int> ReuseShuffleIndices = None, 2272 ArrayRef<unsigned> ReorderIndices = None) { 2273 TreeEntry::EntryState EntryState = 2274 Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather; 2275 return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx, 2276 ReuseShuffleIndices, ReorderIndices); 2277 } 2278 2279 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, 2280 TreeEntry::EntryState EntryState, 2281 Optional<ScheduleData *> Bundle, 2282 const InstructionsState &S, 2283 const EdgeInfo &UserTreeIdx, 2284 ArrayRef<int> ReuseShuffleIndices = None, 2285 ArrayRef<unsigned> ReorderIndices = None) { 2286 assert(((!Bundle && EntryState == TreeEntry::NeedToGather) || 2287 (Bundle && EntryState != TreeEntry::NeedToGather)) && 2288 "Need to vectorize gather entry?"); 2289 VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree)); 2290 TreeEntry *Last = VectorizableTree.back().get(); 2291 Last->Idx = VectorizableTree.size() - 1; 2292 Last->State = EntryState; 2293 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(), 2294 ReuseShuffleIndices.end()); 2295 if (ReorderIndices.empty()) { 2296 Last->Scalars.assign(VL.begin(), VL.end()); 2297 Last->setOperations(S); 2298 } else { 2299 // Reorder scalars and build final mask. 2300 Last->Scalars.assign(VL.size(), nullptr); 2301 transform(ReorderIndices, Last->Scalars.begin(), 2302 [VL](unsigned Idx) -> Value * { 2303 if (Idx >= VL.size()) 2304 return UndefValue::get(VL.front()->getType()); 2305 return VL[Idx]; 2306 }); 2307 InstructionsState S = getSameOpcode(Last->Scalars); 2308 Last->setOperations(S); 2309 Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end()); 2310 } 2311 if (Last->State != TreeEntry::NeedToGather) { 2312 for (Value *V : VL) { 2313 assert(!getTreeEntry(V) && "Scalar already in tree!"); 2314 ScalarToTreeEntry[V] = Last; 2315 } 2316 // Update the scheduler bundle to point to this TreeEntry. 2317 unsigned Lane = 0; 2318 for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember; 2319 BundleMember = BundleMember->NextInBundle) { 2320 BundleMember->TE = Last; 2321 BundleMember->Lane = Lane; 2322 ++Lane; 2323 } 2324 assert((!Bundle.getValue() || Lane == VL.size()) && 2325 "Bundle and VL out of sync"); 2326 } else { 2327 MustGather.insert(VL.begin(), VL.end()); 2328 } 2329 2330 if (UserTreeIdx.UserTE) 2331 Last->UserTreeIndices.push_back(UserTreeIdx); 2332 2333 return Last; 2334 } 2335 2336 /// -- Vectorization State -- 2337 /// Holds all of the tree entries. 2338 TreeEntry::VecTreeTy VectorizableTree; 2339 2340 #ifndef NDEBUG 2341 /// Debug printer. 2342 LLVM_DUMP_METHOD void dumpVectorizableTree() const { 2343 for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) { 2344 VectorizableTree[Id]->dump(); 2345 dbgs() << "\n"; 2346 } 2347 } 2348 #endif 2349 2350 TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); } 2351 2352 const TreeEntry *getTreeEntry(Value *V) const { 2353 return ScalarToTreeEntry.lookup(V); 2354 } 2355 2356 /// Maps a specific scalar to its tree entry. 2357 SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry; 2358 2359 /// Maps a value to the proposed vectorizable size. 2360 SmallDenseMap<Value *, unsigned> InstrElementSize; 2361 2362 /// A list of scalars that we found that we need to keep as scalars. 2363 ValueSet MustGather; 2364 2365 /// This POD struct describes one external user in the vectorized tree. 2366 struct ExternalUser { 2367 ExternalUser(Value *S, llvm::User *U, int L) 2368 : Scalar(S), User(U), Lane(L) {} 2369 2370 // Which scalar in our function. 2371 Value *Scalar; 2372 2373 // Which user that uses the scalar. 2374 llvm::User *User; 2375 2376 // Which lane does the scalar belong to. 2377 int Lane; 2378 }; 2379 using UserList = SmallVector<ExternalUser, 16>; 2380 2381 /// Checks if two instructions may access the same memory. 2382 /// 2383 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it 2384 /// is invariant in the calling loop. 2385 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1, 2386 Instruction *Inst2) { 2387 // First check if the result is already in the cache. 2388 AliasCacheKey key = std::make_pair(Inst1, Inst2); 2389 Optional<bool> &result = AliasCache[key]; 2390 if (result.hasValue()) { 2391 return result.getValue(); 2392 } 2393 bool aliased = true; 2394 if (Loc1.Ptr && isSimple(Inst1)) 2395 aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1)); 2396 // Store the result in the cache. 2397 result = aliased; 2398 return aliased; 2399 } 2400 2401 using AliasCacheKey = std::pair<Instruction *, Instruction *>; 2402 2403 /// Cache for alias results. 2404 /// TODO: consider moving this to the AliasAnalysis itself. 2405 DenseMap<AliasCacheKey, Optional<bool>> AliasCache; 2406 2407 /// Removes an instruction from its block and eventually deletes it. 2408 /// It's like Instruction::eraseFromParent() except that the actual deletion 2409 /// is delayed until BoUpSLP is destructed. 2410 /// This is required to ensure that there are no incorrect collisions in the 2411 /// AliasCache, which can happen if a new instruction is allocated at the 2412 /// same address as a previously deleted instruction. 2413 void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) { 2414 auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first; 2415 It->getSecond() = It->getSecond() && ReplaceOpsWithUndef; 2416 } 2417 2418 /// Temporary store for deleted instructions. Instructions will be deleted 2419 /// eventually when the BoUpSLP is destructed. 2420 DenseMap<Instruction *, bool> DeletedInstructions; 2421 2422 /// A list of values that need to extracted out of the tree. 2423 /// This list holds pairs of (Internal Scalar : External User). External User 2424 /// can be nullptr, it means that this Internal Scalar will be used later, 2425 /// after vectorization. 2426 UserList ExternalUses; 2427 2428 /// Values used only by @llvm.assume calls. 2429 SmallPtrSet<const Value *, 32> EphValues; 2430 2431 /// Holds all of the instructions that we gathered. 2432 SetVector<Instruction *> GatherShuffleSeq; 2433 2434 /// A list of blocks that we are going to CSE. 2435 SetVector<BasicBlock *> CSEBlocks; 2436 2437 /// Contains all scheduling relevant data for an instruction. 2438 /// A ScheduleData either represents a single instruction or a member of an 2439 /// instruction bundle (= a group of instructions which is combined into a 2440 /// vector instruction). 2441 struct ScheduleData { 2442 // The initial value for the dependency counters. It means that the 2443 // dependencies are not calculated yet. 2444 enum { InvalidDeps = -1 }; 2445 2446 ScheduleData() = default; 2447 2448 void init(int BlockSchedulingRegionID, Value *OpVal) { 2449 FirstInBundle = this; 2450 NextInBundle = nullptr; 2451 NextLoadStore = nullptr; 2452 IsScheduled = false; 2453 SchedulingRegionID = BlockSchedulingRegionID; 2454 clearDependencies(); 2455 OpValue = OpVal; 2456 TE = nullptr; 2457 Lane = -1; 2458 } 2459 2460 /// Verify basic self consistency properties 2461 void verify() { 2462 if (hasValidDependencies()) { 2463 assert(UnscheduledDeps <= Dependencies && "invariant"); 2464 } else { 2465 assert(UnscheduledDeps == Dependencies && "invariant"); 2466 } 2467 2468 if (IsScheduled) { 2469 assert(isSchedulingEntity() && 2470 "unexpected scheduled state"); 2471 for (const ScheduleData *BundleMember = this; BundleMember; 2472 BundleMember = BundleMember->NextInBundle) { 2473 assert(BundleMember->hasValidDependencies() && 2474 BundleMember->UnscheduledDeps == 0 && 2475 "unexpected scheduled state"); 2476 assert((BundleMember == this || !BundleMember->IsScheduled) && 2477 "only bundle is marked scheduled"); 2478 } 2479 } 2480 } 2481 2482 /// Returns true if the dependency information has been calculated. 2483 /// Note that depenendency validity can vary between instructions within 2484 /// a single bundle. 2485 bool hasValidDependencies() const { return Dependencies != InvalidDeps; } 2486 2487 /// Returns true for single instructions and for bundle representatives 2488 /// (= the head of a bundle). 2489 bool isSchedulingEntity() const { return FirstInBundle == this; } 2490 2491 /// Returns true if it represents an instruction bundle and not only a 2492 /// single instruction. 2493 bool isPartOfBundle() const { 2494 return NextInBundle != nullptr || FirstInBundle != this; 2495 } 2496 2497 /// Returns true if it is ready for scheduling, i.e. it has no more 2498 /// unscheduled depending instructions/bundles. 2499 bool isReady() const { 2500 assert(isSchedulingEntity() && 2501 "can't consider non-scheduling entity for ready list"); 2502 return unscheduledDepsInBundle() == 0 && !IsScheduled; 2503 } 2504 2505 /// Modifies the number of unscheduled dependencies for this instruction, 2506 /// and returns the number of remaining dependencies for the containing 2507 /// bundle. 2508 int incrementUnscheduledDeps(int Incr) { 2509 assert(hasValidDependencies() && 2510 "increment of unscheduled deps would be meaningless"); 2511 UnscheduledDeps += Incr; 2512 return FirstInBundle->unscheduledDepsInBundle(); 2513 } 2514 2515 /// Sets the number of unscheduled dependencies to the number of 2516 /// dependencies. 2517 void resetUnscheduledDeps() { 2518 UnscheduledDeps = Dependencies; 2519 } 2520 2521 /// Clears all dependency information. 2522 void clearDependencies() { 2523 Dependencies = InvalidDeps; 2524 resetUnscheduledDeps(); 2525 MemoryDependencies.clear(); 2526 } 2527 2528 int unscheduledDepsInBundle() const { 2529 assert(isSchedulingEntity() && "only meaningful on the bundle"); 2530 int Sum = 0; 2531 for (const ScheduleData *BundleMember = this; BundleMember; 2532 BundleMember = BundleMember->NextInBundle) { 2533 if (BundleMember->UnscheduledDeps == InvalidDeps) 2534 return InvalidDeps; 2535 Sum += BundleMember->UnscheduledDeps; 2536 } 2537 return Sum; 2538 } 2539 2540 void dump(raw_ostream &os) const { 2541 if (!isSchedulingEntity()) { 2542 os << "/ " << *Inst; 2543 } else if (NextInBundle) { 2544 os << '[' << *Inst; 2545 ScheduleData *SD = NextInBundle; 2546 while (SD) { 2547 os << ';' << *SD->Inst; 2548 SD = SD->NextInBundle; 2549 } 2550 os << ']'; 2551 } else { 2552 os << *Inst; 2553 } 2554 } 2555 2556 Instruction *Inst = nullptr; 2557 2558 /// Opcode of the current instruction in the schedule data. 2559 Value *OpValue = nullptr; 2560 2561 /// The TreeEntry that this instruction corresponds to. 2562 TreeEntry *TE = nullptr; 2563 2564 /// Points to the head in an instruction bundle (and always to this for 2565 /// single instructions). 2566 ScheduleData *FirstInBundle = nullptr; 2567 2568 /// Single linked list of all instructions in a bundle. Null if it is a 2569 /// single instruction. 2570 ScheduleData *NextInBundle = nullptr; 2571 2572 /// Single linked list of all memory instructions (e.g. load, store, call) 2573 /// in the block - until the end of the scheduling region. 2574 ScheduleData *NextLoadStore = nullptr; 2575 2576 /// The dependent memory instructions. 2577 /// This list is derived on demand in calculateDependencies(). 2578 SmallVector<ScheduleData *, 4> MemoryDependencies; 2579 2580 /// This ScheduleData is in the current scheduling region if this matches 2581 /// the current SchedulingRegionID of BlockScheduling. 2582 int SchedulingRegionID = 0; 2583 2584 /// The number of dependencies. Constitutes of the number of users of the 2585 /// instruction plus the number of dependent memory instructions (if any). 2586 /// This value is calculated on demand. 2587 /// If InvalidDeps, the number of dependencies is not calculated yet. 2588 int Dependencies = InvalidDeps; 2589 2590 /// The number of dependencies minus the number of dependencies of scheduled 2591 /// instructions. As soon as this is zero, the instruction/bundle gets ready 2592 /// for scheduling. 2593 /// Note that this is negative as long as Dependencies is not calculated. 2594 int UnscheduledDeps = InvalidDeps; 2595 2596 /// The lane of this node in the TreeEntry. 2597 int Lane = -1; 2598 2599 /// True if this instruction is scheduled (or considered as scheduled in the 2600 /// dry-run). 2601 bool IsScheduled = false; 2602 }; 2603 2604 #ifndef NDEBUG 2605 friend inline raw_ostream &operator<<(raw_ostream &os, 2606 const BoUpSLP::ScheduleData &SD) { 2607 SD.dump(os); 2608 return os; 2609 } 2610 #endif 2611 2612 friend struct GraphTraits<BoUpSLP *>; 2613 friend struct DOTGraphTraits<BoUpSLP *>; 2614 2615 /// Contains all scheduling data for a basic block. 2616 struct BlockScheduling { 2617 BlockScheduling(BasicBlock *BB) 2618 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {} 2619 2620 void clear() { 2621 ReadyInsts.clear(); 2622 ScheduleStart = nullptr; 2623 ScheduleEnd = nullptr; 2624 FirstLoadStoreInRegion = nullptr; 2625 LastLoadStoreInRegion = nullptr; 2626 2627 // Reduce the maximum schedule region size by the size of the 2628 // previous scheduling run. 2629 ScheduleRegionSizeLimit -= ScheduleRegionSize; 2630 if (ScheduleRegionSizeLimit < MinScheduleRegionSize) 2631 ScheduleRegionSizeLimit = MinScheduleRegionSize; 2632 ScheduleRegionSize = 0; 2633 2634 // Make a new scheduling region, i.e. all existing ScheduleData is not 2635 // in the new region yet. 2636 ++SchedulingRegionID; 2637 } 2638 2639 ScheduleData *getScheduleData(Instruction *I) { 2640 if (BB != I->getParent()) 2641 // Avoid lookup if can't possibly be in map. 2642 return nullptr; 2643 ScheduleData *SD = ScheduleDataMap[I]; 2644 if (SD && isInSchedulingRegion(SD)) 2645 return SD; 2646 return nullptr; 2647 } 2648 2649 ScheduleData *getScheduleData(Value *V) { 2650 if (auto *I = dyn_cast<Instruction>(V)) 2651 return getScheduleData(I); 2652 return nullptr; 2653 } 2654 2655 ScheduleData *getScheduleData(Value *V, Value *Key) { 2656 if (V == Key) 2657 return getScheduleData(V); 2658 auto I = ExtraScheduleDataMap.find(V); 2659 if (I != ExtraScheduleDataMap.end()) { 2660 ScheduleData *SD = I->second[Key]; 2661 if (SD && isInSchedulingRegion(SD)) 2662 return SD; 2663 } 2664 return nullptr; 2665 } 2666 2667 bool isInSchedulingRegion(ScheduleData *SD) const { 2668 return SD->SchedulingRegionID == SchedulingRegionID; 2669 } 2670 2671 /// Marks an instruction as scheduled and puts all dependent ready 2672 /// instructions into the ready-list. 2673 template <typename ReadyListType> 2674 void schedule(ScheduleData *SD, ReadyListType &ReadyList) { 2675 SD->IsScheduled = true; 2676 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n"); 2677 2678 for (ScheduleData *BundleMember = SD; BundleMember; 2679 BundleMember = BundleMember->NextInBundle) { 2680 if (BundleMember->Inst != BundleMember->OpValue) 2681 continue; 2682 2683 // Handle the def-use chain dependencies. 2684 2685 // Decrement the unscheduled counter and insert to ready list if ready. 2686 auto &&DecrUnsched = [this, &ReadyList](Instruction *I) { 2687 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) { 2688 if (OpDef && OpDef->hasValidDependencies() && 2689 OpDef->incrementUnscheduledDeps(-1) == 0) { 2690 // There are no more unscheduled dependencies after 2691 // decrementing, so we can put the dependent instruction 2692 // into the ready list. 2693 ScheduleData *DepBundle = OpDef->FirstInBundle; 2694 assert(!DepBundle->IsScheduled && 2695 "already scheduled bundle gets ready"); 2696 ReadyList.insert(DepBundle); 2697 LLVM_DEBUG(dbgs() 2698 << "SLP: gets ready (def): " << *DepBundle << "\n"); 2699 } 2700 }); 2701 }; 2702 2703 // If BundleMember is a vector bundle, its operands may have been 2704 // reordered during buildTree(). We therefore need to get its operands 2705 // through the TreeEntry. 2706 if (TreeEntry *TE = BundleMember->TE) { 2707 int Lane = BundleMember->Lane; 2708 assert(Lane >= 0 && "Lane not set"); 2709 2710 // Since vectorization tree is being built recursively this assertion 2711 // ensures that the tree entry has all operands set before reaching 2712 // this code. Couple of exceptions known at the moment are extracts 2713 // where their second (immediate) operand is not added. Since 2714 // immediates do not affect scheduler behavior this is considered 2715 // okay. 2716 auto *In = TE->getMainOp(); 2717 assert(In && 2718 (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) || 2719 In->getNumOperands() == TE->getNumOperands()) && 2720 "Missed TreeEntry operands?"); 2721 (void)In; // fake use to avoid build failure when assertions disabled 2722 2723 for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands(); 2724 OpIdx != NumOperands; ++OpIdx) 2725 if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane])) 2726 DecrUnsched(I); 2727 } else { 2728 // If BundleMember is a stand-alone instruction, no operand reordering 2729 // has taken place, so we directly access its operands. 2730 for (Use &U : BundleMember->Inst->operands()) 2731 if (auto *I = dyn_cast<Instruction>(U.get())) 2732 DecrUnsched(I); 2733 } 2734 // Handle the memory dependencies. 2735 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) { 2736 if (MemoryDepSD->hasValidDependencies() && 2737 MemoryDepSD->incrementUnscheduledDeps(-1) == 0) { 2738 // There are no more unscheduled dependencies after decrementing, 2739 // so we can put the dependent instruction into the ready list. 2740 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle; 2741 assert(!DepBundle->IsScheduled && 2742 "already scheduled bundle gets ready"); 2743 ReadyList.insert(DepBundle); 2744 LLVM_DEBUG(dbgs() 2745 << "SLP: gets ready (mem): " << *DepBundle << "\n"); 2746 } 2747 } 2748 } 2749 } 2750 2751 /// Verify basic self consistency properties of the data structure. 2752 void verify() { 2753 if (!ScheduleStart) 2754 return; 2755 2756 assert(ScheduleStart->getParent() == ScheduleEnd->getParent() && 2757 ScheduleStart->comesBefore(ScheduleEnd) && 2758 "Not a valid scheduling region?"); 2759 2760 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 2761 auto *SD = getScheduleData(I); 2762 assert(SD && "primary scheduledata must exist in window"); 2763 assert(isInSchedulingRegion(SD) && 2764 "primary schedule data not in window?"); 2765 assert(isInSchedulingRegion(SD->FirstInBundle) && 2766 "entire bundle in window!"); 2767 (void)SD; 2768 doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); }); 2769 } 2770 2771 for (auto *SD : ReadyInsts) { 2772 assert(SD->isSchedulingEntity() && SD->isReady() && 2773 "item in ready list not ready?"); 2774 (void)SD; 2775 } 2776 } 2777 2778 void doForAllOpcodes(Value *V, 2779 function_ref<void(ScheduleData *SD)> Action) { 2780 if (ScheduleData *SD = getScheduleData(V)) 2781 Action(SD); 2782 auto I = ExtraScheduleDataMap.find(V); 2783 if (I != ExtraScheduleDataMap.end()) 2784 for (auto &P : I->second) 2785 if (isInSchedulingRegion(P.second)) 2786 Action(P.second); 2787 } 2788 2789 /// Put all instructions into the ReadyList which are ready for scheduling. 2790 template <typename ReadyListType> 2791 void initialFillReadyList(ReadyListType &ReadyList) { 2792 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 2793 doForAllOpcodes(I, [&](ScheduleData *SD) { 2794 if (SD->isSchedulingEntity() && SD->hasValidDependencies() && 2795 SD->isReady()) { 2796 ReadyList.insert(SD); 2797 LLVM_DEBUG(dbgs() 2798 << "SLP: initially in ready list: " << *SD << "\n"); 2799 } 2800 }); 2801 } 2802 } 2803 2804 /// Build a bundle from the ScheduleData nodes corresponding to the 2805 /// scalar instruction for each lane. 2806 ScheduleData *buildBundle(ArrayRef<Value *> VL); 2807 2808 /// Checks if a bundle of instructions can be scheduled, i.e. has no 2809 /// cyclic dependencies. This is only a dry-run, no instructions are 2810 /// actually moved at this stage. 2811 /// \returns the scheduling bundle. The returned Optional value is non-None 2812 /// if \p VL is allowed to be scheduled. 2813 Optional<ScheduleData *> 2814 tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 2815 const InstructionsState &S); 2816 2817 /// Un-bundles a group of instructions. 2818 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue); 2819 2820 /// Allocates schedule data chunk. 2821 ScheduleData *allocateScheduleDataChunks(); 2822 2823 /// Extends the scheduling region so that V is inside the region. 2824 /// \returns true if the region size is within the limit. 2825 bool extendSchedulingRegion(Value *V, const InstructionsState &S); 2826 2827 /// Initialize the ScheduleData structures for new instructions in the 2828 /// scheduling region. 2829 void initScheduleData(Instruction *FromI, Instruction *ToI, 2830 ScheduleData *PrevLoadStore, 2831 ScheduleData *NextLoadStore); 2832 2833 /// Updates the dependency information of a bundle and of all instructions/ 2834 /// bundles which depend on the original bundle. 2835 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList, 2836 BoUpSLP *SLP); 2837 2838 /// Sets all instruction in the scheduling region to un-scheduled. 2839 void resetSchedule(); 2840 2841 BasicBlock *BB; 2842 2843 /// Simple memory allocation for ScheduleData. 2844 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks; 2845 2846 /// The size of a ScheduleData array in ScheduleDataChunks. 2847 int ChunkSize; 2848 2849 /// The allocator position in the current chunk, which is the last entry 2850 /// of ScheduleDataChunks. 2851 int ChunkPos; 2852 2853 /// Attaches ScheduleData to Instruction. 2854 /// Note that the mapping survives during all vectorization iterations, i.e. 2855 /// ScheduleData structures are recycled. 2856 DenseMap<Instruction *, ScheduleData *> ScheduleDataMap; 2857 2858 /// Attaches ScheduleData to Instruction with the leading key. 2859 DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>> 2860 ExtraScheduleDataMap; 2861 2862 /// The ready-list for scheduling (only used for the dry-run). 2863 SetVector<ScheduleData *> ReadyInsts; 2864 2865 /// The first instruction of the scheduling region. 2866 Instruction *ScheduleStart = nullptr; 2867 2868 /// The first instruction _after_ the scheduling region. 2869 Instruction *ScheduleEnd = nullptr; 2870 2871 /// The first memory accessing instruction in the scheduling region 2872 /// (can be null). 2873 ScheduleData *FirstLoadStoreInRegion = nullptr; 2874 2875 /// The last memory accessing instruction in the scheduling region 2876 /// (can be null). 2877 ScheduleData *LastLoadStoreInRegion = nullptr; 2878 2879 /// The current size of the scheduling region. 2880 int ScheduleRegionSize = 0; 2881 2882 /// The maximum size allowed for the scheduling region. 2883 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget; 2884 2885 /// The ID of the scheduling region. For a new vectorization iteration this 2886 /// is incremented which "removes" all ScheduleData from the region. 2887 /// Make sure that the initial SchedulingRegionID is greater than the 2888 /// initial SchedulingRegionID in ScheduleData (which is 0). 2889 int SchedulingRegionID = 1; 2890 }; 2891 2892 /// Attaches the BlockScheduling structures to basic blocks. 2893 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules; 2894 2895 /// Performs the "real" scheduling. Done before vectorization is actually 2896 /// performed in a basic block. 2897 void scheduleBlock(BlockScheduling *BS); 2898 2899 /// List of users to ignore during scheduling and that don't need extracting. 2900 ArrayRef<Value *> UserIgnoreList; 2901 2902 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of 2903 /// sorted SmallVectors of unsigned. 2904 struct OrdersTypeDenseMapInfo { 2905 static OrdersType getEmptyKey() { 2906 OrdersType V; 2907 V.push_back(~1U); 2908 return V; 2909 } 2910 2911 static OrdersType getTombstoneKey() { 2912 OrdersType V; 2913 V.push_back(~2U); 2914 return V; 2915 } 2916 2917 static unsigned getHashValue(const OrdersType &V) { 2918 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 2919 } 2920 2921 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) { 2922 return LHS == RHS; 2923 } 2924 }; 2925 2926 // Analysis and block reference. 2927 Function *F; 2928 ScalarEvolution *SE; 2929 TargetTransformInfo *TTI; 2930 TargetLibraryInfo *TLI; 2931 AAResults *AA; 2932 LoopInfo *LI; 2933 DominatorTree *DT; 2934 AssumptionCache *AC; 2935 DemandedBits *DB; 2936 const DataLayout *DL; 2937 OptimizationRemarkEmitter *ORE; 2938 2939 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt. 2940 unsigned MinVecRegSize; // Set by cl::opt (default: 128). 2941 2942 /// Instruction builder to construct the vectorized tree. 2943 IRBuilder<> Builder; 2944 2945 /// A map of scalar integer values to the smallest bit width with which they 2946 /// can legally be represented. The values map to (width, signed) pairs, 2947 /// where "width" indicates the minimum bit width and "signed" is True if the 2948 /// value must be signed-extended, rather than zero-extended, back to its 2949 /// original width. 2950 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs; 2951 }; 2952 2953 } // end namespace slpvectorizer 2954 2955 template <> struct GraphTraits<BoUpSLP *> { 2956 using TreeEntry = BoUpSLP::TreeEntry; 2957 2958 /// NodeRef has to be a pointer per the GraphWriter. 2959 using NodeRef = TreeEntry *; 2960 2961 using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy; 2962 2963 /// Add the VectorizableTree to the index iterator to be able to return 2964 /// TreeEntry pointers. 2965 struct ChildIteratorType 2966 : public iterator_adaptor_base< 2967 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> { 2968 ContainerTy &VectorizableTree; 2969 2970 ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W, 2971 ContainerTy &VT) 2972 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {} 2973 2974 NodeRef operator*() { return I->UserTE; } 2975 }; 2976 2977 static NodeRef getEntryNode(BoUpSLP &R) { 2978 return R.VectorizableTree[0].get(); 2979 } 2980 2981 static ChildIteratorType child_begin(NodeRef N) { 2982 return {N->UserTreeIndices.begin(), N->Container}; 2983 } 2984 2985 static ChildIteratorType child_end(NodeRef N) { 2986 return {N->UserTreeIndices.end(), N->Container}; 2987 } 2988 2989 /// For the node iterator we just need to turn the TreeEntry iterator into a 2990 /// TreeEntry* iterator so that it dereferences to NodeRef. 2991 class nodes_iterator { 2992 using ItTy = ContainerTy::iterator; 2993 ItTy It; 2994 2995 public: 2996 nodes_iterator(const ItTy &It2) : It(It2) {} 2997 NodeRef operator*() { return It->get(); } 2998 nodes_iterator operator++() { 2999 ++It; 3000 return *this; 3001 } 3002 bool operator!=(const nodes_iterator &N2) const { return N2.It != It; } 3003 }; 3004 3005 static nodes_iterator nodes_begin(BoUpSLP *R) { 3006 return nodes_iterator(R->VectorizableTree.begin()); 3007 } 3008 3009 static nodes_iterator nodes_end(BoUpSLP *R) { 3010 return nodes_iterator(R->VectorizableTree.end()); 3011 } 3012 3013 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); } 3014 }; 3015 3016 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits { 3017 using TreeEntry = BoUpSLP::TreeEntry; 3018 3019 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 3020 3021 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) { 3022 std::string Str; 3023 raw_string_ostream OS(Str); 3024 if (isSplat(Entry->Scalars)) 3025 OS << "<splat> "; 3026 for (auto V : Entry->Scalars) { 3027 OS << *V; 3028 if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) { 3029 return EU.Scalar == V; 3030 })) 3031 OS << " <extract>"; 3032 OS << "\n"; 3033 } 3034 return Str; 3035 } 3036 3037 static std::string getNodeAttributes(const TreeEntry *Entry, 3038 const BoUpSLP *) { 3039 if (Entry->State == TreeEntry::NeedToGather) 3040 return "color=red"; 3041 return ""; 3042 } 3043 }; 3044 3045 } // end namespace llvm 3046 3047 BoUpSLP::~BoUpSLP() { 3048 for (const auto &Pair : DeletedInstructions) { 3049 // Replace operands of ignored instructions with Undefs in case if they were 3050 // marked for deletion. 3051 if (Pair.getSecond()) { 3052 Value *Undef = UndefValue::get(Pair.getFirst()->getType()); 3053 Pair.getFirst()->replaceAllUsesWith(Undef); 3054 } 3055 Pair.getFirst()->dropAllReferences(); 3056 } 3057 for (const auto &Pair : DeletedInstructions) { 3058 assert(Pair.getFirst()->use_empty() && 3059 "trying to erase instruction with users."); 3060 Pair.getFirst()->eraseFromParent(); 3061 } 3062 #ifdef EXPENSIVE_CHECKS 3063 // If we could guarantee that this call is not extremely slow, we could 3064 // remove the ifdef limitation (see PR47712). 3065 assert(!verifyFunction(*F, &dbgs())); 3066 #endif 3067 } 3068 3069 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) { 3070 for (auto *V : AV) { 3071 if (auto *I = dyn_cast<Instruction>(V)) 3072 eraseInstruction(I, /*ReplaceOpsWithUndef=*/true); 3073 }; 3074 } 3075 3076 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses 3077 /// contains original mask for the scalars reused in the node. Procedure 3078 /// transform this mask in accordance with the given \p Mask. 3079 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) { 3080 assert(!Mask.empty() && Reuses.size() == Mask.size() && 3081 "Expected non-empty mask."); 3082 SmallVector<int> Prev(Reuses.begin(), Reuses.end()); 3083 Prev.swap(Reuses); 3084 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 3085 if (Mask[I] != UndefMaskElem) 3086 Reuses[Mask[I]] = Prev[I]; 3087 } 3088 3089 /// Reorders the given \p Order according to the given \p Mask. \p Order - is 3090 /// the original order of the scalars. Procedure transforms the provided order 3091 /// in accordance with the given \p Mask. If the resulting \p Order is just an 3092 /// identity order, \p Order is cleared. 3093 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) { 3094 assert(!Mask.empty() && "Expected non-empty mask."); 3095 SmallVector<int> MaskOrder; 3096 if (Order.empty()) { 3097 MaskOrder.resize(Mask.size()); 3098 std::iota(MaskOrder.begin(), MaskOrder.end(), 0); 3099 } else { 3100 inversePermutation(Order, MaskOrder); 3101 } 3102 reorderReuses(MaskOrder, Mask); 3103 if (ShuffleVectorInst::isIdentityMask(MaskOrder)) { 3104 Order.clear(); 3105 return; 3106 } 3107 Order.assign(Mask.size(), Mask.size()); 3108 for (unsigned I = 0, E = Mask.size(); I < E; ++I) 3109 if (MaskOrder[I] != UndefMaskElem) 3110 Order[MaskOrder[I]] = I; 3111 fixupOrderingIndices(Order); 3112 } 3113 3114 Optional<BoUpSLP::OrdersType> 3115 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) { 3116 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only."); 3117 unsigned NumScalars = TE.Scalars.size(); 3118 OrdersType CurrentOrder(NumScalars, NumScalars); 3119 SmallVector<int> Positions; 3120 SmallBitVector UsedPositions(NumScalars); 3121 const TreeEntry *STE = nullptr; 3122 // Try to find all gathered scalars that are gets vectorized in other 3123 // vectorize node. Here we can have only one single tree vector node to 3124 // correctly identify order of the gathered scalars. 3125 for (unsigned I = 0; I < NumScalars; ++I) { 3126 Value *V = TE.Scalars[I]; 3127 if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V)) 3128 continue; 3129 if (const auto *LocalSTE = getTreeEntry(V)) { 3130 if (!STE) 3131 STE = LocalSTE; 3132 else if (STE != LocalSTE) 3133 // Take the order only from the single vector node. 3134 return None; 3135 unsigned Lane = 3136 std::distance(STE->Scalars.begin(), find(STE->Scalars, V)); 3137 if (Lane >= NumScalars) 3138 return None; 3139 if (CurrentOrder[Lane] != NumScalars) { 3140 if (Lane != I) 3141 continue; 3142 UsedPositions.reset(CurrentOrder[Lane]); 3143 } 3144 // The partial identity (where only some elements of the gather node are 3145 // in the identity order) is good. 3146 CurrentOrder[Lane] = I; 3147 UsedPositions.set(I); 3148 } 3149 } 3150 // Need to keep the order if we have a vector entry and at least 2 scalars or 3151 // the vectorized entry has just 2 scalars. 3152 if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) { 3153 auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) { 3154 for (unsigned I = 0; I < NumScalars; ++I) 3155 if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars) 3156 return false; 3157 return true; 3158 }; 3159 if (IsIdentityOrder(CurrentOrder)) { 3160 CurrentOrder.clear(); 3161 return CurrentOrder; 3162 } 3163 auto *It = CurrentOrder.begin(); 3164 for (unsigned I = 0; I < NumScalars;) { 3165 if (UsedPositions.test(I)) { 3166 ++I; 3167 continue; 3168 } 3169 if (*It == NumScalars) { 3170 *It = I; 3171 ++I; 3172 } 3173 ++It; 3174 } 3175 return CurrentOrder; 3176 } 3177 return None; 3178 } 3179 3180 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE, 3181 bool TopToBottom) { 3182 // No need to reorder if need to shuffle reuses, still need to shuffle the 3183 // node. 3184 if (!TE.ReuseShuffleIndices.empty()) 3185 return None; 3186 if (TE.State == TreeEntry::Vectorize && 3187 (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) || 3188 (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) && 3189 !TE.isAltShuffle()) 3190 return TE.ReorderIndices; 3191 if (TE.State == TreeEntry::NeedToGather) { 3192 // TODO: add analysis of other gather nodes with extractelement 3193 // instructions and other values/instructions, not only undefs. 3194 if (((TE.getOpcode() == Instruction::ExtractElement && 3195 !TE.isAltShuffle()) || 3196 (all_of(TE.Scalars, 3197 [](Value *V) { 3198 return isa<UndefValue, ExtractElementInst>(V); 3199 }) && 3200 any_of(TE.Scalars, 3201 [](Value *V) { return isa<ExtractElementInst>(V); }))) && 3202 all_of(TE.Scalars, 3203 [](Value *V) { 3204 auto *EE = dyn_cast<ExtractElementInst>(V); 3205 return !EE || isa<FixedVectorType>(EE->getVectorOperandType()); 3206 }) && 3207 allSameType(TE.Scalars)) { 3208 // Check that gather of extractelements can be represented as 3209 // just a shuffle of a single vector. 3210 OrdersType CurrentOrder; 3211 bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder); 3212 if (Reuse || !CurrentOrder.empty()) { 3213 if (!CurrentOrder.empty()) 3214 fixupOrderingIndices(CurrentOrder); 3215 return CurrentOrder; 3216 } 3217 } 3218 if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE)) 3219 return CurrentOrder; 3220 } 3221 return None; 3222 } 3223 3224 void BoUpSLP::reorderTopToBottom() { 3225 // Maps VF to the graph nodes. 3226 DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries; 3227 // ExtractElement gather nodes which can be vectorized and need to handle 3228 // their ordering. 3229 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3230 // Find all reorderable nodes with the given VF. 3231 // Currently the are vectorized stores,loads,extracts + some gathering of 3232 // extracts. 3233 for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders]( 3234 const std::unique_ptr<TreeEntry> &TE) { 3235 if (Optional<OrdersType> CurrentOrder = 3236 getReorderingData(*TE.get(), /*TopToBottom=*/true)) { 3237 // Do not include ordering for nodes used in the alt opcode vectorization, 3238 // better to reorder them during bottom-to-top stage. If follow the order 3239 // here, it causes reordering of the whole graph though actually it is 3240 // profitable just to reorder the subgraph that starts from the alternate 3241 // opcode vectorization node. Such nodes already end-up with the shuffle 3242 // instruction and it is just enough to change this shuffle rather than 3243 // rotate the scalars for the whole graph. 3244 unsigned Cnt = 0; 3245 const TreeEntry *UserTE = TE.get(); 3246 while (UserTE && Cnt < RecursionMaxDepth) { 3247 if (UserTE->UserTreeIndices.size() != 1) 3248 break; 3249 if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) { 3250 return EI.UserTE->State == TreeEntry::Vectorize && 3251 EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0; 3252 })) 3253 return; 3254 if (UserTE->UserTreeIndices.empty()) 3255 UserTE = nullptr; 3256 else 3257 UserTE = UserTE->UserTreeIndices.back().UserTE; 3258 ++Cnt; 3259 } 3260 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 3261 if (TE->State != TreeEntry::Vectorize) 3262 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3263 } 3264 }); 3265 3266 // Reorder the graph nodes according to their vectorization factor. 3267 for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1; 3268 VF /= 2) { 3269 auto It = VFToOrderedEntries.find(VF); 3270 if (It == VFToOrderedEntries.end()) 3271 continue; 3272 // Try to find the most profitable order. We just are looking for the most 3273 // used order and reorder scalar elements in the nodes according to this 3274 // mostly used order. 3275 ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef(); 3276 // All operands are reordered and used only in this node - propagate the 3277 // most used order to the user node. 3278 MapVector<OrdersType, unsigned, 3279 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3280 OrdersUses; 3281 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3282 for (const TreeEntry *OpTE : OrderedEntries) { 3283 // No need to reorder this nodes, still need to extend and to use shuffle, 3284 // just need to merge reordering shuffle and the reuse shuffle. 3285 if (!OpTE->ReuseShuffleIndices.empty()) 3286 continue; 3287 // Count number of orders uses. 3288 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3289 if (OpTE->State == TreeEntry::NeedToGather) 3290 return GathersToOrders.find(OpTE)->second; 3291 return OpTE->ReorderIndices; 3292 }(); 3293 // Stores actually store the mask, not the order, need to invert. 3294 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3295 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3296 SmallVector<int> Mask; 3297 inversePermutation(Order, Mask); 3298 unsigned E = Order.size(); 3299 OrdersType CurrentOrder(E, E); 3300 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3301 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3302 }); 3303 fixupOrderingIndices(CurrentOrder); 3304 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 3305 } else { 3306 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 3307 } 3308 } 3309 // Set order of the user node. 3310 if (OrdersUses.empty()) 3311 continue; 3312 // Choose the most used order. 3313 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3314 unsigned Cnt = OrdersUses.front().second; 3315 for (const auto &Pair : drop_begin(OrdersUses)) { 3316 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3317 BestOrder = Pair.first; 3318 Cnt = Pair.second; 3319 } 3320 } 3321 // Set order of the user node. 3322 if (BestOrder.empty()) 3323 continue; 3324 SmallVector<int> Mask; 3325 inversePermutation(BestOrder, Mask); 3326 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3327 unsigned E = BestOrder.size(); 3328 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3329 return I < E ? static_cast<int>(I) : UndefMaskElem; 3330 }); 3331 // Do an actual reordering, if profitable. 3332 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 3333 // Just do the reordering for the nodes with the given VF. 3334 if (TE->Scalars.size() != VF) { 3335 if (TE->ReuseShuffleIndices.size() == VF) { 3336 // Need to reorder the reuses masks of the operands with smaller VF to 3337 // be able to find the match between the graph nodes and scalar 3338 // operands of the given node during vectorization/cost estimation. 3339 assert(all_of(TE->UserTreeIndices, 3340 [VF, &TE](const EdgeInfo &EI) { 3341 return EI.UserTE->Scalars.size() == VF || 3342 EI.UserTE->Scalars.size() == 3343 TE->Scalars.size(); 3344 }) && 3345 "All users must be of VF size."); 3346 // Update ordering of the operands with the smaller VF than the given 3347 // one. 3348 reorderReuses(TE->ReuseShuffleIndices, Mask); 3349 } 3350 continue; 3351 } 3352 if (TE->State == TreeEntry::Vectorize && 3353 isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst, 3354 InsertElementInst>(TE->getMainOp()) && 3355 !TE->isAltShuffle()) { 3356 // Build correct orders for extract{element,value}, loads and 3357 // stores. 3358 reorderOrder(TE->ReorderIndices, Mask); 3359 if (isa<InsertElementInst, StoreInst>(TE->getMainOp())) 3360 TE->reorderOperands(Mask); 3361 } else { 3362 // Reorder the node and its operands. 3363 TE->reorderOperands(Mask); 3364 assert(TE->ReorderIndices.empty() && 3365 "Expected empty reorder sequence."); 3366 reorderScalars(TE->Scalars, Mask); 3367 } 3368 if (!TE->ReuseShuffleIndices.empty()) { 3369 // Apply reversed order to keep the original ordering of the reused 3370 // elements to avoid extra reorder indices shuffling. 3371 OrdersType CurrentOrder; 3372 reorderOrder(CurrentOrder, MaskOrder); 3373 SmallVector<int> NewReuses; 3374 inversePermutation(CurrentOrder, NewReuses); 3375 addMask(NewReuses, TE->ReuseShuffleIndices); 3376 TE->ReuseShuffleIndices.swap(NewReuses); 3377 } 3378 } 3379 } 3380 } 3381 3382 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) { 3383 SetVector<TreeEntry *> OrderedEntries; 3384 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3385 // Find all reorderable leaf nodes with the given VF. 3386 // Currently the are vectorized loads,extracts without alternate operands + 3387 // some gathering of extracts. 3388 SmallVector<TreeEntry *> NonVectorized; 3389 for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders, 3390 &NonVectorized]( 3391 const std::unique_ptr<TreeEntry> &TE) { 3392 if (TE->State != TreeEntry::Vectorize) 3393 NonVectorized.push_back(TE.get()); 3394 if (Optional<OrdersType> CurrentOrder = 3395 getReorderingData(*TE.get(), /*TopToBottom=*/false)) { 3396 OrderedEntries.insert(TE.get()); 3397 if (TE->State != TreeEntry::Vectorize) 3398 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3399 } 3400 }); 3401 3402 // Checks if the operands of the users are reordarable and have only single 3403 // use. 3404 auto &&CheckOperands = 3405 [this, &NonVectorized](const auto &Data, 3406 SmallVectorImpl<TreeEntry *> &GatherOps) { 3407 for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) { 3408 if (any_of(Data.second, 3409 [I](const std::pair<unsigned, TreeEntry *> &OpData) { 3410 return OpData.first == I && 3411 OpData.second->State == TreeEntry::Vectorize; 3412 })) 3413 continue; 3414 ArrayRef<Value *> VL = Data.first->getOperand(I); 3415 const TreeEntry *TE = nullptr; 3416 const auto *It = find_if(VL, [this, &TE](Value *V) { 3417 TE = getTreeEntry(V); 3418 return TE; 3419 }); 3420 if (It != VL.end() && TE->isSame(VL)) 3421 return false; 3422 TreeEntry *Gather = nullptr; 3423 if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) { 3424 assert(TE->State != TreeEntry::Vectorize && 3425 "Only non-vectorized nodes are expected."); 3426 if (TE->isSame(VL)) { 3427 Gather = TE; 3428 return true; 3429 } 3430 return false; 3431 }) > 1) 3432 return false; 3433 if (Gather) 3434 GatherOps.push_back(Gather); 3435 } 3436 return true; 3437 }; 3438 // 1. Propagate order to the graph nodes, which use only reordered nodes. 3439 // I.e., if the node has operands, that are reordered, try to make at least 3440 // one operand order in the natural order and reorder others + reorder the 3441 // user node itself. 3442 SmallPtrSet<const TreeEntry *, 4> Visited; 3443 while (!OrderedEntries.empty()) { 3444 // 1. Filter out only reordered nodes. 3445 // 2. If the entry has multiple uses - skip it and jump to the next node. 3446 MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users; 3447 SmallVector<TreeEntry *> Filtered; 3448 for (TreeEntry *TE : OrderedEntries) { 3449 if (!(TE->State == TreeEntry::Vectorize || 3450 (TE->State == TreeEntry::NeedToGather && 3451 GathersToOrders.count(TE))) || 3452 TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() || 3453 !all_of(drop_begin(TE->UserTreeIndices), 3454 [TE](const EdgeInfo &EI) { 3455 return EI.UserTE == TE->UserTreeIndices.front().UserTE; 3456 }) || 3457 !Visited.insert(TE).second) { 3458 Filtered.push_back(TE); 3459 continue; 3460 } 3461 // Build a map between user nodes and their operands order to speedup 3462 // search. The graph currently does not provide this dependency directly. 3463 for (EdgeInfo &EI : TE->UserTreeIndices) { 3464 TreeEntry *UserTE = EI.UserTE; 3465 auto It = Users.find(UserTE); 3466 if (It == Users.end()) 3467 It = Users.insert({UserTE, {}}).first; 3468 It->second.emplace_back(EI.EdgeIdx, TE); 3469 } 3470 } 3471 // Erase filtered entries. 3472 for_each(Filtered, 3473 [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); }); 3474 for (const auto &Data : Users) { 3475 // Check that operands are used only in the User node. 3476 SmallVector<TreeEntry *> GatherOps; 3477 if (!CheckOperands(Data, GatherOps)) { 3478 for_each(Data.second, 3479 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3480 OrderedEntries.remove(Op.second); 3481 }); 3482 continue; 3483 } 3484 // All operands are reordered and used only in this node - propagate the 3485 // most used order to the user node. 3486 MapVector<OrdersType, unsigned, 3487 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3488 OrdersUses; 3489 // Do the analysis for each tree entry only once, otherwise the order of 3490 // the same node my be considered several times, though might be not 3491 // profitable. 3492 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3493 for (const auto &Op : Data.second) { 3494 TreeEntry *OpTE = Op.second; 3495 if (!VisitedOps.insert(OpTE).second) 3496 continue; 3497 if (!OpTE->ReuseShuffleIndices.empty() || 3498 (IgnoreReorder && OpTE == VectorizableTree.front().get())) 3499 continue; 3500 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3501 if (OpTE->State == TreeEntry::NeedToGather) 3502 return GathersToOrders.find(OpTE)->second; 3503 return OpTE->ReorderIndices; 3504 }(); 3505 // Stores actually store the mask, not the order, need to invert. 3506 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3507 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3508 SmallVector<int> Mask; 3509 inversePermutation(Order, Mask); 3510 unsigned E = Order.size(); 3511 OrdersType CurrentOrder(E, E); 3512 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3513 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3514 }); 3515 fixupOrderingIndices(CurrentOrder); 3516 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 3517 } else { 3518 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 3519 } 3520 OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second += 3521 OpTE->UserTreeIndices.size(); 3522 assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0."); 3523 --OrdersUses[{}]; 3524 } 3525 // If no orders - skip current nodes and jump to the next one, if any. 3526 if (OrdersUses.empty()) { 3527 for_each(Data.second, 3528 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3529 OrderedEntries.remove(Op.second); 3530 }); 3531 continue; 3532 } 3533 // Choose the best order. 3534 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3535 unsigned Cnt = OrdersUses.front().second; 3536 for (const auto &Pair : drop_begin(OrdersUses)) { 3537 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3538 BestOrder = Pair.first; 3539 Cnt = Pair.second; 3540 } 3541 } 3542 // Set order of the user node (reordering of operands and user nodes). 3543 if (BestOrder.empty()) { 3544 for_each(Data.second, 3545 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3546 OrderedEntries.remove(Op.second); 3547 }); 3548 continue; 3549 } 3550 // Erase operands from OrderedEntries list and adjust their orders. 3551 VisitedOps.clear(); 3552 SmallVector<int> Mask; 3553 inversePermutation(BestOrder, Mask); 3554 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3555 unsigned E = BestOrder.size(); 3556 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3557 return I < E ? static_cast<int>(I) : UndefMaskElem; 3558 }); 3559 for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) { 3560 TreeEntry *TE = Op.second; 3561 OrderedEntries.remove(TE); 3562 if (!VisitedOps.insert(TE).second) 3563 continue; 3564 if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) { 3565 // Just reorder reuses indices. 3566 reorderReuses(TE->ReuseShuffleIndices, Mask); 3567 continue; 3568 } 3569 // Gathers are processed separately. 3570 if (TE->State != TreeEntry::Vectorize) 3571 continue; 3572 assert((BestOrder.size() == TE->ReorderIndices.size() || 3573 TE->ReorderIndices.empty()) && 3574 "Non-matching sizes of user/operand entries."); 3575 reorderOrder(TE->ReorderIndices, Mask); 3576 } 3577 // For gathers just need to reorder its scalars. 3578 for (TreeEntry *Gather : GatherOps) { 3579 assert(Gather->ReorderIndices.empty() && 3580 "Unexpected reordering of gathers."); 3581 if (!Gather->ReuseShuffleIndices.empty()) { 3582 // Just reorder reuses indices. 3583 reorderReuses(Gather->ReuseShuffleIndices, Mask); 3584 continue; 3585 } 3586 reorderScalars(Gather->Scalars, Mask); 3587 OrderedEntries.remove(Gather); 3588 } 3589 // Reorder operands of the user node and set the ordering for the user 3590 // node itself. 3591 if (Data.first->State != TreeEntry::Vectorize || 3592 !isa<ExtractElementInst, ExtractValueInst, LoadInst>( 3593 Data.first->getMainOp()) || 3594 Data.first->isAltShuffle()) 3595 Data.first->reorderOperands(Mask); 3596 if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) || 3597 Data.first->isAltShuffle()) { 3598 reorderScalars(Data.first->Scalars, Mask); 3599 reorderOrder(Data.first->ReorderIndices, MaskOrder); 3600 if (Data.first->ReuseShuffleIndices.empty() && 3601 !Data.first->ReorderIndices.empty() && 3602 !Data.first->isAltShuffle()) { 3603 // Insert user node to the list to try to sink reordering deeper in 3604 // the graph. 3605 OrderedEntries.insert(Data.first); 3606 } 3607 } else { 3608 reorderOrder(Data.first->ReorderIndices, Mask); 3609 } 3610 } 3611 } 3612 // If the reordering is unnecessary, just remove the reorder. 3613 if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() && 3614 VectorizableTree.front()->ReuseShuffleIndices.empty()) 3615 VectorizableTree.front()->ReorderIndices.clear(); 3616 } 3617 3618 void BoUpSLP::buildExternalUses( 3619 const ExtraValueToDebugLocsMap &ExternallyUsedValues) { 3620 // Collect the values that we need to extract from the tree. 3621 for (auto &TEPtr : VectorizableTree) { 3622 TreeEntry *Entry = TEPtr.get(); 3623 3624 // No need to handle users of gathered values. 3625 if (Entry->State == TreeEntry::NeedToGather) 3626 continue; 3627 3628 // For each lane: 3629 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 3630 Value *Scalar = Entry->Scalars[Lane]; 3631 int FoundLane = Entry->findLaneForValue(Scalar); 3632 3633 // Check if the scalar is externally used as an extra arg. 3634 auto ExtI = ExternallyUsedValues.find(Scalar); 3635 if (ExtI != ExternallyUsedValues.end()) { 3636 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " 3637 << Lane << " from " << *Scalar << ".\n"); 3638 ExternalUses.emplace_back(Scalar, nullptr, FoundLane); 3639 } 3640 for (User *U : Scalar->users()) { 3641 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n"); 3642 3643 Instruction *UserInst = dyn_cast<Instruction>(U); 3644 if (!UserInst) 3645 continue; 3646 3647 if (isDeleted(UserInst)) 3648 continue; 3649 3650 // Skip in-tree scalars that become vectors 3651 if (TreeEntry *UseEntry = getTreeEntry(U)) { 3652 Value *UseScalar = UseEntry->Scalars[0]; 3653 // Some in-tree scalars will remain as scalar in vectorized 3654 // instructions. If that is the case, the one in Lane 0 will 3655 // be used. 3656 if (UseScalar != U || 3657 UseEntry->State == TreeEntry::ScatterVectorize || 3658 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) { 3659 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U 3660 << ".\n"); 3661 assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state"); 3662 continue; 3663 } 3664 } 3665 3666 // Ignore users in the user ignore list. 3667 if (is_contained(UserIgnoreList, UserInst)) 3668 continue; 3669 3670 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " 3671 << Lane << " from " << *Scalar << ".\n"); 3672 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane)); 3673 } 3674 } 3675 } 3676 } 3677 3678 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, 3679 ArrayRef<Value *> UserIgnoreLst) { 3680 deleteTree(); 3681 UserIgnoreList = UserIgnoreLst; 3682 if (!allSameType(Roots)) 3683 return; 3684 buildTree_rec(Roots, 0, EdgeInfo()); 3685 } 3686 3687 namespace { 3688 /// Tracks the state we can represent the loads in the given sequence. 3689 enum class LoadsState { Gather, Vectorize, ScatterVectorize }; 3690 } // anonymous namespace 3691 3692 /// Checks if the given array of loads can be represented as a vectorized, 3693 /// scatter or just simple gather. 3694 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0, 3695 const TargetTransformInfo &TTI, 3696 const DataLayout &DL, ScalarEvolution &SE, 3697 SmallVectorImpl<unsigned> &Order, 3698 SmallVectorImpl<Value *> &PointerOps) { 3699 // Check that a vectorized load would load the same memory as a scalar 3700 // load. For example, we don't want to vectorize loads that are smaller 3701 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 3702 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 3703 // from such a struct, we read/write packed bits disagreeing with the 3704 // unvectorized version. 3705 Type *ScalarTy = VL0->getType(); 3706 3707 if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy)) 3708 return LoadsState::Gather; 3709 3710 // Make sure all loads in the bundle are simple - we can't vectorize 3711 // atomic or volatile loads. 3712 PointerOps.clear(); 3713 PointerOps.resize(VL.size()); 3714 auto *POIter = PointerOps.begin(); 3715 for (Value *V : VL) { 3716 auto *L = cast<LoadInst>(V); 3717 if (!L->isSimple()) 3718 return LoadsState::Gather; 3719 *POIter = L->getPointerOperand(); 3720 ++POIter; 3721 } 3722 3723 Order.clear(); 3724 // Check the order of pointer operands. 3725 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) { 3726 Value *Ptr0; 3727 Value *PtrN; 3728 if (Order.empty()) { 3729 Ptr0 = PointerOps.front(); 3730 PtrN = PointerOps.back(); 3731 } else { 3732 Ptr0 = PointerOps[Order.front()]; 3733 PtrN = PointerOps[Order.back()]; 3734 } 3735 Optional<int> Diff = 3736 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE); 3737 // Check that the sorted loads are consecutive. 3738 if (static_cast<unsigned>(*Diff) == VL.size() - 1) 3739 return LoadsState::Vectorize; 3740 Align CommonAlignment = cast<LoadInst>(VL0)->getAlign(); 3741 for (Value *V : VL) 3742 CommonAlignment = 3743 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 3744 if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()), 3745 CommonAlignment)) 3746 return LoadsState::ScatterVectorize; 3747 } 3748 3749 return LoadsState::Gather; 3750 } 3751 3752 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth, 3753 const EdgeInfo &UserTreeIdx) { 3754 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!"); 3755 3756 SmallVector<int> ReuseShuffleIndicies; 3757 SmallVector<Value *> UniqueValues; 3758 auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues, 3759 &UserTreeIdx, 3760 this](const InstructionsState &S) { 3761 // Check that every instruction appears once in this bundle. 3762 DenseMap<Value *, unsigned> UniquePositions; 3763 for (Value *V : VL) { 3764 if (isConstant(V)) { 3765 ReuseShuffleIndicies.emplace_back( 3766 isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size()); 3767 UniqueValues.emplace_back(V); 3768 continue; 3769 } 3770 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 3771 ReuseShuffleIndicies.emplace_back(Res.first->second); 3772 if (Res.second) 3773 UniqueValues.emplace_back(V); 3774 } 3775 size_t NumUniqueScalarValues = UniqueValues.size(); 3776 if (NumUniqueScalarValues == VL.size()) { 3777 ReuseShuffleIndicies.clear(); 3778 } else { 3779 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n"); 3780 if (NumUniqueScalarValues <= 1 || 3781 (UniquePositions.size() == 1 && all_of(UniqueValues, 3782 [](Value *V) { 3783 return isa<UndefValue>(V) || 3784 !isConstant(V); 3785 })) || 3786 !llvm::isPowerOf2_32(NumUniqueScalarValues)) { 3787 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); 3788 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3789 return false; 3790 } 3791 VL = UniqueValues; 3792 } 3793 return true; 3794 }; 3795 3796 InstructionsState S = getSameOpcode(VL); 3797 if (Depth == RecursionMaxDepth) { 3798 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); 3799 if (TryToFindDuplicates(S)) 3800 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3801 ReuseShuffleIndicies); 3802 return; 3803 } 3804 3805 // Don't handle scalable vectors 3806 if (S.getOpcode() == Instruction::ExtractElement && 3807 isa<ScalableVectorType>( 3808 cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) { 3809 LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n"); 3810 if (TryToFindDuplicates(S)) 3811 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3812 ReuseShuffleIndicies); 3813 return; 3814 } 3815 3816 // Don't handle vectors. 3817 if (S.OpValue->getType()->isVectorTy() && 3818 !isa<InsertElementInst>(S.OpValue)) { 3819 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); 3820 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3821 return; 3822 } 3823 3824 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue)) 3825 if (SI->getValueOperand()->getType()->isVectorTy()) { 3826 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); 3827 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3828 return; 3829 } 3830 3831 // If all of the operands are identical or constant we have a simple solution. 3832 // If we deal with insert/extract instructions, they all must have constant 3833 // indices, otherwise we should gather them, not try to vectorize. 3834 if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() || 3835 (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) && 3836 !all_of(VL, isVectorLikeInstWithConstOps))) { 3837 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n"); 3838 if (TryToFindDuplicates(S)) 3839 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3840 ReuseShuffleIndicies); 3841 return; 3842 } 3843 3844 // We now know that this is a vector of instructions of the same type from 3845 // the same block. 3846 3847 // Don't vectorize ephemeral values. 3848 for (Value *V : VL) { 3849 if (EphValues.count(V)) { 3850 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 3851 << ") is ephemeral.\n"); 3852 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3853 return; 3854 } 3855 } 3856 3857 // Check if this is a duplicate of another entry. 3858 if (TreeEntry *E = getTreeEntry(S.OpValue)) { 3859 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n"); 3860 if (!E->isSame(VL)) { 3861 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); 3862 if (TryToFindDuplicates(S)) 3863 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3864 ReuseShuffleIndicies); 3865 return; 3866 } 3867 // Record the reuse of the tree node. FIXME, currently this is only used to 3868 // properly draw the graph rather than for the actual vectorization. 3869 E->UserTreeIndices.push_back(UserTreeIdx); 3870 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue 3871 << ".\n"); 3872 return; 3873 } 3874 3875 // Check that none of the instructions in the bundle are already in the tree. 3876 for (Value *V : VL) { 3877 auto *I = dyn_cast<Instruction>(V); 3878 if (!I) 3879 continue; 3880 if (getTreeEntry(I)) { 3881 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 3882 << ") is already in tree.\n"); 3883 if (TryToFindDuplicates(S)) 3884 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3885 ReuseShuffleIndicies); 3886 return; 3887 } 3888 } 3889 3890 // The reduction nodes (stored in UserIgnoreList) also should stay scalar. 3891 for (Value *V : VL) { 3892 if (is_contained(UserIgnoreList, V)) { 3893 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n"); 3894 if (TryToFindDuplicates(S)) 3895 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3896 ReuseShuffleIndicies); 3897 return; 3898 } 3899 } 3900 3901 // Check that all of the users of the scalars that we want to vectorize are 3902 // schedulable. 3903 auto *VL0 = cast<Instruction>(S.OpValue); 3904 BasicBlock *BB = VL0->getParent(); 3905 3906 if (!DT->isReachableFromEntry(BB)) { 3907 // Don't go into unreachable blocks. They may contain instructions with 3908 // dependency cycles which confuse the final scheduling. 3909 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n"); 3910 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3911 return; 3912 } 3913 3914 // Check that every instruction appears once in this bundle. 3915 if (!TryToFindDuplicates(S)) 3916 return; 3917 3918 auto &BSRef = BlocksSchedules[BB]; 3919 if (!BSRef) 3920 BSRef = std::make_unique<BlockScheduling>(BB); 3921 3922 BlockScheduling &BS = *BSRef.get(); 3923 3924 Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S); 3925 #ifdef EXPENSIVE_CHECKS 3926 // Make sure we didn't break any internal invariants 3927 BS.verify(); 3928 #endif 3929 if (!Bundle) { 3930 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n"); 3931 assert((!BS.getScheduleData(VL0) || 3932 !BS.getScheduleData(VL0)->isPartOfBundle()) && 3933 "tryScheduleBundle should cancelScheduling on failure"); 3934 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3935 ReuseShuffleIndicies); 3936 return; 3937 } 3938 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); 3939 3940 unsigned ShuffleOrOp = S.isAltShuffle() ? 3941 (unsigned) Instruction::ShuffleVector : S.getOpcode(); 3942 switch (ShuffleOrOp) { 3943 case Instruction::PHI: { 3944 auto *PH = cast<PHINode>(VL0); 3945 3946 // Check for terminator values (e.g. invoke). 3947 for (Value *V : VL) 3948 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 3949 Instruction *Term = dyn_cast<Instruction>( 3950 cast<PHINode>(V)->getIncomingValueForBlock( 3951 PH->getIncomingBlock(I))); 3952 if (Term && Term->isTerminator()) { 3953 LLVM_DEBUG(dbgs() 3954 << "SLP: Need to swizzle PHINodes (terminator use).\n"); 3955 BS.cancelScheduling(VL, VL0); 3956 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3957 ReuseShuffleIndicies); 3958 return; 3959 } 3960 } 3961 3962 TreeEntry *TE = 3963 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies); 3964 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); 3965 3966 // Keeps the reordered operands to avoid code duplication. 3967 SmallVector<ValueList, 2> OperandsVec; 3968 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 3969 if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) { 3970 ValueList Operands(VL.size(), PoisonValue::get(PH->getType())); 3971 TE->setOperand(I, Operands); 3972 OperandsVec.push_back(Operands); 3973 continue; 3974 } 3975 ValueList Operands; 3976 // Prepare the operand vector. 3977 for (Value *V : VL) 3978 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock( 3979 PH->getIncomingBlock(I))); 3980 TE->setOperand(I, Operands); 3981 OperandsVec.push_back(Operands); 3982 } 3983 for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx) 3984 buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx}); 3985 return; 3986 } 3987 case Instruction::ExtractValue: 3988 case Instruction::ExtractElement: { 3989 OrdersType CurrentOrder; 3990 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder); 3991 if (Reuse) { 3992 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n"); 3993 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3994 ReuseShuffleIndicies); 3995 // This is a special case, as it does not gather, but at the same time 3996 // we are not extending buildTree_rec() towards the operands. 3997 ValueList Op0; 3998 Op0.assign(VL.size(), VL0->getOperand(0)); 3999 VectorizableTree.back()->setOperand(0, Op0); 4000 return; 4001 } 4002 if (!CurrentOrder.empty()) { 4003 LLVM_DEBUG({ 4004 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " 4005 "with order"; 4006 for (unsigned Idx : CurrentOrder) 4007 dbgs() << " " << Idx; 4008 dbgs() << "\n"; 4009 }); 4010 fixupOrderingIndices(CurrentOrder); 4011 // Insert new order with initial value 0, if it does not exist, 4012 // otherwise return the iterator to the existing one. 4013 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4014 ReuseShuffleIndicies, CurrentOrder); 4015 // This is a special case, as it does not gather, but at the same time 4016 // we are not extending buildTree_rec() towards the operands. 4017 ValueList Op0; 4018 Op0.assign(VL.size(), VL0->getOperand(0)); 4019 VectorizableTree.back()->setOperand(0, Op0); 4020 return; 4021 } 4022 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n"); 4023 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4024 ReuseShuffleIndicies); 4025 BS.cancelScheduling(VL, VL0); 4026 return; 4027 } 4028 case Instruction::InsertElement: { 4029 assert(ReuseShuffleIndicies.empty() && "All inserts should be unique"); 4030 4031 // Check that we have a buildvector and not a shuffle of 2 or more 4032 // different vectors. 4033 ValueSet SourceVectors; 4034 for (Value *V : VL) { 4035 SourceVectors.insert(cast<Instruction>(V)->getOperand(0)); 4036 assert(getInsertIndex(V) != None && "Non-constant or undef index?"); 4037 } 4038 4039 if (count_if(VL, [&SourceVectors](Value *V) { 4040 return !SourceVectors.contains(V); 4041 }) >= 2) { 4042 // Found 2nd source vector - cancel. 4043 LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with " 4044 "different source vectors.\n"); 4045 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4046 BS.cancelScheduling(VL, VL0); 4047 return; 4048 } 4049 4050 auto OrdCompare = [](const std::pair<int, int> &P1, 4051 const std::pair<int, int> &P2) { 4052 return P1.first > P2.first; 4053 }; 4054 PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>, 4055 decltype(OrdCompare)> 4056 Indices(OrdCompare); 4057 for (int I = 0, E = VL.size(); I < E; ++I) { 4058 unsigned Idx = *getInsertIndex(VL[I]); 4059 Indices.emplace(Idx, I); 4060 } 4061 OrdersType CurrentOrder(VL.size(), VL.size()); 4062 bool IsIdentity = true; 4063 for (int I = 0, E = VL.size(); I < E; ++I) { 4064 CurrentOrder[Indices.top().second] = I; 4065 IsIdentity &= Indices.top().second == I; 4066 Indices.pop(); 4067 } 4068 if (IsIdentity) 4069 CurrentOrder.clear(); 4070 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4071 None, CurrentOrder); 4072 LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n"); 4073 4074 constexpr int NumOps = 2; 4075 ValueList VectorOperands[NumOps]; 4076 for (int I = 0; I < NumOps; ++I) { 4077 for (Value *V : VL) 4078 VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I)); 4079 4080 TE->setOperand(I, VectorOperands[I]); 4081 } 4082 buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1}); 4083 return; 4084 } 4085 case Instruction::Load: { 4086 // Check that a vectorized load would load the same memory as a scalar 4087 // load. For example, we don't want to vectorize loads that are smaller 4088 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 4089 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 4090 // from such a struct, we read/write packed bits disagreeing with the 4091 // unvectorized version. 4092 SmallVector<Value *> PointerOps; 4093 OrdersType CurrentOrder; 4094 TreeEntry *TE = nullptr; 4095 switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder, 4096 PointerOps)) { 4097 case LoadsState::Vectorize: 4098 if (CurrentOrder.empty()) { 4099 // Original loads are consecutive and does not require reordering. 4100 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4101 ReuseShuffleIndicies); 4102 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n"); 4103 } else { 4104 fixupOrderingIndices(CurrentOrder); 4105 // Need to reorder. 4106 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4107 ReuseShuffleIndicies, CurrentOrder); 4108 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n"); 4109 } 4110 TE->setOperandsInOrder(); 4111 break; 4112 case LoadsState::ScatterVectorize: 4113 // Vectorizing non-consecutive loads with `llvm.masked.gather`. 4114 TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S, 4115 UserTreeIdx, ReuseShuffleIndicies); 4116 TE->setOperandsInOrder(); 4117 buildTree_rec(PointerOps, Depth + 1, {TE, 0}); 4118 LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n"); 4119 break; 4120 case LoadsState::Gather: 4121 BS.cancelScheduling(VL, VL0); 4122 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4123 ReuseShuffleIndicies); 4124 #ifndef NDEBUG 4125 Type *ScalarTy = VL0->getType(); 4126 if (DL->getTypeSizeInBits(ScalarTy) != 4127 DL->getTypeAllocSizeInBits(ScalarTy)) 4128 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n"); 4129 else if (any_of(VL, [](Value *V) { 4130 return !cast<LoadInst>(V)->isSimple(); 4131 })) 4132 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n"); 4133 else 4134 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n"); 4135 #endif // NDEBUG 4136 break; 4137 } 4138 return; 4139 } 4140 case Instruction::ZExt: 4141 case Instruction::SExt: 4142 case Instruction::FPToUI: 4143 case Instruction::FPToSI: 4144 case Instruction::FPExt: 4145 case Instruction::PtrToInt: 4146 case Instruction::IntToPtr: 4147 case Instruction::SIToFP: 4148 case Instruction::UIToFP: 4149 case Instruction::Trunc: 4150 case Instruction::FPTrunc: 4151 case Instruction::BitCast: { 4152 Type *SrcTy = VL0->getOperand(0)->getType(); 4153 for (Value *V : VL) { 4154 Type *Ty = cast<Instruction>(V)->getOperand(0)->getType(); 4155 if (Ty != SrcTy || !isValidElementType(Ty)) { 4156 BS.cancelScheduling(VL, VL0); 4157 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4158 ReuseShuffleIndicies); 4159 LLVM_DEBUG(dbgs() 4160 << "SLP: Gathering casts with different src types.\n"); 4161 return; 4162 } 4163 } 4164 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4165 ReuseShuffleIndicies); 4166 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n"); 4167 4168 TE->setOperandsInOrder(); 4169 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4170 ValueList Operands; 4171 // Prepare the operand vector. 4172 for (Value *V : VL) 4173 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4174 4175 buildTree_rec(Operands, Depth + 1, {TE, i}); 4176 } 4177 return; 4178 } 4179 case Instruction::ICmp: 4180 case Instruction::FCmp: { 4181 // Check that all of the compares have the same predicate. 4182 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 4183 CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0); 4184 Type *ComparedTy = VL0->getOperand(0)->getType(); 4185 for (Value *V : VL) { 4186 CmpInst *Cmp = cast<CmpInst>(V); 4187 if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) || 4188 Cmp->getOperand(0)->getType() != ComparedTy) { 4189 BS.cancelScheduling(VL, VL0); 4190 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4191 ReuseShuffleIndicies); 4192 LLVM_DEBUG(dbgs() 4193 << "SLP: Gathering cmp with different predicate.\n"); 4194 return; 4195 } 4196 } 4197 4198 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4199 ReuseShuffleIndicies); 4200 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n"); 4201 4202 ValueList Left, Right; 4203 if (cast<CmpInst>(VL0)->isCommutative()) { 4204 // Commutative predicate - collect + sort operands of the instructions 4205 // so that each side is more likely to have the same opcode. 4206 assert(P0 == SwapP0 && "Commutative Predicate mismatch"); 4207 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4208 } else { 4209 // Collect operands - commute if it uses the swapped predicate. 4210 for (Value *V : VL) { 4211 auto *Cmp = cast<CmpInst>(V); 4212 Value *LHS = Cmp->getOperand(0); 4213 Value *RHS = Cmp->getOperand(1); 4214 if (Cmp->getPredicate() != P0) 4215 std::swap(LHS, RHS); 4216 Left.push_back(LHS); 4217 Right.push_back(RHS); 4218 } 4219 } 4220 TE->setOperand(0, Left); 4221 TE->setOperand(1, Right); 4222 buildTree_rec(Left, Depth + 1, {TE, 0}); 4223 buildTree_rec(Right, Depth + 1, {TE, 1}); 4224 return; 4225 } 4226 case Instruction::Select: 4227 case Instruction::FNeg: 4228 case Instruction::Add: 4229 case Instruction::FAdd: 4230 case Instruction::Sub: 4231 case Instruction::FSub: 4232 case Instruction::Mul: 4233 case Instruction::FMul: 4234 case Instruction::UDiv: 4235 case Instruction::SDiv: 4236 case Instruction::FDiv: 4237 case Instruction::URem: 4238 case Instruction::SRem: 4239 case Instruction::FRem: 4240 case Instruction::Shl: 4241 case Instruction::LShr: 4242 case Instruction::AShr: 4243 case Instruction::And: 4244 case Instruction::Or: 4245 case Instruction::Xor: { 4246 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4247 ReuseShuffleIndicies); 4248 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n"); 4249 4250 // Sort operands of the instructions so that each side is more likely to 4251 // have the same opcode. 4252 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) { 4253 ValueList Left, Right; 4254 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4255 TE->setOperand(0, Left); 4256 TE->setOperand(1, Right); 4257 buildTree_rec(Left, Depth + 1, {TE, 0}); 4258 buildTree_rec(Right, Depth + 1, {TE, 1}); 4259 return; 4260 } 4261 4262 TE->setOperandsInOrder(); 4263 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4264 ValueList Operands; 4265 // Prepare the operand vector. 4266 for (Value *V : VL) 4267 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4268 4269 buildTree_rec(Operands, Depth + 1, {TE, i}); 4270 } 4271 return; 4272 } 4273 case Instruction::GetElementPtr: { 4274 // We don't combine GEPs with complicated (nested) indexing. 4275 for (Value *V : VL) { 4276 if (cast<Instruction>(V)->getNumOperands() != 2) { 4277 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"); 4278 BS.cancelScheduling(VL, VL0); 4279 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4280 ReuseShuffleIndicies); 4281 return; 4282 } 4283 } 4284 4285 // We can't combine several GEPs into one vector if they operate on 4286 // different types. 4287 Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType(); 4288 for (Value *V : VL) { 4289 Type *CurTy = cast<GEPOperator>(V)->getSourceElementType(); 4290 if (Ty0 != CurTy) { 4291 LLVM_DEBUG(dbgs() 4292 << "SLP: not-vectorizable GEP (different types).\n"); 4293 BS.cancelScheduling(VL, VL0); 4294 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4295 ReuseShuffleIndicies); 4296 return; 4297 } 4298 } 4299 4300 // We don't combine GEPs with non-constant indexes. 4301 Type *Ty1 = VL0->getOperand(1)->getType(); 4302 for (Value *V : VL) { 4303 auto Op = cast<Instruction>(V)->getOperand(1); 4304 if (!isa<ConstantInt>(Op) || 4305 (Op->getType() != Ty1 && 4306 Op->getType()->getScalarSizeInBits() > 4307 DL->getIndexSizeInBits( 4308 V->getType()->getPointerAddressSpace()))) { 4309 LLVM_DEBUG(dbgs() 4310 << "SLP: not-vectorizable GEP (non-constant indexes).\n"); 4311 BS.cancelScheduling(VL, VL0); 4312 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4313 ReuseShuffleIndicies); 4314 return; 4315 } 4316 } 4317 4318 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4319 ReuseShuffleIndicies); 4320 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n"); 4321 SmallVector<ValueList, 2> Operands(2); 4322 // Prepare the operand vector for pointer operands. 4323 for (Value *V : VL) 4324 Operands.front().push_back( 4325 cast<GetElementPtrInst>(V)->getPointerOperand()); 4326 TE->setOperand(0, Operands.front()); 4327 // Need to cast all indices to the same type before vectorization to 4328 // avoid crash. 4329 // Required to be able to find correct matches between different gather 4330 // nodes and reuse the vectorized values rather than trying to gather them 4331 // again. 4332 int IndexIdx = 1; 4333 Type *VL0Ty = VL0->getOperand(IndexIdx)->getType(); 4334 Type *Ty = all_of(VL, 4335 [VL0Ty, IndexIdx](Value *V) { 4336 return VL0Ty == cast<GetElementPtrInst>(V) 4337 ->getOperand(IndexIdx) 4338 ->getType(); 4339 }) 4340 ? VL0Ty 4341 : DL->getIndexType(cast<GetElementPtrInst>(VL0) 4342 ->getPointerOperandType() 4343 ->getScalarType()); 4344 // Prepare the operand vector. 4345 for (Value *V : VL) { 4346 auto *Op = cast<Instruction>(V)->getOperand(IndexIdx); 4347 auto *CI = cast<ConstantInt>(Op); 4348 Operands.back().push_back(ConstantExpr::getIntegerCast( 4349 CI, Ty, CI->getValue().isSignBitSet())); 4350 } 4351 TE->setOperand(IndexIdx, Operands.back()); 4352 4353 for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I) 4354 buildTree_rec(Operands[I], Depth + 1, {TE, I}); 4355 return; 4356 } 4357 case Instruction::Store: { 4358 // Check if the stores are consecutive or if we need to swizzle them. 4359 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType(); 4360 // Avoid types that are padded when being allocated as scalars, while 4361 // being packed together in a vector (such as i1). 4362 if (DL->getTypeSizeInBits(ScalarTy) != 4363 DL->getTypeAllocSizeInBits(ScalarTy)) { 4364 BS.cancelScheduling(VL, VL0); 4365 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4366 ReuseShuffleIndicies); 4367 LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n"); 4368 return; 4369 } 4370 // Make sure all stores in the bundle are simple - we can't vectorize 4371 // atomic or volatile stores. 4372 SmallVector<Value *, 4> PointerOps(VL.size()); 4373 ValueList Operands(VL.size()); 4374 auto POIter = PointerOps.begin(); 4375 auto OIter = Operands.begin(); 4376 for (Value *V : VL) { 4377 auto *SI = cast<StoreInst>(V); 4378 if (!SI->isSimple()) { 4379 BS.cancelScheduling(VL, VL0); 4380 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4381 ReuseShuffleIndicies); 4382 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n"); 4383 return; 4384 } 4385 *POIter = SI->getPointerOperand(); 4386 *OIter = SI->getValueOperand(); 4387 ++POIter; 4388 ++OIter; 4389 } 4390 4391 OrdersType CurrentOrder; 4392 // Check the order of pointer operands. 4393 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) { 4394 Value *Ptr0; 4395 Value *PtrN; 4396 if (CurrentOrder.empty()) { 4397 Ptr0 = PointerOps.front(); 4398 PtrN = PointerOps.back(); 4399 } else { 4400 Ptr0 = PointerOps[CurrentOrder.front()]; 4401 PtrN = PointerOps[CurrentOrder.back()]; 4402 } 4403 Optional<int> Dist = 4404 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE); 4405 // Check that the sorted pointer operands are consecutive. 4406 if (static_cast<unsigned>(*Dist) == VL.size() - 1) { 4407 if (CurrentOrder.empty()) { 4408 // Original stores are consecutive and does not require reordering. 4409 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, 4410 UserTreeIdx, ReuseShuffleIndicies); 4411 TE->setOperandsInOrder(); 4412 buildTree_rec(Operands, Depth + 1, {TE, 0}); 4413 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n"); 4414 } else { 4415 fixupOrderingIndices(CurrentOrder); 4416 TreeEntry *TE = 4417 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4418 ReuseShuffleIndicies, CurrentOrder); 4419 TE->setOperandsInOrder(); 4420 buildTree_rec(Operands, Depth + 1, {TE, 0}); 4421 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n"); 4422 } 4423 return; 4424 } 4425 } 4426 4427 BS.cancelScheduling(VL, VL0); 4428 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4429 ReuseShuffleIndicies); 4430 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n"); 4431 return; 4432 } 4433 case Instruction::Call: { 4434 // Check if the calls are all to the same vectorizable intrinsic or 4435 // library function. 4436 CallInst *CI = cast<CallInst>(VL0); 4437 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4438 4439 VFShape Shape = VFShape::get( 4440 *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())), 4441 false /*HasGlobalPred*/); 4442 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 4443 4444 if (!VecFunc && !isTriviallyVectorizable(ID)) { 4445 BS.cancelScheduling(VL, VL0); 4446 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4447 ReuseShuffleIndicies); 4448 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n"); 4449 return; 4450 } 4451 Function *F = CI->getCalledFunction(); 4452 unsigned NumArgs = CI->arg_size(); 4453 SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr); 4454 for (unsigned j = 0; j != NumArgs; ++j) 4455 if (hasVectorInstrinsicScalarOpd(ID, j)) 4456 ScalarArgs[j] = CI->getArgOperand(j); 4457 for (Value *V : VL) { 4458 CallInst *CI2 = dyn_cast<CallInst>(V); 4459 if (!CI2 || CI2->getCalledFunction() != F || 4460 getVectorIntrinsicIDForCall(CI2, TLI) != ID || 4461 (VecFunc && 4462 VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) || 4463 !CI->hasIdenticalOperandBundleSchema(*CI2)) { 4464 BS.cancelScheduling(VL, VL0); 4465 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4466 ReuseShuffleIndicies); 4467 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V 4468 << "\n"); 4469 return; 4470 } 4471 // Some intrinsics have scalar arguments and should be same in order for 4472 // them to be vectorized. 4473 for (unsigned j = 0; j != NumArgs; ++j) { 4474 if (hasVectorInstrinsicScalarOpd(ID, j)) { 4475 Value *A1J = CI2->getArgOperand(j); 4476 if (ScalarArgs[j] != A1J) { 4477 BS.cancelScheduling(VL, VL0); 4478 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4479 ReuseShuffleIndicies); 4480 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI 4481 << " argument " << ScalarArgs[j] << "!=" << A1J 4482 << "\n"); 4483 return; 4484 } 4485 } 4486 } 4487 // Verify that the bundle operands are identical between the two calls. 4488 if (CI->hasOperandBundles() && 4489 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(), 4490 CI->op_begin() + CI->getBundleOperandsEndIndex(), 4491 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) { 4492 BS.cancelScheduling(VL, VL0); 4493 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4494 ReuseShuffleIndicies); 4495 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" 4496 << *CI << "!=" << *V << '\n'); 4497 return; 4498 } 4499 } 4500 4501 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4502 ReuseShuffleIndicies); 4503 TE->setOperandsInOrder(); 4504 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 4505 // For scalar operands no need to to create an entry since no need to 4506 // vectorize it. 4507 if (hasVectorInstrinsicScalarOpd(ID, i)) 4508 continue; 4509 ValueList Operands; 4510 // Prepare the operand vector. 4511 for (Value *V : VL) { 4512 auto *CI2 = cast<CallInst>(V); 4513 Operands.push_back(CI2->getArgOperand(i)); 4514 } 4515 buildTree_rec(Operands, Depth + 1, {TE, i}); 4516 } 4517 return; 4518 } 4519 case Instruction::ShuffleVector: { 4520 // If this is not an alternate sequence of opcode like add-sub 4521 // then do not vectorize this instruction. 4522 if (!S.isAltShuffle()) { 4523 BS.cancelScheduling(VL, VL0); 4524 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4525 ReuseShuffleIndicies); 4526 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n"); 4527 return; 4528 } 4529 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4530 ReuseShuffleIndicies); 4531 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n"); 4532 4533 // Reorder operands if reordering would enable vectorization. 4534 auto *CI = dyn_cast<CmpInst>(VL0); 4535 if (isa<BinaryOperator>(VL0) || CI) { 4536 ValueList Left, Right; 4537 if (!CI || all_of(VL, [](Value *V) { 4538 return cast<CmpInst>(V)->isCommutative(); 4539 })) { 4540 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4541 } else { 4542 CmpInst::Predicate P0 = CI->getPredicate(); 4543 CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate(); 4544 assert(P0 != AltP0 && 4545 "Expected different main/alternate predicates."); 4546 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 4547 Value *BaseOp0 = VL0->getOperand(0); 4548 Value *BaseOp1 = VL0->getOperand(1); 4549 // Collect operands - commute if it uses the swapped predicate or 4550 // alternate operation. 4551 for (Value *V : VL) { 4552 auto *Cmp = cast<CmpInst>(V); 4553 Value *LHS = Cmp->getOperand(0); 4554 Value *RHS = Cmp->getOperand(1); 4555 CmpInst::Predicate CurrentPred = Cmp->getPredicate(); 4556 if (P0 == AltP0Swapped) { 4557 if (CI != Cmp && S.AltOp != Cmp && 4558 ((P0 == CurrentPred && 4559 !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) || 4560 (AltP0 == CurrentPred && 4561 areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)))) 4562 std::swap(LHS, RHS); 4563 } else if (P0 != CurrentPred && AltP0 != CurrentPred) { 4564 std::swap(LHS, RHS); 4565 } 4566 Left.push_back(LHS); 4567 Right.push_back(RHS); 4568 } 4569 } 4570 TE->setOperand(0, Left); 4571 TE->setOperand(1, Right); 4572 buildTree_rec(Left, Depth + 1, {TE, 0}); 4573 buildTree_rec(Right, Depth + 1, {TE, 1}); 4574 return; 4575 } 4576 4577 TE->setOperandsInOrder(); 4578 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4579 ValueList Operands; 4580 // Prepare the operand vector. 4581 for (Value *V : VL) 4582 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4583 4584 buildTree_rec(Operands, Depth + 1, {TE, i}); 4585 } 4586 return; 4587 } 4588 default: 4589 BS.cancelScheduling(VL, VL0); 4590 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4591 ReuseShuffleIndicies); 4592 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); 4593 return; 4594 } 4595 } 4596 4597 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const { 4598 unsigned N = 1; 4599 Type *EltTy = T; 4600 4601 while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) || 4602 isa<VectorType>(EltTy)) { 4603 if (auto *ST = dyn_cast<StructType>(EltTy)) { 4604 // Check that struct is homogeneous. 4605 for (const auto *Ty : ST->elements()) 4606 if (Ty != *ST->element_begin()) 4607 return 0; 4608 N *= ST->getNumElements(); 4609 EltTy = *ST->element_begin(); 4610 } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) { 4611 N *= AT->getNumElements(); 4612 EltTy = AT->getElementType(); 4613 } else { 4614 auto *VT = cast<FixedVectorType>(EltTy); 4615 N *= VT->getNumElements(); 4616 EltTy = VT->getElementType(); 4617 } 4618 } 4619 4620 if (!isValidElementType(EltTy)) 4621 return 0; 4622 uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N)); 4623 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T)) 4624 return 0; 4625 return N; 4626 } 4627 4628 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 4629 SmallVectorImpl<unsigned> &CurrentOrder) const { 4630 const auto *It = find_if(VL, [](Value *V) { 4631 return isa<ExtractElementInst, ExtractValueInst>(V); 4632 }); 4633 assert(It != VL.end() && "Expected at least one extract instruction."); 4634 auto *E0 = cast<Instruction>(*It); 4635 assert(all_of(VL, 4636 [](Value *V) { 4637 return isa<UndefValue, ExtractElementInst, ExtractValueInst>( 4638 V); 4639 }) && 4640 "Invalid opcode"); 4641 // Check if all of the extracts come from the same vector and from the 4642 // correct offset. 4643 Value *Vec = E0->getOperand(0); 4644 4645 CurrentOrder.clear(); 4646 4647 // We have to extract from a vector/aggregate with the same number of elements. 4648 unsigned NElts; 4649 if (E0->getOpcode() == Instruction::ExtractValue) { 4650 const DataLayout &DL = E0->getModule()->getDataLayout(); 4651 NElts = canMapToVector(Vec->getType(), DL); 4652 if (!NElts) 4653 return false; 4654 // Check if load can be rewritten as load of vector. 4655 LoadInst *LI = dyn_cast<LoadInst>(Vec); 4656 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size())) 4657 return false; 4658 } else { 4659 NElts = cast<FixedVectorType>(Vec->getType())->getNumElements(); 4660 } 4661 4662 if (NElts != VL.size()) 4663 return false; 4664 4665 // Check that all of the indices extract from the correct offset. 4666 bool ShouldKeepOrder = true; 4667 unsigned E = VL.size(); 4668 // Assign to all items the initial value E + 1 so we can check if the extract 4669 // instruction index was used already. 4670 // Also, later we can check that all the indices are used and we have a 4671 // consecutive access in the extract instructions, by checking that no 4672 // element of CurrentOrder still has value E + 1. 4673 CurrentOrder.assign(E, E); 4674 unsigned I = 0; 4675 for (; I < E; ++I) { 4676 auto *Inst = dyn_cast<Instruction>(VL[I]); 4677 if (!Inst) 4678 continue; 4679 if (Inst->getOperand(0) != Vec) 4680 break; 4681 if (auto *EE = dyn_cast<ExtractElementInst>(Inst)) 4682 if (isa<UndefValue>(EE->getIndexOperand())) 4683 continue; 4684 Optional<unsigned> Idx = getExtractIndex(Inst); 4685 if (!Idx) 4686 break; 4687 const unsigned ExtIdx = *Idx; 4688 if (ExtIdx != I) { 4689 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E) 4690 break; 4691 ShouldKeepOrder = false; 4692 CurrentOrder[ExtIdx] = I; 4693 } else { 4694 if (CurrentOrder[I] != E) 4695 break; 4696 CurrentOrder[I] = I; 4697 } 4698 } 4699 if (I < E) { 4700 CurrentOrder.clear(); 4701 return false; 4702 } 4703 if (ShouldKeepOrder) 4704 CurrentOrder.clear(); 4705 4706 return ShouldKeepOrder; 4707 } 4708 4709 bool BoUpSLP::areAllUsersVectorized(Instruction *I, 4710 ArrayRef<Value *> VectorizedVals) const { 4711 return (I->hasOneUse() && is_contained(VectorizedVals, I)) || 4712 all_of(I->users(), [this](User *U) { 4713 return ScalarToTreeEntry.count(U) > 0 || 4714 isVectorLikeInstWithConstOps(U) || 4715 (isa<ExtractElementInst>(U) && MustGather.contains(U)); 4716 }); 4717 } 4718 4719 static std::pair<InstructionCost, InstructionCost> 4720 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy, 4721 TargetTransformInfo *TTI, TargetLibraryInfo *TLI) { 4722 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4723 4724 // Calculate the cost of the scalar and vector calls. 4725 SmallVector<Type *, 4> VecTys; 4726 for (Use &Arg : CI->args()) 4727 VecTys.push_back( 4728 FixedVectorType::get(Arg->getType(), VecTy->getNumElements())); 4729 FastMathFlags FMF; 4730 if (auto *FPCI = dyn_cast<FPMathOperator>(CI)) 4731 FMF = FPCI->getFastMathFlags(); 4732 SmallVector<const Value *> Arguments(CI->args()); 4733 IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF, 4734 dyn_cast<IntrinsicInst>(CI)); 4735 auto IntrinsicCost = 4736 TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput); 4737 4738 auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 4739 VecTy->getNumElements())), 4740 false /*HasGlobalPred*/); 4741 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 4742 auto LibCost = IntrinsicCost; 4743 if (!CI->isNoBuiltin() && VecFunc) { 4744 // Calculate the cost of the vector library call. 4745 // If the corresponding vector call is cheaper, return its cost. 4746 LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys, 4747 TTI::TCK_RecipThroughput); 4748 } 4749 return {IntrinsicCost, LibCost}; 4750 } 4751 4752 /// Compute the cost of creating a vector of type \p VecTy containing the 4753 /// extracted values from \p VL. 4754 static InstructionCost 4755 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy, 4756 TargetTransformInfo::ShuffleKind ShuffleKind, 4757 ArrayRef<int> Mask, TargetTransformInfo &TTI) { 4758 unsigned NumOfParts = TTI.getNumberOfParts(VecTy); 4759 4760 if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts || 4761 VecTy->getNumElements() < NumOfParts) 4762 return TTI.getShuffleCost(ShuffleKind, VecTy, Mask); 4763 4764 bool AllConsecutive = true; 4765 unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts; 4766 unsigned Idx = -1; 4767 InstructionCost Cost = 0; 4768 4769 // Process extracts in blocks of EltsPerVector to check if the source vector 4770 // operand can be re-used directly. If not, add the cost of creating a shuffle 4771 // to extract the values into a vector register. 4772 for (auto *V : VL) { 4773 ++Idx; 4774 4775 // Need to exclude undefs from analysis. 4776 if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem) 4777 continue; 4778 4779 // Reached the start of a new vector registers. 4780 if (Idx % EltsPerVector == 0) { 4781 AllConsecutive = true; 4782 continue; 4783 } 4784 4785 // Check all extracts for a vector register on the target directly 4786 // extract values in order. 4787 unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V)); 4788 if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) { 4789 unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1])); 4790 AllConsecutive &= PrevIdx + 1 == CurrentIdx && 4791 CurrentIdx % EltsPerVector == Idx % EltsPerVector; 4792 } 4793 4794 if (AllConsecutive) 4795 continue; 4796 4797 // Skip all indices, except for the last index per vector block. 4798 if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size()) 4799 continue; 4800 4801 // If we have a series of extracts which are not consecutive and hence 4802 // cannot re-use the source vector register directly, compute the shuffle 4803 // cost to extract the a vector with EltsPerVector elements. 4804 Cost += TTI.getShuffleCost( 4805 TargetTransformInfo::SK_PermuteSingleSrc, 4806 FixedVectorType::get(VecTy->getElementType(), EltsPerVector)); 4807 } 4808 return Cost; 4809 } 4810 4811 /// Build shuffle mask for shuffle graph entries and lists of main and alternate 4812 /// operations operands. 4813 static void 4814 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices, 4815 ArrayRef<int> ReusesIndices, 4816 const function_ref<bool(Instruction *)> IsAltOp, 4817 SmallVectorImpl<int> &Mask, 4818 SmallVectorImpl<Value *> *OpScalars = nullptr, 4819 SmallVectorImpl<Value *> *AltScalars = nullptr) { 4820 unsigned Sz = VL.size(); 4821 Mask.assign(Sz, UndefMaskElem); 4822 SmallVector<int> OrderMask; 4823 if (!ReorderIndices.empty()) 4824 inversePermutation(ReorderIndices, OrderMask); 4825 for (unsigned I = 0; I < Sz; ++I) { 4826 unsigned Idx = I; 4827 if (!ReorderIndices.empty()) 4828 Idx = OrderMask[I]; 4829 auto *OpInst = cast<Instruction>(VL[Idx]); 4830 if (IsAltOp(OpInst)) { 4831 Mask[I] = Sz + Idx; 4832 if (AltScalars) 4833 AltScalars->push_back(OpInst); 4834 } else { 4835 Mask[I] = Idx; 4836 if (OpScalars) 4837 OpScalars->push_back(OpInst); 4838 } 4839 } 4840 if (!ReusesIndices.empty()) { 4841 SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem); 4842 transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) { 4843 return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem; 4844 }); 4845 Mask.swap(NewMask); 4846 } 4847 } 4848 4849 /// Checks if the specified instruction \p I is an alternate operation for the 4850 /// given \p MainOp and \p AltOp instructions. 4851 static bool isAlternateInstruction(const Instruction *I, 4852 const Instruction *MainOp, 4853 const Instruction *AltOp) { 4854 if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) { 4855 auto *AltCI0 = cast<CmpInst>(AltOp); 4856 auto *CI = cast<CmpInst>(I); 4857 CmpInst::Predicate P0 = CI0->getPredicate(); 4858 CmpInst::Predicate AltP0 = AltCI0->getPredicate(); 4859 assert(P0 != AltP0 && "Expected different main/alternate predicates."); 4860 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 4861 CmpInst::Predicate CurrentPred = CI->getPredicate(); 4862 if (P0 == AltP0Swapped) 4863 return I == AltCI0 || 4864 (I != MainOp && 4865 !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1), 4866 CI->getOperand(0), CI->getOperand(1))); 4867 return AltP0 == CurrentPred || AltP0Swapped == CurrentPred; 4868 } 4869 return I->getOpcode() == AltOp->getOpcode(); 4870 } 4871 4872 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E, 4873 ArrayRef<Value *> VectorizedVals) { 4874 ArrayRef<Value*> VL = E->Scalars; 4875 4876 Type *ScalarTy = VL[0]->getType(); 4877 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 4878 ScalarTy = SI->getValueOperand()->getType(); 4879 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0])) 4880 ScalarTy = CI->getOperand(0)->getType(); 4881 else if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 4882 ScalarTy = IE->getOperand(1)->getType(); 4883 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 4884 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 4885 4886 // If we have computed a smaller type for the expression, update VecTy so 4887 // that the costs will be accurate. 4888 if (MinBWs.count(VL[0])) 4889 VecTy = FixedVectorType::get( 4890 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size()); 4891 unsigned EntryVF = E->getVectorFactor(); 4892 auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF); 4893 4894 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 4895 // FIXME: it tries to fix a problem with MSVC buildbots. 4896 TargetTransformInfo &TTIRef = *TTI; 4897 auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy, 4898 VectorizedVals, E](InstructionCost &Cost) { 4899 DenseMap<Value *, int> ExtractVectorsTys; 4900 SmallPtrSet<Value *, 4> CheckedExtracts; 4901 for (auto *V : VL) { 4902 if (isa<UndefValue>(V)) 4903 continue; 4904 // If all users of instruction are going to be vectorized and this 4905 // instruction itself is not going to be vectorized, consider this 4906 // instruction as dead and remove its cost from the final cost of the 4907 // vectorized tree. 4908 // Also, avoid adjusting the cost for extractelements with multiple uses 4909 // in different graph entries. 4910 const TreeEntry *VE = getTreeEntry(V); 4911 if (!CheckedExtracts.insert(V).second || 4912 !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) || 4913 (VE && VE != E)) 4914 continue; 4915 auto *EE = cast<ExtractElementInst>(V); 4916 Optional<unsigned> EEIdx = getExtractIndex(EE); 4917 if (!EEIdx) 4918 continue; 4919 unsigned Idx = *EEIdx; 4920 if (TTIRef.getNumberOfParts(VecTy) != 4921 TTIRef.getNumberOfParts(EE->getVectorOperandType())) { 4922 auto It = 4923 ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first; 4924 It->getSecond() = std::min<int>(It->second, Idx); 4925 } 4926 // Take credit for instruction that will become dead. 4927 if (EE->hasOneUse()) { 4928 Instruction *Ext = EE->user_back(); 4929 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 4930 all_of(Ext->users(), 4931 [](User *U) { return isa<GetElementPtrInst>(U); })) { 4932 // Use getExtractWithExtendCost() to calculate the cost of 4933 // extractelement/ext pair. 4934 Cost -= 4935 TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(), 4936 EE->getVectorOperandType(), Idx); 4937 // Add back the cost of s|zext which is subtracted separately. 4938 Cost += TTIRef.getCastInstrCost( 4939 Ext->getOpcode(), Ext->getType(), EE->getType(), 4940 TTI::getCastContextHint(Ext), CostKind, Ext); 4941 continue; 4942 } 4943 } 4944 Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement, 4945 EE->getVectorOperandType(), Idx); 4946 } 4947 // Add a cost for subvector extracts/inserts if required. 4948 for (const auto &Data : ExtractVectorsTys) { 4949 auto *EEVTy = cast<FixedVectorType>(Data.first->getType()); 4950 unsigned NumElts = VecTy->getNumElements(); 4951 if (Data.second % NumElts == 0) 4952 continue; 4953 if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) { 4954 unsigned Idx = (Data.second / NumElts) * NumElts; 4955 unsigned EENumElts = EEVTy->getNumElements(); 4956 if (Idx + NumElts <= EENumElts) { 4957 Cost += 4958 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 4959 EEVTy, None, Idx, VecTy); 4960 } else { 4961 // Need to round up the subvector type vectorization factor to avoid a 4962 // crash in cost model functions. Make SubVT so that Idx + VF of SubVT 4963 // <= EENumElts. 4964 auto *SubVT = 4965 FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx); 4966 Cost += 4967 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 4968 EEVTy, None, Idx, SubVT); 4969 } 4970 } else { 4971 Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector, 4972 VecTy, None, 0, EEVTy); 4973 } 4974 } 4975 }; 4976 if (E->State == TreeEntry::NeedToGather) { 4977 if (allConstant(VL)) 4978 return 0; 4979 if (isa<InsertElementInst>(VL[0])) 4980 return InstructionCost::getInvalid(); 4981 SmallVector<int> Mask; 4982 SmallVector<const TreeEntry *> Entries; 4983 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 4984 isGatherShuffledEntry(E, Mask, Entries); 4985 if (Shuffle.hasValue()) { 4986 InstructionCost GatherCost = 0; 4987 if (ShuffleVectorInst::isIdentityMask(Mask)) { 4988 // Perfect match in the graph, will reuse the previously vectorized 4989 // node. Cost is 0. 4990 LLVM_DEBUG( 4991 dbgs() 4992 << "SLP: perfect diamond match for gather bundle that starts with " 4993 << *VL.front() << ".\n"); 4994 if (NeedToShuffleReuses) 4995 GatherCost = 4996 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 4997 FinalVecTy, E->ReuseShuffleIndices); 4998 } else { 4999 LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size() 5000 << " entries for bundle that starts with " 5001 << *VL.front() << ".\n"); 5002 // Detected that instead of gather we can emit a shuffle of single/two 5003 // previously vectorized nodes. Add the cost of the permutation rather 5004 // than gather. 5005 ::addMask(Mask, E->ReuseShuffleIndices); 5006 GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask); 5007 } 5008 return GatherCost; 5009 } 5010 if ((E->getOpcode() == Instruction::ExtractElement || 5011 all_of(E->Scalars, 5012 [](Value *V) { 5013 return isa<ExtractElementInst, UndefValue>(V); 5014 })) && 5015 allSameType(VL)) { 5016 // Check that gather of extractelements can be represented as just a 5017 // shuffle of a single/two vectors the scalars are extracted from. 5018 SmallVector<int> Mask; 5019 Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = 5020 isFixedVectorShuffle(VL, Mask); 5021 if (ShuffleKind.hasValue()) { 5022 // Found the bunch of extractelement instructions that must be gathered 5023 // into a vector and can be represented as a permutation elements in a 5024 // single input vector or of 2 input vectors. 5025 InstructionCost Cost = 5026 computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI); 5027 AdjustExtractsCost(Cost); 5028 if (NeedToShuffleReuses) 5029 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 5030 FinalVecTy, E->ReuseShuffleIndices); 5031 return Cost; 5032 } 5033 } 5034 if (isSplat(VL)) { 5035 // Found the broadcasting of the single scalar, calculate the cost as the 5036 // broadcast. 5037 assert(VecTy == FinalVecTy && 5038 "No reused scalars expected for broadcast."); 5039 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy); 5040 } 5041 InstructionCost ReuseShuffleCost = 0; 5042 if (NeedToShuffleReuses) 5043 ReuseShuffleCost = TTI->getShuffleCost( 5044 TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices); 5045 // Improve gather cost for gather of loads, if we can group some of the 5046 // loads into vector loads. 5047 if (VL.size() > 2 && E->getOpcode() == Instruction::Load && 5048 !E->isAltShuffle()) { 5049 BoUpSLP::ValueSet VectorizedLoads; 5050 unsigned StartIdx = 0; 5051 unsigned VF = VL.size() / 2; 5052 unsigned VectorizedCnt = 0; 5053 unsigned ScatterVectorizeCnt = 0; 5054 const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType()); 5055 for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) { 5056 for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End; 5057 Cnt += VF) { 5058 ArrayRef<Value *> Slice = VL.slice(Cnt, VF); 5059 if (!VectorizedLoads.count(Slice.front()) && 5060 !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) { 5061 SmallVector<Value *> PointerOps; 5062 OrdersType CurrentOrder; 5063 LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL, 5064 *SE, CurrentOrder, PointerOps); 5065 switch (LS) { 5066 case LoadsState::Vectorize: 5067 case LoadsState::ScatterVectorize: 5068 // Mark the vectorized loads so that we don't vectorize them 5069 // again. 5070 if (LS == LoadsState::Vectorize) 5071 ++VectorizedCnt; 5072 else 5073 ++ScatterVectorizeCnt; 5074 VectorizedLoads.insert(Slice.begin(), Slice.end()); 5075 // If we vectorized initial block, no need to try to vectorize it 5076 // again. 5077 if (Cnt == StartIdx) 5078 StartIdx += VF; 5079 break; 5080 case LoadsState::Gather: 5081 break; 5082 } 5083 } 5084 } 5085 // Check if the whole array was vectorized already - exit. 5086 if (StartIdx >= VL.size()) 5087 break; 5088 // Found vectorizable parts - exit. 5089 if (!VectorizedLoads.empty()) 5090 break; 5091 } 5092 if (!VectorizedLoads.empty()) { 5093 InstructionCost GatherCost = 0; 5094 unsigned NumParts = TTI->getNumberOfParts(VecTy); 5095 bool NeedInsertSubvectorAnalysis = 5096 !NumParts || (VL.size() / VF) > NumParts; 5097 // Get the cost for gathered loads. 5098 for (unsigned I = 0, End = VL.size(); I < End; I += VF) { 5099 if (VectorizedLoads.contains(VL[I])) 5100 continue; 5101 GatherCost += getGatherCost(VL.slice(I, VF)); 5102 } 5103 // The cost for vectorized loads. 5104 InstructionCost ScalarsCost = 0; 5105 for (Value *V : VectorizedLoads) { 5106 auto *LI = cast<LoadInst>(V); 5107 ScalarsCost += TTI->getMemoryOpCost( 5108 Instruction::Load, LI->getType(), LI->getAlign(), 5109 LI->getPointerAddressSpace(), CostKind, LI); 5110 } 5111 auto *LI = cast<LoadInst>(E->getMainOp()); 5112 auto *LoadTy = FixedVectorType::get(LI->getType(), VF); 5113 Align Alignment = LI->getAlign(); 5114 GatherCost += 5115 VectorizedCnt * 5116 TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment, 5117 LI->getPointerAddressSpace(), CostKind, LI); 5118 GatherCost += ScatterVectorizeCnt * 5119 TTI->getGatherScatterOpCost( 5120 Instruction::Load, LoadTy, LI->getPointerOperand(), 5121 /*VariableMask=*/false, Alignment, CostKind, LI); 5122 if (NeedInsertSubvectorAnalysis) { 5123 // Add the cost for the subvectors insert. 5124 for (int I = VF, E = VL.size(); I < E; I += VF) 5125 GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy, 5126 None, I, LoadTy); 5127 } 5128 return ReuseShuffleCost + GatherCost - ScalarsCost; 5129 } 5130 } 5131 return ReuseShuffleCost + getGatherCost(VL); 5132 } 5133 InstructionCost CommonCost = 0; 5134 SmallVector<int> Mask; 5135 if (!E->ReorderIndices.empty()) { 5136 SmallVector<int> NewMask; 5137 if (E->getOpcode() == Instruction::Store) { 5138 // For stores the order is actually a mask. 5139 NewMask.resize(E->ReorderIndices.size()); 5140 copy(E->ReorderIndices, NewMask.begin()); 5141 } else { 5142 inversePermutation(E->ReorderIndices, NewMask); 5143 } 5144 ::addMask(Mask, NewMask); 5145 } 5146 if (NeedToShuffleReuses) 5147 ::addMask(Mask, E->ReuseShuffleIndices); 5148 if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask)) 5149 CommonCost = 5150 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask); 5151 assert((E->State == TreeEntry::Vectorize || 5152 E->State == TreeEntry::ScatterVectorize) && 5153 "Unhandled state"); 5154 assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL"); 5155 Instruction *VL0 = E->getMainOp(); 5156 unsigned ShuffleOrOp = 5157 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 5158 switch (ShuffleOrOp) { 5159 case Instruction::PHI: 5160 return 0; 5161 5162 case Instruction::ExtractValue: 5163 case Instruction::ExtractElement: { 5164 // The common cost of removal ExtractElement/ExtractValue instructions + 5165 // the cost of shuffles, if required to resuffle the original vector. 5166 if (NeedToShuffleReuses) { 5167 unsigned Idx = 0; 5168 for (unsigned I : E->ReuseShuffleIndices) { 5169 if (ShuffleOrOp == Instruction::ExtractElement) { 5170 auto *EE = cast<ExtractElementInst>(VL[I]); 5171 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 5172 EE->getVectorOperandType(), 5173 *getExtractIndex(EE)); 5174 } else { 5175 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 5176 VecTy, Idx); 5177 ++Idx; 5178 } 5179 } 5180 Idx = EntryVF; 5181 for (Value *V : VL) { 5182 if (ShuffleOrOp == Instruction::ExtractElement) { 5183 auto *EE = cast<ExtractElementInst>(V); 5184 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 5185 EE->getVectorOperandType(), 5186 *getExtractIndex(EE)); 5187 } else { 5188 --Idx; 5189 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 5190 VecTy, Idx); 5191 } 5192 } 5193 } 5194 if (ShuffleOrOp == Instruction::ExtractValue) { 5195 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 5196 auto *EI = cast<Instruction>(VL[I]); 5197 // Take credit for instruction that will become dead. 5198 if (EI->hasOneUse()) { 5199 Instruction *Ext = EI->user_back(); 5200 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 5201 all_of(Ext->users(), 5202 [](User *U) { return isa<GetElementPtrInst>(U); })) { 5203 // Use getExtractWithExtendCost() to calculate the cost of 5204 // extractelement/ext pair. 5205 CommonCost -= TTI->getExtractWithExtendCost( 5206 Ext->getOpcode(), Ext->getType(), VecTy, I); 5207 // Add back the cost of s|zext which is subtracted separately. 5208 CommonCost += TTI->getCastInstrCost( 5209 Ext->getOpcode(), Ext->getType(), EI->getType(), 5210 TTI::getCastContextHint(Ext), CostKind, Ext); 5211 continue; 5212 } 5213 } 5214 CommonCost -= 5215 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I); 5216 } 5217 } else { 5218 AdjustExtractsCost(CommonCost); 5219 } 5220 return CommonCost; 5221 } 5222 case Instruction::InsertElement: { 5223 assert(E->ReuseShuffleIndices.empty() && 5224 "Unique insertelements only are expected."); 5225 auto *SrcVecTy = cast<FixedVectorType>(VL0->getType()); 5226 5227 unsigned const NumElts = SrcVecTy->getNumElements(); 5228 unsigned const NumScalars = VL.size(); 5229 APInt DemandedElts = APInt::getZero(NumElts); 5230 // TODO: Add support for Instruction::InsertValue. 5231 SmallVector<int> Mask; 5232 if (!E->ReorderIndices.empty()) { 5233 inversePermutation(E->ReorderIndices, Mask); 5234 Mask.append(NumElts - NumScalars, UndefMaskElem); 5235 } else { 5236 Mask.assign(NumElts, UndefMaskElem); 5237 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 5238 } 5239 unsigned Offset = *getInsertIndex(VL0); 5240 bool IsIdentity = true; 5241 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 5242 Mask.swap(PrevMask); 5243 for (unsigned I = 0; I < NumScalars; ++I) { 5244 unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]); 5245 DemandedElts.setBit(InsertIdx); 5246 IsIdentity &= InsertIdx - Offset == I; 5247 Mask[InsertIdx - Offset] = I; 5248 } 5249 assert(Offset < NumElts && "Failed to find vector index offset"); 5250 5251 InstructionCost Cost = 0; 5252 Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts, 5253 /*Insert*/ true, /*Extract*/ false); 5254 5255 if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) { 5256 // FIXME: Replace with SK_InsertSubvector once it is properly supported. 5257 unsigned Sz = PowerOf2Ceil(Offset + NumScalars); 5258 Cost += TTI->getShuffleCost( 5259 TargetTransformInfo::SK_PermuteSingleSrc, 5260 FixedVectorType::get(SrcVecTy->getElementType(), Sz)); 5261 } else if (!IsIdentity) { 5262 auto *FirstInsert = 5263 cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 5264 return !is_contained(E->Scalars, 5265 cast<Instruction>(V)->getOperand(0)); 5266 })); 5267 if (isUndefVector(FirstInsert->getOperand(0))) { 5268 Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask); 5269 } else { 5270 SmallVector<int> InsertMask(NumElts); 5271 std::iota(InsertMask.begin(), InsertMask.end(), 0); 5272 for (unsigned I = 0; I < NumElts; I++) { 5273 if (Mask[I] != UndefMaskElem) 5274 InsertMask[Offset + I] = NumElts + I; 5275 } 5276 Cost += 5277 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask); 5278 } 5279 } 5280 5281 return Cost; 5282 } 5283 case Instruction::ZExt: 5284 case Instruction::SExt: 5285 case Instruction::FPToUI: 5286 case Instruction::FPToSI: 5287 case Instruction::FPExt: 5288 case Instruction::PtrToInt: 5289 case Instruction::IntToPtr: 5290 case Instruction::SIToFP: 5291 case Instruction::UIToFP: 5292 case Instruction::Trunc: 5293 case Instruction::FPTrunc: 5294 case Instruction::BitCast: { 5295 Type *SrcTy = VL0->getOperand(0)->getType(); 5296 InstructionCost ScalarEltCost = 5297 TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy, 5298 TTI::getCastContextHint(VL0), CostKind, VL0); 5299 if (NeedToShuffleReuses) { 5300 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5301 } 5302 5303 // Calculate the cost of this instruction. 5304 InstructionCost ScalarCost = VL.size() * ScalarEltCost; 5305 5306 auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size()); 5307 InstructionCost VecCost = 0; 5308 // Check if the values are candidates to demote. 5309 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) { 5310 VecCost = CommonCost + TTI->getCastInstrCost( 5311 E->getOpcode(), VecTy, SrcVecTy, 5312 TTI::getCastContextHint(VL0), CostKind, VL0); 5313 } 5314 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5315 return VecCost - ScalarCost; 5316 } 5317 case Instruction::FCmp: 5318 case Instruction::ICmp: 5319 case Instruction::Select: { 5320 // Calculate the cost of this instruction. 5321 InstructionCost ScalarEltCost = 5322 TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 5323 CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0); 5324 if (NeedToShuffleReuses) { 5325 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5326 } 5327 auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size()); 5328 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5329 5330 // Check if all entries in VL are either compares or selects with compares 5331 // as condition that have the same predicates. 5332 CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE; 5333 bool First = true; 5334 for (auto *V : VL) { 5335 CmpInst::Predicate CurrentPred; 5336 auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value()); 5337 if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) && 5338 !match(V, MatchCmp)) || 5339 (!First && VecPred != CurrentPred)) { 5340 VecPred = CmpInst::BAD_ICMP_PREDICATE; 5341 break; 5342 } 5343 First = false; 5344 VecPred = CurrentPred; 5345 } 5346 5347 InstructionCost VecCost = TTI->getCmpSelInstrCost( 5348 E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0); 5349 // Check if it is possible and profitable to use min/max for selects in 5350 // VL. 5351 // 5352 auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL); 5353 if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) { 5354 IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy, 5355 {VecTy, VecTy}); 5356 InstructionCost IntrinsicCost = 5357 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 5358 // If the selects are the only uses of the compares, they will be dead 5359 // and we can adjust the cost by removing their cost. 5360 if (IntrinsicAndUse.second) 5361 IntrinsicCost -= 5362 TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy, 5363 CmpInst::BAD_ICMP_PREDICATE, CostKind); 5364 VecCost = std::min(VecCost, IntrinsicCost); 5365 } 5366 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5367 return CommonCost + VecCost - ScalarCost; 5368 } 5369 case Instruction::FNeg: 5370 case Instruction::Add: 5371 case Instruction::FAdd: 5372 case Instruction::Sub: 5373 case Instruction::FSub: 5374 case Instruction::Mul: 5375 case Instruction::FMul: 5376 case Instruction::UDiv: 5377 case Instruction::SDiv: 5378 case Instruction::FDiv: 5379 case Instruction::URem: 5380 case Instruction::SRem: 5381 case Instruction::FRem: 5382 case Instruction::Shl: 5383 case Instruction::LShr: 5384 case Instruction::AShr: 5385 case Instruction::And: 5386 case Instruction::Or: 5387 case Instruction::Xor: { 5388 // Certain instructions can be cheaper to vectorize if they have a 5389 // constant second vector operand. 5390 TargetTransformInfo::OperandValueKind Op1VK = 5391 TargetTransformInfo::OK_AnyValue; 5392 TargetTransformInfo::OperandValueKind Op2VK = 5393 TargetTransformInfo::OK_UniformConstantValue; 5394 TargetTransformInfo::OperandValueProperties Op1VP = 5395 TargetTransformInfo::OP_None; 5396 TargetTransformInfo::OperandValueProperties Op2VP = 5397 TargetTransformInfo::OP_PowerOf2; 5398 5399 // If all operands are exactly the same ConstantInt then set the 5400 // operand kind to OK_UniformConstantValue. 5401 // If instead not all operands are constants, then set the operand kind 5402 // to OK_AnyValue. If all operands are constants but not the same, 5403 // then set the operand kind to OK_NonUniformConstantValue. 5404 ConstantInt *CInt0 = nullptr; 5405 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 5406 const Instruction *I = cast<Instruction>(VL[i]); 5407 unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0; 5408 ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx)); 5409 if (!CInt) { 5410 Op2VK = TargetTransformInfo::OK_AnyValue; 5411 Op2VP = TargetTransformInfo::OP_None; 5412 break; 5413 } 5414 if (Op2VP == TargetTransformInfo::OP_PowerOf2 && 5415 !CInt->getValue().isPowerOf2()) 5416 Op2VP = TargetTransformInfo::OP_None; 5417 if (i == 0) { 5418 CInt0 = CInt; 5419 continue; 5420 } 5421 if (CInt0 != CInt) 5422 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 5423 } 5424 5425 SmallVector<const Value *, 4> Operands(VL0->operand_values()); 5426 InstructionCost ScalarEltCost = 5427 TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK, 5428 Op2VK, Op1VP, Op2VP, Operands, VL0); 5429 if (NeedToShuffleReuses) { 5430 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5431 } 5432 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5433 InstructionCost VecCost = 5434 TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK, 5435 Op2VK, Op1VP, Op2VP, Operands, VL0); 5436 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5437 return CommonCost + VecCost - ScalarCost; 5438 } 5439 case Instruction::GetElementPtr: { 5440 TargetTransformInfo::OperandValueKind Op1VK = 5441 TargetTransformInfo::OK_AnyValue; 5442 TargetTransformInfo::OperandValueKind Op2VK = 5443 TargetTransformInfo::OK_UniformConstantValue; 5444 5445 InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost( 5446 Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK); 5447 if (NeedToShuffleReuses) { 5448 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5449 } 5450 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5451 InstructionCost VecCost = TTI->getArithmeticInstrCost( 5452 Instruction::Add, VecTy, CostKind, Op1VK, Op2VK); 5453 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5454 return CommonCost + VecCost - ScalarCost; 5455 } 5456 case Instruction::Load: { 5457 // Cost of wide load - cost of scalar loads. 5458 Align Alignment = cast<LoadInst>(VL0)->getAlign(); 5459 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 5460 Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0); 5461 if (NeedToShuffleReuses) { 5462 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5463 } 5464 InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost; 5465 InstructionCost VecLdCost; 5466 if (E->State == TreeEntry::Vectorize) { 5467 VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0, 5468 CostKind, VL0); 5469 } else { 5470 assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState"); 5471 Align CommonAlignment = Alignment; 5472 for (Value *V : VL) 5473 CommonAlignment = 5474 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 5475 VecLdCost = TTI->getGatherScatterOpCost( 5476 Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(), 5477 /*VariableMask=*/false, CommonAlignment, CostKind, VL0); 5478 } 5479 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost)); 5480 return CommonCost + VecLdCost - ScalarLdCost; 5481 } 5482 case Instruction::Store: { 5483 // We know that we can merge the stores. Calculate the cost. 5484 bool IsReorder = !E->ReorderIndices.empty(); 5485 auto *SI = 5486 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0); 5487 Align Alignment = SI->getAlign(); 5488 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 5489 Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0); 5490 InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost; 5491 InstructionCost VecStCost = TTI->getMemoryOpCost( 5492 Instruction::Store, VecTy, Alignment, 0, CostKind, VL0); 5493 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost)); 5494 return CommonCost + VecStCost - ScalarStCost; 5495 } 5496 case Instruction::Call: { 5497 CallInst *CI = cast<CallInst>(VL0); 5498 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 5499 5500 // Calculate the cost of the scalar and vector calls. 5501 IntrinsicCostAttributes CostAttrs(ID, *CI, 1); 5502 InstructionCost ScalarEltCost = 5503 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 5504 if (NeedToShuffleReuses) { 5505 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5506 } 5507 InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost; 5508 5509 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 5510 InstructionCost VecCallCost = 5511 std::min(VecCallCosts.first, VecCallCosts.second); 5512 5513 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost 5514 << " (" << VecCallCost << "-" << ScalarCallCost << ")" 5515 << " for " << *CI << "\n"); 5516 5517 return CommonCost + VecCallCost - ScalarCallCost; 5518 } 5519 case Instruction::ShuffleVector: { 5520 assert(E->isAltShuffle() && 5521 ((Instruction::isBinaryOp(E->getOpcode()) && 5522 Instruction::isBinaryOp(E->getAltOpcode())) || 5523 (Instruction::isCast(E->getOpcode()) && 5524 Instruction::isCast(E->getAltOpcode())) || 5525 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 5526 "Invalid Shuffle Vector Operand"); 5527 InstructionCost ScalarCost = 0; 5528 if (NeedToShuffleReuses) { 5529 for (unsigned Idx : E->ReuseShuffleIndices) { 5530 Instruction *I = cast<Instruction>(VL[Idx]); 5531 CommonCost -= TTI->getInstructionCost(I, CostKind); 5532 } 5533 for (Value *V : VL) { 5534 Instruction *I = cast<Instruction>(V); 5535 CommonCost += TTI->getInstructionCost(I, CostKind); 5536 } 5537 } 5538 for (Value *V : VL) { 5539 Instruction *I = cast<Instruction>(V); 5540 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 5541 ScalarCost += TTI->getInstructionCost(I, CostKind); 5542 } 5543 // VecCost is equal to sum of the cost of creating 2 vectors 5544 // and the cost of creating shuffle. 5545 InstructionCost VecCost = 0; 5546 // Try to find the previous shuffle node with the same operands and same 5547 // main/alternate ops. 5548 auto &&TryFindNodeWithEqualOperands = [this, E]() { 5549 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 5550 if (TE.get() == E) 5551 break; 5552 if (TE->isAltShuffle() && 5553 ((TE->getOpcode() == E->getOpcode() && 5554 TE->getAltOpcode() == E->getAltOpcode()) || 5555 (TE->getOpcode() == E->getAltOpcode() && 5556 TE->getAltOpcode() == E->getOpcode())) && 5557 TE->hasEqualOperands(*E)) 5558 return true; 5559 } 5560 return false; 5561 }; 5562 if (TryFindNodeWithEqualOperands()) { 5563 LLVM_DEBUG({ 5564 dbgs() << "SLP: diamond match for alternate node found.\n"; 5565 E->dump(); 5566 }); 5567 // No need to add new vector costs here since we're going to reuse 5568 // same main/alternate vector ops, just do different shuffling. 5569 } else if (Instruction::isBinaryOp(E->getOpcode())) { 5570 VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind); 5571 VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy, 5572 CostKind); 5573 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 5574 VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, 5575 Builder.getInt1Ty(), 5576 CI0->getPredicate(), CostKind, VL0); 5577 VecCost += TTI->getCmpSelInstrCost( 5578 E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 5579 cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind, 5580 E->getAltOp()); 5581 } else { 5582 Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType(); 5583 Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType(); 5584 auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size()); 5585 auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size()); 5586 VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty, 5587 TTI::CastContextHint::None, CostKind); 5588 VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty, 5589 TTI::CastContextHint::None, CostKind); 5590 } 5591 5592 SmallVector<int> Mask; 5593 buildShuffleEntryMask( 5594 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 5595 [E](Instruction *I) { 5596 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 5597 return isAlternateInstruction(I, E->getMainOp(), E->getAltOp()); 5598 }, 5599 Mask); 5600 CommonCost = 5601 TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask); 5602 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5603 return CommonCost + VecCost - ScalarCost; 5604 } 5605 default: 5606 llvm_unreachable("Unknown instruction"); 5607 } 5608 } 5609 5610 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const { 5611 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height " 5612 << VectorizableTree.size() << " is fully vectorizable .\n"); 5613 5614 auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) { 5615 SmallVector<int> Mask; 5616 return TE->State == TreeEntry::NeedToGather && 5617 !any_of(TE->Scalars, 5618 [this](Value *V) { return EphValues.contains(V); }) && 5619 (allConstant(TE->Scalars) || isSplat(TE->Scalars) || 5620 TE->Scalars.size() < Limit || 5621 ((TE->getOpcode() == Instruction::ExtractElement || 5622 all_of(TE->Scalars, 5623 [](Value *V) { 5624 return isa<ExtractElementInst, UndefValue>(V); 5625 })) && 5626 isFixedVectorShuffle(TE->Scalars, Mask)) || 5627 (TE->State == TreeEntry::NeedToGather && 5628 TE->getOpcode() == Instruction::Load && !TE->isAltShuffle())); 5629 }; 5630 5631 // We only handle trees of heights 1 and 2. 5632 if (VectorizableTree.size() == 1 && 5633 (VectorizableTree[0]->State == TreeEntry::Vectorize || 5634 (ForReduction && 5635 AreVectorizableGathers(VectorizableTree[0].get(), 5636 VectorizableTree[0]->Scalars.size()) && 5637 VectorizableTree[0]->getVectorFactor() > 2))) 5638 return true; 5639 5640 if (VectorizableTree.size() != 2) 5641 return false; 5642 5643 // Handle splat and all-constants stores. Also try to vectorize tiny trees 5644 // with the second gather nodes if they have less scalar operands rather than 5645 // the initial tree element (may be profitable to shuffle the second gather) 5646 // or they are extractelements, which form shuffle. 5647 SmallVector<int> Mask; 5648 if (VectorizableTree[0]->State == TreeEntry::Vectorize && 5649 AreVectorizableGathers(VectorizableTree[1].get(), 5650 VectorizableTree[0]->Scalars.size())) 5651 return true; 5652 5653 // Gathering cost would be too much for tiny trees. 5654 if (VectorizableTree[0]->State == TreeEntry::NeedToGather || 5655 (VectorizableTree[1]->State == TreeEntry::NeedToGather && 5656 VectorizableTree[0]->State != TreeEntry::ScatterVectorize)) 5657 return false; 5658 5659 return true; 5660 } 5661 5662 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts, 5663 TargetTransformInfo *TTI, 5664 bool MustMatchOrInst) { 5665 // Look past the root to find a source value. Arbitrarily follow the 5666 // path through operand 0 of any 'or'. Also, peek through optional 5667 // shift-left-by-multiple-of-8-bits. 5668 Value *ZextLoad = Root; 5669 const APInt *ShAmtC; 5670 bool FoundOr = false; 5671 while (!isa<ConstantExpr>(ZextLoad) && 5672 (match(ZextLoad, m_Or(m_Value(), m_Value())) || 5673 (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) && 5674 ShAmtC->urem(8) == 0))) { 5675 auto *BinOp = cast<BinaryOperator>(ZextLoad); 5676 ZextLoad = BinOp->getOperand(0); 5677 if (BinOp->getOpcode() == Instruction::Or) 5678 FoundOr = true; 5679 } 5680 // Check if the input is an extended load of the required or/shift expression. 5681 Value *Load; 5682 if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root || 5683 !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load)) 5684 return false; 5685 5686 // Require that the total load bit width is a legal integer type. 5687 // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target. 5688 // But <16 x i8> --> i128 is not, so the backend probably can't reduce it. 5689 Type *SrcTy = Load->getType(); 5690 unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts; 5691 if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth))) 5692 return false; 5693 5694 // Everything matched - assume that we can fold the whole sequence using 5695 // load combining. 5696 LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at " 5697 << *(cast<Instruction>(Root)) << "\n"); 5698 5699 return true; 5700 } 5701 5702 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const { 5703 if (RdxKind != RecurKind::Or) 5704 return false; 5705 5706 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 5707 Value *FirstReduced = VectorizableTree[0]->Scalars[0]; 5708 return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI, 5709 /* MatchOr */ false); 5710 } 5711 5712 bool BoUpSLP::isLoadCombineCandidate() const { 5713 // Peek through a final sequence of stores and check if all operations are 5714 // likely to be load-combined. 5715 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 5716 for (Value *Scalar : VectorizableTree[0]->Scalars) { 5717 Value *X; 5718 if (!match(Scalar, m_Store(m_Value(X), m_Value())) || 5719 !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true)) 5720 return false; 5721 } 5722 return true; 5723 } 5724 5725 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const { 5726 // No need to vectorize inserts of gathered values. 5727 if (VectorizableTree.size() == 2 && 5728 isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) && 5729 VectorizableTree[1]->State == TreeEntry::NeedToGather) 5730 return true; 5731 5732 // We can vectorize the tree if its size is greater than or equal to the 5733 // minimum size specified by the MinTreeSize command line option. 5734 if (VectorizableTree.size() >= MinTreeSize) 5735 return false; 5736 5737 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we 5738 // can vectorize it if we can prove it fully vectorizable. 5739 if (isFullyVectorizableTinyTree(ForReduction)) 5740 return false; 5741 5742 assert(VectorizableTree.empty() 5743 ? ExternalUses.empty() 5744 : true && "We shouldn't have any external users"); 5745 5746 // Otherwise, we can't vectorize the tree. It is both tiny and not fully 5747 // vectorizable. 5748 return true; 5749 } 5750 5751 InstructionCost BoUpSLP::getSpillCost() const { 5752 // Walk from the bottom of the tree to the top, tracking which values are 5753 // live. When we see a call instruction that is not part of our tree, 5754 // query TTI to see if there is a cost to keeping values live over it 5755 // (for example, if spills and fills are required). 5756 unsigned BundleWidth = VectorizableTree.front()->Scalars.size(); 5757 InstructionCost Cost = 0; 5758 5759 SmallPtrSet<Instruction*, 4> LiveValues; 5760 Instruction *PrevInst = nullptr; 5761 5762 // The entries in VectorizableTree are not necessarily ordered by their 5763 // position in basic blocks. Collect them and order them by dominance so later 5764 // instructions are guaranteed to be visited first. For instructions in 5765 // different basic blocks, we only scan to the beginning of the block, so 5766 // their order does not matter, as long as all instructions in a basic block 5767 // are grouped together. Using dominance ensures a deterministic order. 5768 SmallVector<Instruction *, 16> OrderedScalars; 5769 for (const auto &TEPtr : VectorizableTree) { 5770 Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]); 5771 if (!Inst) 5772 continue; 5773 OrderedScalars.push_back(Inst); 5774 } 5775 llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) { 5776 auto *NodeA = DT->getNode(A->getParent()); 5777 auto *NodeB = DT->getNode(B->getParent()); 5778 assert(NodeA && "Should only process reachable instructions"); 5779 assert(NodeB && "Should only process reachable instructions"); 5780 assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && 5781 "Different nodes should have different DFS numbers"); 5782 if (NodeA != NodeB) 5783 return NodeA->getDFSNumIn() < NodeB->getDFSNumIn(); 5784 return B->comesBefore(A); 5785 }); 5786 5787 for (Instruction *Inst : OrderedScalars) { 5788 if (!PrevInst) { 5789 PrevInst = Inst; 5790 continue; 5791 } 5792 5793 // Update LiveValues. 5794 LiveValues.erase(PrevInst); 5795 for (auto &J : PrevInst->operands()) { 5796 if (isa<Instruction>(&*J) && getTreeEntry(&*J)) 5797 LiveValues.insert(cast<Instruction>(&*J)); 5798 } 5799 5800 LLVM_DEBUG({ 5801 dbgs() << "SLP: #LV: " << LiveValues.size(); 5802 for (auto *X : LiveValues) 5803 dbgs() << " " << X->getName(); 5804 dbgs() << ", Looking at "; 5805 Inst->dump(); 5806 }); 5807 5808 // Now find the sequence of instructions between PrevInst and Inst. 5809 unsigned NumCalls = 0; 5810 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(), 5811 PrevInstIt = 5812 PrevInst->getIterator().getReverse(); 5813 while (InstIt != PrevInstIt) { 5814 if (PrevInstIt == PrevInst->getParent()->rend()) { 5815 PrevInstIt = Inst->getParent()->rbegin(); 5816 continue; 5817 } 5818 5819 // Debug information does not impact spill cost. 5820 if ((isa<CallInst>(&*PrevInstIt) && 5821 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) && 5822 &*PrevInstIt != PrevInst) 5823 NumCalls++; 5824 5825 ++PrevInstIt; 5826 } 5827 5828 if (NumCalls) { 5829 SmallVector<Type*, 4> V; 5830 for (auto *II : LiveValues) { 5831 auto *ScalarTy = II->getType(); 5832 if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy)) 5833 ScalarTy = VectorTy->getElementType(); 5834 V.push_back(FixedVectorType::get(ScalarTy, BundleWidth)); 5835 } 5836 Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V); 5837 } 5838 5839 PrevInst = Inst; 5840 } 5841 5842 return Cost; 5843 } 5844 5845 /// Check if two insertelement instructions are from the same buildvector. 5846 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU, 5847 InsertElementInst *V) { 5848 // Instructions must be from the same basic blocks. 5849 if (VU->getParent() != V->getParent()) 5850 return false; 5851 // Checks if 2 insertelements are from the same buildvector. 5852 if (VU->getType() != V->getType()) 5853 return false; 5854 // Multiple used inserts are separate nodes. 5855 if (!VU->hasOneUse() && !V->hasOneUse()) 5856 return false; 5857 auto *IE1 = VU; 5858 auto *IE2 = V; 5859 // Go through the vector operand of insertelement instructions trying to find 5860 // either VU as the original vector for IE2 or V as the original vector for 5861 // IE1. 5862 do { 5863 if (IE2 == VU || IE1 == V) 5864 return true; 5865 if (IE1) { 5866 if (IE1 != VU && !IE1->hasOneUse()) 5867 IE1 = nullptr; 5868 else 5869 IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0)); 5870 } 5871 if (IE2) { 5872 if (IE2 != V && !IE2->hasOneUse()) 5873 IE2 = nullptr; 5874 else 5875 IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0)); 5876 } 5877 } while (IE1 || IE2); 5878 return false; 5879 } 5880 5881 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) { 5882 InstructionCost Cost = 0; 5883 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size " 5884 << VectorizableTree.size() << ".\n"); 5885 5886 unsigned BundleWidth = VectorizableTree[0]->Scalars.size(); 5887 5888 for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) { 5889 TreeEntry &TE = *VectorizableTree[I].get(); 5890 5891 InstructionCost C = getEntryCost(&TE, VectorizedVals); 5892 Cost += C; 5893 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 5894 << " for bundle that starts with " << *TE.Scalars[0] 5895 << ".\n" 5896 << "SLP: Current total cost = " << Cost << "\n"); 5897 } 5898 5899 SmallPtrSet<Value *, 16> ExtractCostCalculated; 5900 InstructionCost ExtractCost = 0; 5901 SmallVector<unsigned> VF; 5902 SmallVector<SmallVector<int>> ShuffleMask; 5903 SmallVector<Value *> FirstUsers; 5904 SmallVector<APInt> DemandedElts; 5905 for (ExternalUser &EU : ExternalUses) { 5906 // We only add extract cost once for the same scalar. 5907 if (!isa_and_nonnull<InsertElementInst>(EU.User) && 5908 !ExtractCostCalculated.insert(EU.Scalar).second) 5909 continue; 5910 5911 // Uses by ephemeral values are free (because the ephemeral value will be 5912 // removed prior to code generation, and so the extraction will be 5913 // removed as well). 5914 if (EphValues.count(EU.User)) 5915 continue; 5916 5917 // No extract cost for vector "scalar" 5918 if (isa<FixedVectorType>(EU.Scalar->getType())) 5919 continue; 5920 5921 // Already counted the cost for external uses when tried to adjust the cost 5922 // for extractelements, no need to add it again. 5923 if (isa<ExtractElementInst>(EU.Scalar)) 5924 continue; 5925 5926 // If found user is an insertelement, do not calculate extract cost but try 5927 // to detect it as a final shuffled/identity match. 5928 if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) { 5929 if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) { 5930 Optional<unsigned> InsertIdx = getInsertIndex(VU); 5931 if (InsertIdx) { 5932 auto *It = find_if(FirstUsers, [VU](Value *V) { 5933 return areTwoInsertFromSameBuildVector(VU, 5934 cast<InsertElementInst>(V)); 5935 }); 5936 int VecId = -1; 5937 if (It == FirstUsers.end()) { 5938 VF.push_back(FTy->getNumElements()); 5939 ShuffleMask.emplace_back(VF.back(), UndefMaskElem); 5940 // Find the insertvector, vectorized in tree, if any. 5941 Value *Base = VU; 5942 while (isa<InsertElementInst>(Base)) { 5943 // Build the mask for the vectorized insertelement instructions. 5944 if (const TreeEntry *E = getTreeEntry(Base)) { 5945 VU = cast<InsertElementInst>(Base); 5946 do { 5947 int Idx = E->findLaneForValue(Base); 5948 ShuffleMask.back()[Idx] = Idx; 5949 Base = cast<InsertElementInst>(Base)->getOperand(0); 5950 } while (E == getTreeEntry(Base)); 5951 break; 5952 } 5953 Base = cast<InsertElementInst>(Base)->getOperand(0); 5954 } 5955 FirstUsers.push_back(VU); 5956 DemandedElts.push_back(APInt::getZero(VF.back())); 5957 VecId = FirstUsers.size() - 1; 5958 } else { 5959 VecId = std::distance(FirstUsers.begin(), It); 5960 } 5961 ShuffleMask[VecId][*InsertIdx] = EU.Lane; 5962 DemandedElts[VecId].setBit(*InsertIdx); 5963 continue; 5964 } 5965 } 5966 } 5967 5968 // If we plan to rewrite the tree in a smaller type, we will need to sign 5969 // extend the extracted value back to the original type. Here, we account 5970 // for the extract and the added cost of the sign extend if needed. 5971 auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth); 5972 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 5973 if (MinBWs.count(ScalarRoot)) { 5974 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 5975 auto Extend = 5976 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt; 5977 VecTy = FixedVectorType::get(MinTy, BundleWidth); 5978 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(), 5979 VecTy, EU.Lane); 5980 } else { 5981 ExtractCost += 5982 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane); 5983 } 5984 } 5985 5986 InstructionCost SpillCost = getSpillCost(); 5987 Cost += SpillCost + ExtractCost; 5988 if (FirstUsers.size() == 1) { 5989 int Limit = ShuffleMask.front().size() * 2; 5990 if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) && 5991 !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) { 5992 InstructionCost C = TTI->getShuffleCost( 5993 TTI::SK_PermuteSingleSrc, 5994 cast<FixedVectorType>(FirstUsers.front()->getType()), 5995 ShuffleMask.front()); 5996 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 5997 << " for final shuffle of insertelement external users " 5998 << *VectorizableTree.front()->Scalars.front() << ".\n" 5999 << "SLP: Current total cost = " << Cost << "\n"); 6000 Cost += C; 6001 } 6002 InstructionCost InsertCost = TTI->getScalarizationOverhead( 6003 cast<FixedVectorType>(FirstUsers.front()->getType()), 6004 DemandedElts.front(), /*Insert*/ true, /*Extract*/ false); 6005 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 6006 << " for insertelements gather.\n" 6007 << "SLP: Current total cost = " << Cost << "\n"); 6008 Cost -= InsertCost; 6009 } else if (FirstUsers.size() >= 2) { 6010 unsigned MaxVF = *std::max_element(VF.begin(), VF.end()); 6011 // Combined masks of the first 2 vectors. 6012 SmallVector<int> CombinedMask(MaxVF, UndefMaskElem); 6013 copy(ShuffleMask.front(), CombinedMask.begin()); 6014 APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF); 6015 auto *VecTy = FixedVectorType::get( 6016 cast<VectorType>(FirstUsers.front()->getType())->getElementType(), 6017 MaxVF); 6018 for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) { 6019 if (ShuffleMask[1][I] != UndefMaskElem) { 6020 CombinedMask[I] = ShuffleMask[1][I] + MaxVF; 6021 CombinedDemandedElts.setBit(I); 6022 } 6023 } 6024 InstructionCost C = 6025 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask); 6026 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6027 << " for final shuffle of vector node and external " 6028 "insertelement users " 6029 << *VectorizableTree.front()->Scalars.front() << ".\n" 6030 << "SLP: Current total cost = " << Cost << "\n"); 6031 Cost += C; 6032 InstructionCost InsertCost = TTI->getScalarizationOverhead( 6033 VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false); 6034 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 6035 << " for insertelements gather.\n" 6036 << "SLP: Current total cost = " << Cost << "\n"); 6037 Cost -= InsertCost; 6038 for (int I = 2, E = FirstUsers.size(); I < E; ++I) { 6039 // Other elements - permutation of 2 vectors (the initial one and the 6040 // next Ith incoming vector). 6041 unsigned VF = ShuffleMask[I].size(); 6042 for (unsigned Idx = 0; Idx < VF; ++Idx) { 6043 int Mask = ShuffleMask[I][Idx]; 6044 if (Mask != UndefMaskElem) 6045 CombinedMask[Idx] = MaxVF + Mask; 6046 else if (CombinedMask[Idx] != UndefMaskElem) 6047 CombinedMask[Idx] = Idx; 6048 } 6049 for (unsigned Idx = VF; Idx < MaxVF; ++Idx) 6050 if (CombinedMask[Idx] != UndefMaskElem) 6051 CombinedMask[Idx] = Idx; 6052 InstructionCost C = 6053 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask); 6054 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6055 << " for final shuffle of vector node and external " 6056 "insertelement users " 6057 << *VectorizableTree.front()->Scalars.front() << ".\n" 6058 << "SLP: Current total cost = " << Cost << "\n"); 6059 Cost += C; 6060 InstructionCost InsertCost = TTI->getScalarizationOverhead( 6061 cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I], 6062 /*Insert*/ true, /*Extract*/ false); 6063 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 6064 << " for insertelements gather.\n" 6065 << "SLP: Current total cost = " << Cost << "\n"); 6066 Cost -= InsertCost; 6067 } 6068 } 6069 6070 #ifndef NDEBUG 6071 SmallString<256> Str; 6072 { 6073 raw_svector_ostream OS(Str); 6074 OS << "SLP: Spill Cost = " << SpillCost << ".\n" 6075 << "SLP: Extract Cost = " << ExtractCost << ".\n" 6076 << "SLP: Total Cost = " << Cost << ".\n"; 6077 } 6078 LLVM_DEBUG(dbgs() << Str); 6079 if (ViewSLPTree) 6080 ViewGraph(this, "SLP" + F->getName(), false, Str); 6081 #endif 6082 6083 return Cost; 6084 } 6085 6086 Optional<TargetTransformInfo::ShuffleKind> 6087 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 6088 SmallVectorImpl<const TreeEntry *> &Entries) { 6089 // TODO: currently checking only for Scalars in the tree entry, need to count 6090 // reused elements too for better cost estimation. 6091 Mask.assign(TE->Scalars.size(), UndefMaskElem); 6092 Entries.clear(); 6093 // Build a lists of values to tree entries. 6094 DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs; 6095 for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) { 6096 if (EntryPtr.get() == TE) 6097 break; 6098 if (EntryPtr->State != TreeEntry::NeedToGather) 6099 continue; 6100 for (Value *V : EntryPtr->Scalars) 6101 ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get()); 6102 } 6103 // Find all tree entries used by the gathered values. If no common entries 6104 // found - not a shuffle. 6105 // Here we build a set of tree nodes for each gathered value and trying to 6106 // find the intersection between these sets. If we have at least one common 6107 // tree node for each gathered value - we have just a permutation of the 6108 // single vector. If we have 2 different sets, we're in situation where we 6109 // have a permutation of 2 input vectors. 6110 SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs; 6111 DenseMap<Value *, int> UsedValuesEntry; 6112 for (Value *V : TE->Scalars) { 6113 if (isa<UndefValue>(V)) 6114 continue; 6115 // Build a list of tree entries where V is used. 6116 SmallPtrSet<const TreeEntry *, 4> VToTEs; 6117 auto It = ValueToTEs.find(V); 6118 if (It != ValueToTEs.end()) 6119 VToTEs = It->second; 6120 if (const TreeEntry *VTE = getTreeEntry(V)) 6121 VToTEs.insert(VTE); 6122 if (VToTEs.empty()) 6123 return None; 6124 if (UsedTEs.empty()) { 6125 // The first iteration, just insert the list of nodes to vector. 6126 UsedTEs.push_back(VToTEs); 6127 } else { 6128 // Need to check if there are any previously used tree nodes which use V. 6129 // If there are no such nodes, consider that we have another one input 6130 // vector. 6131 SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs); 6132 unsigned Idx = 0; 6133 for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) { 6134 // Do we have a non-empty intersection of previously listed tree entries 6135 // and tree entries using current V? 6136 set_intersect(VToTEs, Set); 6137 if (!VToTEs.empty()) { 6138 // Yes, write the new subset and continue analysis for the next 6139 // scalar. 6140 Set.swap(VToTEs); 6141 break; 6142 } 6143 VToTEs = SavedVToTEs; 6144 ++Idx; 6145 } 6146 // No non-empty intersection found - need to add a second set of possible 6147 // source vectors. 6148 if (Idx == UsedTEs.size()) { 6149 // If the number of input vectors is greater than 2 - not a permutation, 6150 // fallback to the regular gather. 6151 if (UsedTEs.size() == 2) 6152 return None; 6153 UsedTEs.push_back(SavedVToTEs); 6154 Idx = UsedTEs.size() - 1; 6155 } 6156 UsedValuesEntry.try_emplace(V, Idx); 6157 } 6158 } 6159 6160 unsigned VF = 0; 6161 if (UsedTEs.size() == 1) { 6162 // Try to find the perfect match in another gather node at first. 6163 auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) { 6164 return EntryPtr->isSame(TE->Scalars); 6165 }); 6166 if (It != UsedTEs.front().end()) { 6167 Entries.push_back(*It); 6168 std::iota(Mask.begin(), Mask.end(), 0); 6169 return TargetTransformInfo::SK_PermuteSingleSrc; 6170 } 6171 // No perfect match, just shuffle, so choose the first tree node. 6172 Entries.push_back(*UsedTEs.front().begin()); 6173 } else { 6174 // Try to find nodes with the same vector factor. 6175 assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries."); 6176 DenseMap<int, const TreeEntry *> VFToTE; 6177 for (const TreeEntry *TE : UsedTEs.front()) 6178 VFToTE.try_emplace(TE->getVectorFactor(), TE); 6179 for (const TreeEntry *TE : UsedTEs.back()) { 6180 auto It = VFToTE.find(TE->getVectorFactor()); 6181 if (It != VFToTE.end()) { 6182 VF = It->first; 6183 Entries.push_back(It->second); 6184 Entries.push_back(TE); 6185 break; 6186 } 6187 } 6188 // No 2 source vectors with the same vector factor - give up and do regular 6189 // gather. 6190 if (Entries.empty()) 6191 return None; 6192 } 6193 6194 // Build a shuffle mask for better cost estimation and vector emission. 6195 for (int I = 0, E = TE->Scalars.size(); I < E; ++I) { 6196 Value *V = TE->Scalars[I]; 6197 if (isa<UndefValue>(V)) 6198 continue; 6199 unsigned Idx = UsedValuesEntry.lookup(V); 6200 const TreeEntry *VTE = Entries[Idx]; 6201 int FoundLane = VTE->findLaneForValue(V); 6202 Mask[I] = Idx * VF + FoundLane; 6203 // Extra check required by isSingleSourceMaskImpl function (called by 6204 // ShuffleVectorInst::isSingleSourceMask). 6205 if (Mask[I] >= 2 * E) 6206 return None; 6207 } 6208 switch (Entries.size()) { 6209 case 1: 6210 return TargetTransformInfo::SK_PermuteSingleSrc; 6211 case 2: 6212 return TargetTransformInfo::SK_PermuteTwoSrc; 6213 default: 6214 break; 6215 } 6216 return None; 6217 } 6218 6219 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty, 6220 const APInt &ShuffledIndices, 6221 bool NeedToShuffle) const { 6222 InstructionCost Cost = 6223 TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true, 6224 /*Extract*/ false); 6225 if (NeedToShuffle) 6226 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty); 6227 return Cost; 6228 } 6229 6230 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const { 6231 // Find the type of the operands in VL. 6232 Type *ScalarTy = VL[0]->getType(); 6233 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 6234 ScalarTy = SI->getValueOperand()->getType(); 6235 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 6236 bool DuplicateNonConst = false; 6237 // Find the cost of inserting/extracting values from the vector. 6238 // Check if the same elements are inserted several times and count them as 6239 // shuffle candidates. 6240 APInt ShuffledElements = APInt::getZero(VL.size()); 6241 DenseSet<Value *> UniqueElements; 6242 // Iterate in reverse order to consider insert elements with the high cost. 6243 for (unsigned I = VL.size(); I > 0; --I) { 6244 unsigned Idx = I - 1; 6245 // No need to shuffle duplicates for constants. 6246 if (isConstant(VL[Idx])) { 6247 ShuffledElements.setBit(Idx); 6248 continue; 6249 } 6250 if (!UniqueElements.insert(VL[Idx]).second) { 6251 DuplicateNonConst = true; 6252 ShuffledElements.setBit(Idx); 6253 } 6254 } 6255 return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst); 6256 } 6257 6258 // Perform operand reordering on the instructions in VL and return the reordered 6259 // operands in Left and Right. 6260 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 6261 SmallVectorImpl<Value *> &Left, 6262 SmallVectorImpl<Value *> &Right, 6263 const DataLayout &DL, 6264 ScalarEvolution &SE, 6265 const BoUpSLP &R) { 6266 if (VL.empty()) 6267 return; 6268 VLOperands Ops(VL, DL, SE, R); 6269 // Reorder the operands in place. 6270 Ops.reorder(); 6271 Left = Ops.getVL(0); 6272 Right = Ops.getVL(1); 6273 } 6274 6275 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) { 6276 // Get the basic block this bundle is in. All instructions in the bundle 6277 // should be in this block. 6278 auto *Front = E->getMainOp(); 6279 auto *BB = Front->getParent(); 6280 assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool { 6281 auto *I = cast<Instruction>(V); 6282 return !E->isOpcodeOrAlt(I) || I->getParent() == BB; 6283 })); 6284 6285 // The last instruction in the bundle in program order. 6286 Instruction *LastInst = nullptr; 6287 6288 // Find the last instruction. The common case should be that BB has been 6289 // scheduled, and the last instruction is VL.back(). So we start with 6290 // VL.back() and iterate over schedule data until we reach the end of the 6291 // bundle. The end of the bundle is marked by null ScheduleData. 6292 if (BlocksSchedules.count(BB)) { 6293 auto *Bundle = 6294 BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back())); 6295 if (Bundle && Bundle->isPartOfBundle()) 6296 for (; Bundle; Bundle = Bundle->NextInBundle) 6297 if (Bundle->OpValue == Bundle->Inst) 6298 LastInst = Bundle->Inst; 6299 } 6300 6301 // LastInst can still be null at this point if there's either not an entry 6302 // for BB in BlocksSchedules or there's no ScheduleData available for 6303 // VL.back(). This can be the case if buildTree_rec aborts for various 6304 // reasons (e.g., the maximum recursion depth is reached, the maximum region 6305 // size is reached, etc.). ScheduleData is initialized in the scheduling 6306 // "dry-run". 6307 // 6308 // If this happens, we can still find the last instruction by brute force. We 6309 // iterate forwards from Front (inclusive) until we either see all 6310 // instructions in the bundle or reach the end of the block. If Front is the 6311 // last instruction in program order, LastInst will be set to Front, and we 6312 // will visit all the remaining instructions in the block. 6313 // 6314 // One of the reasons we exit early from buildTree_rec is to place an upper 6315 // bound on compile-time. Thus, taking an additional compile-time hit here is 6316 // not ideal. However, this should be exceedingly rare since it requires that 6317 // we both exit early from buildTree_rec and that the bundle be out-of-order 6318 // (causing us to iterate all the way to the end of the block). 6319 if (!LastInst) { 6320 SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end()); 6321 for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) { 6322 if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I)) 6323 LastInst = &I; 6324 if (Bundle.empty()) 6325 break; 6326 } 6327 } 6328 assert(LastInst && "Failed to find last instruction in bundle"); 6329 6330 // Set the insertion point after the last instruction in the bundle. Set the 6331 // debug location to Front. 6332 Builder.SetInsertPoint(BB, ++LastInst->getIterator()); 6333 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 6334 } 6335 6336 Value *BoUpSLP::gather(ArrayRef<Value *> VL) { 6337 // List of instructions/lanes from current block and/or the blocks which are 6338 // part of the current loop. These instructions will be inserted at the end to 6339 // make it possible to optimize loops and hoist invariant instructions out of 6340 // the loops body with better chances for success. 6341 SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts; 6342 SmallSet<int, 4> PostponedIndices; 6343 Loop *L = LI->getLoopFor(Builder.GetInsertBlock()); 6344 auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) { 6345 SmallPtrSet<BasicBlock *, 4> Visited; 6346 while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second) 6347 InsertBB = InsertBB->getSinglePredecessor(); 6348 return InsertBB && InsertBB == InstBB; 6349 }; 6350 for (int I = 0, E = VL.size(); I < E; ++I) { 6351 if (auto *Inst = dyn_cast<Instruction>(VL[I])) 6352 if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) || 6353 getTreeEntry(Inst) || (L && (L->contains(Inst)))) && 6354 PostponedIndices.insert(I).second) 6355 PostponedInsts.emplace_back(Inst, I); 6356 } 6357 6358 auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) { 6359 Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos)); 6360 auto *InsElt = dyn_cast<InsertElementInst>(Vec); 6361 if (!InsElt) 6362 return Vec; 6363 GatherShuffleSeq.insert(InsElt); 6364 CSEBlocks.insert(InsElt->getParent()); 6365 // Add to our 'need-to-extract' list. 6366 if (TreeEntry *Entry = getTreeEntry(V)) { 6367 // Find which lane we need to extract. 6368 unsigned FoundLane = Entry->findLaneForValue(V); 6369 ExternalUses.emplace_back(V, InsElt, FoundLane); 6370 } 6371 return Vec; 6372 }; 6373 Value *Val0 = 6374 isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0]; 6375 FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size()); 6376 Value *Vec = PoisonValue::get(VecTy); 6377 SmallVector<int> NonConsts; 6378 // Insert constant values at first. 6379 for (int I = 0, E = VL.size(); I < E; ++I) { 6380 if (PostponedIndices.contains(I)) 6381 continue; 6382 if (!isConstant(VL[I])) { 6383 NonConsts.push_back(I); 6384 continue; 6385 } 6386 Vec = CreateInsertElement(Vec, VL[I], I); 6387 } 6388 // Insert non-constant values. 6389 for (int I : NonConsts) 6390 Vec = CreateInsertElement(Vec, VL[I], I); 6391 // Append instructions, which are/may be part of the loop, in the end to make 6392 // it possible to hoist non-loop-based instructions. 6393 for (const std::pair<Value *, unsigned> &Pair : PostponedInsts) 6394 Vec = CreateInsertElement(Vec, Pair.first, Pair.second); 6395 6396 return Vec; 6397 } 6398 6399 namespace { 6400 /// Merges shuffle masks and emits final shuffle instruction, if required. 6401 class ShuffleInstructionBuilder { 6402 IRBuilderBase &Builder; 6403 const unsigned VF = 0; 6404 bool IsFinalized = false; 6405 SmallVector<int, 4> Mask; 6406 /// Holds all of the instructions that we gathered. 6407 SetVector<Instruction *> &GatherShuffleSeq; 6408 /// A list of blocks that we are going to CSE. 6409 SetVector<BasicBlock *> &CSEBlocks; 6410 6411 public: 6412 ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF, 6413 SetVector<Instruction *> &GatherShuffleSeq, 6414 SetVector<BasicBlock *> &CSEBlocks) 6415 : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq), 6416 CSEBlocks(CSEBlocks) {} 6417 6418 /// Adds a mask, inverting it before applying. 6419 void addInversedMask(ArrayRef<unsigned> SubMask) { 6420 if (SubMask.empty()) 6421 return; 6422 SmallVector<int, 4> NewMask; 6423 inversePermutation(SubMask, NewMask); 6424 addMask(NewMask); 6425 } 6426 6427 /// Functions adds masks, merging them into single one. 6428 void addMask(ArrayRef<unsigned> SubMask) { 6429 SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end()); 6430 addMask(NewMask); 6431 } 6432 6433 void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); } 6434 6435 Value *finalize(Value *V) { 6436 IsFinalized = true; 6437 unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements(); 6438 if (VF == ValueVF && Mask.empty()) 6439 return V; 6440 SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem); 6441 std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0); 6442 addMask(NormalizedMask); 6443 6444 if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask)) 6445 return V; 6446 Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle"); 6447 if (auto *I = dyn_cast<Instruction>(Vec)) { 6448 GatherShuffleSeq.insert(I); 6449 CSEBlocks.insert(I->getParent()); 6450 } 6451 return Vec; 6452 } 6453 6454 ~ShuffleInstructionBuilder() { 6455 assert((IsFinalized || Mask.empty()) && 6456 "Shuffle construction must be finalized."); 6457 } 6458 }; 6459 } // namespace 6460 6461 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { 6462 unsigned VF = VL.size(); 6463 InstructionsState S = getSameOpcode(VL); 6464 if (S.getOpcode()) { 6465 if (TreeEntry *E = getTreeEntry(S.OpValue)) 6466 if (E->isSame(VL)) { 6467 Value *V = vectorizeTree(E); 6468 if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) { 6469 if (!E->ReuseShuffleIndices.empty()) { 6470 // Reshuffle to get only unique values. 6471 // If some of the scalars are duplicated in the vectorization tree 6472 // entry, we do not vectorize them but instead generate a mask for 6473 // the reuses. But if there are several users of the same entry, 6474 // they may have different vectorization factors. This is especially 6475 // important for PHI nodes. In this case, we need to adapt the 6476 // resulting instruction for the user vectorization factor and have 6477 // to reshuffle it again to take only unique elements of the vector. 6478 // Without this code the function incorrectly returns reduced vector 6479 // instruction with the same elements, not with the unique ones. 6480 6481 // block: 6482 // %phi = phi <2 x > { .., %entry} {%shuffle, %block} 6483 // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0> 6484 // ... (use %2) 6485 // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0} 6486 // br %block 6487 SmallVector<int> UniqueIdxs(VF, UndefMaskElem); 6488 SmallSet<int, 4> UsedIdxs; 6489 int Pos = 0; 6490 int Sz = VL.size(); 6491 for (int Idx : E->ReuseShuffleIndices) { 6492 if (Idx != Sz && Idx != UndefMaskElem && 6493 UsedIdxs.insert(Idx).second) 6494 UniqueIdxs[Idx] = Pos; 6495 ++Pos; 6496 } 6497 assert(VF >= UsedIdxs.size() && "Expected vectorization factor " 6498 "less than original vector size."); 6499 UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem); 6500 V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle"); 6501 } else { 6502 assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() && 6503 "Expected vectorization factor less " 6504 "than original vector size."); 6505 SmallVector<int> UniformMask(VF, 0); 6506 std::iota(UniformMask.begin(), UniformMask.end(), 0); 6507 V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle"); 6508 } 6509 if (auto *I = dyn_cast<Instruction>(V)) { 6510 GatherShuffleSeq.insert(I); 6511 CSEBlocks.insert(I->getParent()); 6512 } 6513 } 6514 return V; 6515 } 6516 } 6517 6518 // Check that every instruction appears once in this bundle. 6519 SmallVector<int> ReuseShuffleIndicies; 6520 SmallVector<Value *> UniqueValues; 6521 if (VL.size() > 2) { 6522 DenseMap<Value *, unsigned> UniquePositions; 6523 unsigned NumValues = 6524 std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) { 6525 return !isa<UndefValue>(V); 6526 }).base()); 6527 VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues)); 6528 int UniqueVals = 0; 6529 for (Value *V : VL.drop_back(VL.size() - VF)) { 6530 if (isa<UndefValue>(V)) { 6531 ReuseShuffleIndicies.emplace_back(UndefMaskElem); 6532 continue; 6533 } 6534 if (isConstant(V)) { 6535 ReuseShuffleIndicies.emplace_back(UniqueValues.size()); 6536 UniqueValues.emplace_back(V); 6537 continue; 6538 } 6539 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 6540 ReuseShuffleIndicies.emplace_back(Res.first->second); 6541 if (Res.second) { 6542 UniqueValues.emplace_back(V); 6543 ++UniqueVals; 6544 } 6545 } 6546 if (UniqueVals == 1 && UniqueValues.size() == 1) { 6547 // Emit pure splat vector. 6548 ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(), 6549 UndefMaskElem); 6550 } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) { 6551 ReuseShuffleIndicies.clear(); 6552 UniqueValues.clear(); 6553 UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues)); 6554 } 6555 UniqueValues.append(VF - UniqueValues.size(), 6556 PoisonValue::get(VL[0]->getType())); 6557 VL = UniqueValues; 6558 } 6559 6560 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 6561 CSEBlocks); 6562 Value *Vec = gather(VL); 6563 if (!ReuseShuffleIndicies.empty()) { 6564 ShuffleBuilder.addMask(ReuseShuffleIndicies); 6565 Vec = ShuffleBuilder.finalize(Vec); 6566 } 6567 return Vec; 6568 } 6569 6570 Value *BoUpSLP::vectorizeTree(TreeEntry *E) { 6571 IRBuilder<>::InsertPointGuard Guard(Builder); 6572 6573 if (E->VectorizedValue) { 6574 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"); 6575 return E->VectorizedValue; 6576 } 6577 6578 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 6579 unsigned VF = E->getVectorFactor(); 6580 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 6581 CSEBlocks); 6582 if (E->State == TreeEntry::NeedToGather) { 6583 if (E->getMainOp()) 6584 setInsertPointAfterBundle(E); 6585 Value *Vec; 6586 SmallVector<int> Mask; 6587 SmallVector<const TreeEntry *> Entries; 6588 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 6589 isGatherShuffledEntry(E, Mask, Entries); 6590 if (Shuffle.hasValue()) { 6591 assert((Entries.size() == 1 || Entries.size() == 2) && 6592 "Expected shuffle of 1 or 2 entries."); 6593 Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue, 6594 Entries.back()->VectorizedValue, Mask); 6595 if (auto *I = dyn_cast<Instruction>(Vec)) { 6596 GatherShuffleSeq.insert(I); 6597 CSEBlocks.insert(I->getParent()); 6598 } 6599 } else { 6600 Vec = gather(E->Scalars); 6601 } 6602 if (NeedToShuffleReuses) { 6603 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6604 Vec = ShuffleBuilder.finalize(Vec); 6605 } 6606 E->VectorizedValue = Vec; 6607 return Vec; 6608 } 6609 6610 assert((E->State == TreeEntry::Vectorize || 6611 E->State == TreeEntry::ScatterVectorize) && 6612 "Unhandled state"); 6613 unsigned ShuffleOrOp = 6614 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 6615 Instruction *VL0 = E->getMainOp(); 6616 Type *ScalarTy = VL0->getType(); 6617 if (auto *Store = dyn_cast<StoreInst>(VL0)) 6618 ScalarTy = Store->getValueOperand()->getType(); 6619 else if (auto *IE = dyn_cast<InsertElementInst>(VL0)) 6620 ScalarTy = IE->getOperand(1)->getType(); 6621 auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size()); 6622 switch (ShuffleOrOp) { 6623 case Instruction::PHI: { 6624 assert( 6625 (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) && 6626 "PHI reordering is free."); 6627 auto *PH = cast<PHINode>(VL0); 6628 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI()); 6629 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 6630 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); 6631 Value *V = NewPhi; 6632 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6633 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6634 V = ShuffleBuilder.finalize(V); 6635 6636 E->VectorizedValue = V; 6637 6638 // PHINodes may have multiple entries from the same block. We want to 6639 // visit every block once. 6640 SmallPtrSet<BasicBlock*, 4> VisitedBBs; 6641 6642 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 6643 ValueList Operands; 6644 BasicBlock *IBB = PH->getIncomingBlock(i); 6645 6646 if (!VisitedBBs.insert(IBB).second) { 6647 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB); 6648 continue; 6649 } 6650 6651 Builder.SetInsertPoint(IBB->getTerminator()); 6652 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 6653 Value *Vec = vectorizeTree(E->getOperand(i)); 6654 NewPhi->addIncoming(Vec, IBB); 6655 } 6656 6657 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && 6658 "Invalid number of incoming values"); 6659 return V; 6660 } 6661 6662 case Instruction::ExtractElement: { 6663 Value *V = E->getSingleOperand(0); 6664 Builder.SetInsertPoint(VL0); 6665 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6666 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6667 V = ShuffleBuilder.finalize(V); 6668 E->VectorizedValue = V; 6669 return V; 6670 } 6671 case Instruction::ExtractValue: { 6672 auto *LI = cast<LoadInst>(E->getSingleOperand(0)); 6673 Builder.SetInsertPoint(LI); 6674 auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace()); 6675 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy); 6676 LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign()); 6677 Value *NewV = propagateMetadata(V, E->Scalars); 6678 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6679 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6680 NewV = ShuffleBuilder.finalize(NewV); 6681 E->VectorizedValue = NewV; 6682 return NewV; 6683 } 6684 case Instruction::InsertElement: { 6685 assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique"); 6686 Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back())); 6687 Value *V = vectorizeTree(E->getOperand(1)); 6688 6689 // Create InsertVector shuffle if necessary 6690 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 6691 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); 6692 })); 6693 const unsigned NumElts = 6694 cast<FixedVectorType>(FirstInsert->getType())->getNumElements(); 6695 const unsigned NumScalars = E->Scalars.size(); 6696 6697 unsigned Offset = *getInsertIndex(VL0); 6698 assert(Offset < NumElts && "Failed to find vector index offset"); 6699 6700 // Create shuffle to resize vector 6701 SmallVector<int> Mask; 6702 if (!E->ReorderIndices.empty()) { 6703 inversePermutation(E->ReorderIndices, Mask); 6704 Mask.append(NumElts - NumScalars, UndefMaskElem); 6705 } else { 6706 Mask.assign(NumElts, UndefMaskElem); 6707 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 6708 } 6709 // Create InsertVector shuffle if necessary 6710 bool IsIdentity = true; 6711 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 6712 Mask.swap(PrevMask); 6713 for (unsigned I = 0; I < NumScalars; ++I) { 6714 Value *Scalar = E->Scalars[PrevMask[I]]; 6715 unsigned InsertIdx = *getInsertIndex(Scalar); 6716 IsIdentity &= InsertIdx - Offset == I; 6717 Mask[InsertIdx - Offset] = I; 6718 } 6719 if (!IsIdentity || NumElts != NumScalars) { 6720 V = Builder.CreateShuffleVector(V, Mask); 6721 if (auto *I = dyn_cast<Instruction>(V)) { 6722 GatherShuffleSeq.insert(I); 6723 CSEBlocks.insert(I->getParent()); 6724 } 6725 } 6726 6727 if ((!IsIdentity || Offset != 0 || 6728 !isUndefVector(FirstInsert->getOperand(0))) && 6729 NumElts != NumScalars) { 6730 SmallVector<int> InsertMask(NumElts); 6731 std::iota(InsertMask.begin(), InsertMask.end(), 0); 6732 for (unsigned I = 0; I < NumElts; I++) { 6733 if (Mask[I] != UndefMaskElem) 6734 InsertMask[Offset + I] = NumElts + I; 6735 } 6736 6737 V = Builder.CreateShuffleVector( 6738 FirstInsert->getOperand(0), V, InsertMask, 6739 cast<Instruction>(E->Scalars.back())->getName()); 6740 if (auto *I = dyn_cast<Instruction>(V)) { 6741 GatherShuffleSeq.insert(I); 6742 CSEBlocks.insert(I->getParent()); 6743 } 6744 } 6745 6746 ++NumVectorInstructions; 6747 E->VectorizedValue = V; 6748 return V; 6749 } 6750 case Instruction::ZExt: 6751 case Instruction::SExt: 6752 case Instruction::FPToUI: 6753 case Instruction::FPToSI: 6754 case Instruction::FPExt: 6755 case Instruction::PtrToInt: 6756 case Instruction::IntToPtr: 6757 case Instruction::SIToFP: 6758 case Instruction::UIToFP: 6759 case Instruction::Trunc: 6760 case Instruction::FPTrunc: 6761 case Instruction::BitCast: { 6762 setInsertPointAfterBundle(E); 6763 6764 Value *InVec = vectorizeTree(E->getOperand(0)); 6765 6766 if (E->VectorizedValue) { 6767 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6768 return E->VectorizedValue; 6769 } 6770 6771 auto *CI = cast<CastInst>(VL0); 6772 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); 6773 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6774 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6775 V = ShuffleBuilder.finalize(V); 6776 6777 E->VectorizedValue = V; 6778 ++NumVectorInstructions; 6779 return V; 6780 } 6781 case Instruction::FCmp: 6782 case Instruction::ICmp: { 6783 setInsertPointAfterBundle(E); 6784 6785 Value *L = vectorizeTree(E->getOperand(0)); 6786 Value *R = vectorizeTree(E->getOperand(1)); 6787 6788 if (E->VectorizedValue) { 6789 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6790 return E->VectorizedValue; 6791 } 6792 6793 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 6794 Value *V = Builder.CreateCmp(P0, L, R); 6795 propagateIRFlags(V, E->Scalars, VL0); 6796 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6797 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6798 V = ShuffleBuilder.finalize(V); 6799 6800 E->VectorizedValue = V; 6801 ++NumVectorInstructions; 6802 return V; 6803 } 6804 case Instruction::Select: { 6805 setInsertPointAfterBundle(E); 6806 6807 Value *Cond = vectorizeTree(E->getOperand(0)); 6808 Value *True = vectorizeTree(E->getOperand(1)); 6809 Value *False = vectorizeTree(E->getOperand(2)); 6810 6811 if (E->VectorizedValue) { 6812 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6813 return E->VectorizedValue; 6814 } 6815 6816 Value *V = Builder.CreateSelect(Cond, True, False); 6817 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6818 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6819 V = ShuffleBuilder.finalize(V); 6820 6821 E->VectorizedValue = V; 6822 ++NumVectorInstructions; 6823 return V; 6824 } 6825 case Instruction::FNeg: { 6826 setInsertPointAfterBundle(E); 6827 6828 Value *Op = vectorizeTree(E->getOperand(0)); 6829 6830 if (E->VectorizedValue) { 6831 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6832 return E->VectorizedValue; 6833 } 6834 6835 Value *V = Builder.CreateUnOp( 6836 static_cast<Instruction::UnaryOps>(E->getOpcode()), Op); 6837 propagateIRFlags(V, E->Scalars, VL0); 6838 if (auto *I = dyn_cast<Instruction>(V)) 6839 V = propagateMetadata(I, E->Scalars); 6840 6841 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6842 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6843 V = ShuffleBuilder.finalize(V); 6844 6845 E->VectorizedValue = V; 6846 ++NumVectorInstructions; 6847 6848 return V; 6849 } 6850 case Instruction::Add: 6851 case Instruction::FAdd: 6852 case Instruction::Sub: 6853 case Instruction::FSub: 6854 case Instruction::Mul: 6855 case Instruction::FMul: 6856 case Instruction::UDiv: 6857 case Instruction::SDiv: 6858 case Instruction::FDiv: 6859 case Instruction::URem: 6860 case Instruction::SRem: 6861 case Instruction::FRem: 6862 case Instruction::Shl: 6863 case Instruction::LShr: 6864 case Instruction::AShr: 6865 case Instruction::And: 6866 case Instruction::Or: 6867 case Instruction::Xor: { 6868 setInsertPointAfterBundle(E); 6869 6870 Value *LHS = vectorizeTree(E->getOperand(0)); 6871 Value *RHS = vectorizeTree(E->getOperand(1)); 6872 6873 if (E->VectorizedValue) { 6874 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6875 return E->VectorizedValue; 6876 } 6877 6878 Value *V = Builder.CreateBinOp( 6879 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, 6880 RHS); 6881 propagateIRFlags(V, E->Scalars, VL0); 6882 if (auto *I = dyn_cast<Instruction>(V)) 6883 V = propagateMetadata(I, E->Scalars); 6884 6885 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6886 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6887 V = ShuffleBuilder.finalize(V); 6888 6889 E->VectorizedValue = V; 6890 ++NumVectorInstructions; 6891 6892 return V; 6893 } 6894 case Instruction::Load: { 6895 // Loads are inserted at the head of the tree because we don't want to 6896 // sink them all the way down past store instructions. 6897 setInsertPointAfterBundle(E); 6898 6899 LoadInst *LI = cast<LoadInst>(VL0); 6900 Instruction *NewLI; 6901 unsigned AS = LI->getPointerAddressSpace(); 6902 Value *PO = LI->getPointerOperand(); 6903 if (E->State == TreeEntry::Vectorize) { 6904 6905 Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS)); 6906 6907 // The pointer operand uses an in-tree scalar so we add the new BitCast 6908 // to ExternalUses list to make sure that an extract will be generated 6909 // in the future. 6910 if (TreeEntry *Entry = getTreeEntry(PO)) { 6911 // Find which lane we need to extract. 6912 unsigned FoundLane = Entry->findLaneForValue(PO); 6913 ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane); 6914 } 6915 6916 NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign()); 6917 } else { 6918 assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state"); 6919 Value *VecPtr = vectorizeTree(E->getOperand(0)); 6920 // Use the minimum alignment of the gathered loads. 6921 Align CommonAlignment = LI->getAlign(); 6922 for (Value *V : E->Scalars) 6923 CommonAlignment = 6924 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 6925 NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment); 6926 } 6927 Value *V = propagateMetadata(NewLI, E->Scalars); 6928 6929 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6930 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6931 V = ShuffleBuilder.finalize(V); 6932 E->VectorizedValue = V; 6933 ++NumVectorInstructions; 6934 return V; 6935 } 6936 case Instruction::Store: { 6937 auto *SI = cast<StoreInst>(VL0); 6938 unsigned AS = SI->getPointerAddressSpace(); 6939 6940 setInsertPointAfterBundle(E); 6941 6942 Value *VecValue = vectorizeTree(E->getOperand(0)); 6943 ShuffleBuilder.addMask(E->ReorderIndices); 6944 VecValue = ShuffleBuilder.finalize(VecValue); 6945 6946 Value *ScalarPtr = SI->getPointerOperand(); 6947 Value *VecPtr = Builder.CreateBitCast( 6948 ScalarPtr, VecValue->getType()->getPointerTo(AS)); 6949 StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr, 6950 SI->getAlign()); 6951 6952 // The pointer operand uses an in-tree scalar, so add the new BitCast to 6953 // ExternalUses to make sure that an extract will be generated in the 6954 // future. 6955 if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) { 6956 // Find which lane we need to extract. 6957 unsigned FoundLane = Entry->findLaneForValue(ScalarPtr); 6958 ExternalUses.push_back( 6959 ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane)); 6960 } 6961 6962 Value *V = propagateMetadata(ST, E->Scalars); 6963 6964 E->VectorizedValue = V; 6965 ++NumVectorInstructions; 6966 return V; 6967 } 6968 case Instruction::GetElementPtr: { 6969 auto *GEP0 = cast<GetElementPtrInst>(VL0); 6970 setInsertPointAfterBundle(E); 6971 6972 Value *Op0 = vectorizeTree(E->getOperand(0)); 6973 6974 SmallVector<Value *> OpVecs; 6975 for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) { 6976 Value *OpVec = vectorizeTree(E->getOperand(J)); 6977 OpVecs.push_back(OpVec); 6978 } 6979 6980 Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs); 6981 if (Instruction *I = dyn_cast<Instruction>(V)) 6982 V = propagateMetadata(I, E->Scalars); 6983 6984 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6985 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6986 V = ShuffleBuilder.finalize(V); 6987 6988 E->VectorizedValue = V; 6989 ++NumVectorInstructions; 6990 6991 return V; 6992 } 6993 case Instruction::Call: { 6994 CallInst *CI = cast<CallInst>(VL0); 6995 setInsertPointAfterBundle(E); 6996 6997 Intrinsic::ID IID = Intrinsic::not_intrinsic; 6998 if (Function *FI = CI->getCalledFunction()) 6999 IID = FI->getIntrinsicID(); 7000 7001 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 7002 7003 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 7004 bool UseIntrinsic = ID != Intrinsic::not_intrinsic && 7005 VecCallCosts.first <= VecCallCosts.second; 7006 7007 Value *ScalarArg = nullptr; 7008 std::vector<Value *> OpVecs; 7009 SmallVector<Type *, 2> TysForDecl = 7010 {FixedVectorType::get(CI->getType(), E->Scalars.size())}; 7011 for (int j = 0, e = CI->arg_size(); j < e; ++j) { 7012 ValueList OpVL; 7013 // Some intrinsics have scalar arguments. This argument should not be 7014 // vectorized. 7015 if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) { 7016 CallInst *CEI = cast<CallInst>(VL0); 7017 ScalarArg = CEI->getArgOperand(j); 7018 OpVecs.push_back(CEI->getArgOperand(j)); 7019 if (hasVectorInstrinsicOverloadedScalarOpd(IID, j)) 7020 TysForDecl.push_back(ScalarArg->getType()); 7021 continue; 7022 } 7023 7024 Value *OpVec = vectorizeTree(E->getOperand(j)); 7025 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n"); 7026 OpVecs.push_back(OpVec); 7027 } 7028 7029 Function *CF; 7030 if (!UseIntrinsic) { 7031 VFShape Shape = 7032 VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 7033 VecTy->getNumElements())), 7034 false /*HasGlobalPred*/); 7035 CF = VFDatabase(*CI).getVectorizedFunction(Shape); 7036 } else { 7037 CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl); 7038 } 7039 7040 SmallVector<OperandBundleDef, 1> OpBundles; 7041 CI->getOperandBundlesAsDefs(OpBundles); 7042 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles); 7043 7044 // The scalar argument uses an in-tree scalar so we add the new vectorized 7045 // call to ExternalUses list to make sure that an extract will be 7046 // generated in the future. 7047 if (ScalarArg) { 7048 if (TreeEntry *Entry = getTreeEntry(ScalarArg)) { 7049 // Find which lane we need to extract. 7050 unsigned FoundLane = Entry->findLaneForValue(ScalarArg); 7051 ExternalUses.push_back( 7052 ExternalUser(ScalarArg, cast<User>(V), FoundLane)); 7053 } 7054 } 7055 7056 propagateIRFlags(V, E->Scalars, VL0); 7057 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7058 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7059 V = ShuffleBuilder.finalize(V); 7060 7061 E->VectorizedValue = V; 7062 ++NumVectorInstructions; 7063 return V; 7064 } 7065 case Instruction::ShuffleVector: { 7066 assert(E->isAltShuffle() && 7067 ((Instruction::isBinaryOp(E->getOpcode()) && 7068 Instruction::isBinaryOp(E->getAltOpcode())) || 7069 (Instruction::isCast(E->getOpcode()) && 7070 Instruction::isCast(E->getAltOpcode())) || 7071 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 7072 "Invalid Shuffle Vector Operand"); 7073 7074 Value *LHS = nullptr, *RHS = nullptr; 7075 if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) { 7076 setInsertPointAfterBundle(E); 7077 LHS = vectorizeTree(E->getOperand(0)); 7078 RHS = vectorizeTree(E->getOperand(1)); 7079 } else { 7080 setInsertPointAfterBundle(E); 7081 LHS = vectorizeTree(E->getOperand(0)); 7082 } 7083 7084 if (E->VectorizedValue) { 7085 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7086 return E->VectorizedValue; 7087 } 7088 7089 Value *V0, *V1; 7090 if (Instruction::isBinaryOp(E->getOpcode())) { 7091 V0 = Builder.CreateBinOp( 7092 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS); 7093 V1 = Builder.CreateBinOp( 7094 static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS); 7095 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 7096 V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS); 7097 auto *AltCI = cast<CmpInst>(E->getAltOp()); 7098 CmpInst::Predicate AltPred = AltCI->getPredicate(); 7099 V1 = Builder.CreateCmp(AltPred, LHS, RHS); 7100 } else { 7101 V0 = Builder.CreateCast( 7102 static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy); 7103 V1 = Builder.CreateCast( 7104 static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy); 7105 } 7106 // Add V0 and V1 to later analysis to try to find and remove matching 7107 // instruction, if any. 7108 for (Value *V : {V0, V1}) { 7109 if (auto *I = dyn_cast<Instruction>(V)) { 7110 GatherShuffleSeq.insert(I); 7111 CSEBlocks.insert(I->getParent()); 7112 } 7113 } 7114 7115 // Create shuffle to take alternate operations from the vector. 7116 // Also, gather up main and alt scalar ops to propagate IR flags to 7117 // each vector operation. 7118 ValueList OpScalars, AltScalars; 7119 SmallVector<int> Mask; 7120 buildShuffleEntryMask( 7121 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 7122 [E](Instruction *I) { 7123 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 7124 return isAlternateInstruction(I, E->getMainOp(), E->getAltOp()); 7125 }, 7126 Mask, &OpScalars, &AltScalars); 7127 7128 propagateIRFlags(V0, OpScalars); 7129 propagateIRFlags(V1, AltScalars); 7130 7131 Value *V = Builder.CreateShuffleVector(V0, V1, Mask); 7132 if (auto *I = dyn_cast<Instruction>(V)) { 7133 V = propagateMetadata(I, E->Scalars); 7134 GatherShuffleSeq.insert(I); 7135 CSEBlocks.insert(I->getParent()); 7136 } 7137 V = ShuffleBuilder.finalize(V); 7138 7139 E->VectorizedValue = V; 7140 ++NumVectorInstructions; 7141 7142 return V; 7143 } 7144 default: 7145 llvm_unreachable("unknown inst"); 7146 } 7147 return nullptr; 7148 } 7149 7150 Value *BoUpSLP::vectorizeTree() { 7151 ExtraValueToDebugLocsMap ExternallyUsedValues; 7152 return vectorizeTree(ExternallyUsedValues); 7153 } 7154 7155 Value * 7156 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) { 7157 // All blocks must be scheduled before any instructions are inserted. 7158 for (auto &BSIter : BlocksSchedules) { 7159 scheduleBlock(BSIter.second.get()); 7160 } 7161 7162 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7163 auto *VectorRoot = vectorizeTree(VectorizableTree[0].get()); 7164 7165 // If the vectorized tree can be rewritten in a smaller type, we truncate the 7166 // vectorized root. InstCombine will then rewrite the entire expression. We 7167 // sign extend the extracted values below. 7168 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 7169 if (MinBWs.count(ScalarRoot)) { 7170 if (auto *I = dyn_cast<Instruction>(VectorRoot)) { 7171 // If current instr is a phi and not the last phi, insert it after the 7172 // last phi node. 7173 if (isa<PHINode>(I)) 7174 Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt()); 7175 else 7176 Builder.SetInsertPoint(&*++BasicBlock::iterator(I)); 7177 } 7178 auto BundleWidth = VectorizableTree[0]->Scalars.size(); 7179 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 7180 auto *VecTy = FixedVectorType::get(MinTy, BundleWidth); 7181 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy); 7182 VectorizableTree[0]->VectorizedValue = Trunc; 7183 } 7184 7185 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() 7186 << " values .\n"); 7187 7188 // Extract all of the elements with the external uses. 7189 for (const auto &ExternalUse : ExternalUses) { 7190 Value *Scalar = ExternalUse.Scalar; 7191 llvm::User *User = ExternalUse.User; 7192 7193 // Skip users that we already RAUW. This happens when one instruction 7194 // has multiple uses of the same value. 7195 if (User && !is_contained(Scalar->users(), User)) 7196 continue; 7197 TreeEntry *E = getTreeEntry(Scalar); 7198 assert(E && "Invalid scalar"); 7199 assert(E->State != TreeEntry::NeedToGather && 7200 "Extracting from a gather list"); 7201 7202 Value *Vec = E->VectorizedValue; 7203 assert(Vec && "Can't find vectorizable value"); 7204 7205 Value *Lane = Builder.getInt32(ExternalUse.Lane); 7206 auto ExtractAndExtendIfNeeded = [&](Value *Vec) { 7207 if (Scalar->getType() != Vec->getType()) { 7208 Value *Ex; 7209 // "Reuse" the existing extract to improve final codegen. 7210 if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) { 7211 Ex = Builder.CreateExtractElement(ES->getOperand(0), 7212 ES->getOperand(1)); 7213 } else { 7214 Ex = Builder.CreateExtractElement(Vec, Lane); 7215 } 7216 // If necessary, sign-extend or zero-extend ScalarRoot 7217 // to the larger type. 7218 if (!MinBWs.count(ScalarRoot)) 7219 return Ex; 7220 if (MinBWs[ScalarRoot].second) 7221 return Builder.CreateSExt(Ex, Scalar->getType()); 7222 return Builder.CreateZExt(Ex, Scalar->getType()); 7223 } 7224 assert(isa<FixedVectorType>(Scalar->getType()) && 7225 isa<InsertElementInst>(Scalar) && 7226 "In-tree scalar of vector type is not insertelement?"); 7227 return Vec; 7228 }; 7229 // If User == nullptr, the Scalar is used as extra arg. Generate 7230 // ExtractElement instruction and update the record for this scalar in 7231 // ExternallyUsedValues. 7232 if (!User) { 7233 assert(ExternallyUsedValues.count(Scalar) && 7234 "Scalar with nullptr as an external user must be registered in " 7235 "ExternallyUsedValues map"); 7236 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 7237 Builder.SetInsertPoint(VecI->getParent(), 7238 std::next(VecI->getIterator())); 7239 } else { 7240 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7241 } 7242 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7243 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent()); 7244 auto &NewInstLocs = ExternallyUsedValues[NewInst]; 7245 auto It = ExternallyUsedValues.find(Scalar); 7246 assert(It != ExternallyUsedValues.end() && 7247 "Externally used scalar is not found in ExternallyUsedValues"); 7248 NewInstLocs.append(It->second); 7249 ExternallyUsedValues.erase(Scalar); 7250 // Required to update internally referenced instructions. 7251 Scalar->replaceAllUsesWith(NewInst); 7252 continue; 7253 } 7254 7255 // Generate extracts for out-of-tree users. 7256 // Find the insertion point for the extractelement lane. 7257 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 7258 if (PHINode *PH = dyn_cast<PHINode>(User)) { 7259 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { 7260 if (PH->getIncomingValue(i) == Scalar) { 7261 Instruction *IncomingTerminator = 7262 PH->getIncomingBlock(i)->getTerminator(); 7263 if (isa<CatchSwitchInst>(IncomingTerminator)) { 7264 Builder.SetInsertPoint(VecI->getParent(), 7265 std::next(VecI->getIterator())); 7266 } else { 7267 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator()); 7268 } 7269 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7270 CSEBlocks.insert(PH->getIncomingBlock(i)); 7271 PH->setOperand(i, NewInst); 7272 } 7273 } 7274 } else { 7275 Builder.SetInsertPoint(cast<Instruction>(User)); 7276 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7277 CSEBlocks.insert(cast<Instruction>(User)->getParent()); 7278 User->replaceUsesOfWith(Scalar, NewInst); 7279 } 7280 } else { 7281 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7282 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7283 CSEBlocks.insert(&F->getEntryBlock()); 7284 User->replaceUsesOfWith(Scalar, NewInst); 7285 } 7286 7287 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n"); 7288 } 7289 7290 // For each vectorized value: 7291 for (auto &TEPtr : VectorizableTree) { 7292 TreeEntry *Entry = TEPtr.get(); 7293 7294 // No need to handle users of gathered values. 7295 if (Entry->State == TreeEntry::NeedToGather) 7296 continue; 7297 7298 assert(Entry->VectorizedValue && "Can't find vectorizable value"); 7299 7300 // For each lane: 7301 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 7302 Value *Scalar = Entry->Scalars[Lane]; 7303 7304 #ifndef NDEBUG 7305 Type *Ty = Scalar->getType(); 7306 if (!Ty->isVoidTy()) { 7307 for (User *U : Scalar->users()) { 7308 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n"); 7309 7310 // It is legal to delete users in the ignorelist. 7311 assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) || 7312 (isa_and_nonnull<Instruction>(U) && 7313 isDeleted(cast<Instruction>(U)))) && 7314 "Deleting out-of-tree value"); 7315 } 7316 } 7317 #endif 7318 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n"); 7319 eraseInstruction(cast<Instruction>(Scalar)); 7320 } 7321 } 7322 7323 Builder.ClearInsertionPoint(); 7324 InstrElementSize.clear(); 7325 7326 return VectorizableTree[0]->VectorizedValue; 7327 } 7328 7329 void BoUpSLP::optimizeGatherSequence() { 7330 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size() 7331 << " gather sequences instructions.\n"); 7332 // LICM InsertElementInst sequences. 7333 for (Instruction *I : GatherShuffleSeq) { 7334 if (isDeleted(I)) 7335 continue; 7336 7337 // Check if this block is inside a loop. 7338 Loop *L = LI->getLoopFor(I->getParent()); 7339 if (!L) 7340 continue; 7341 7342 // Check if it has a preheader. 7343 BasicBlock *PreHeader = L->getLoopPreheader(); 7344 if (!PreHeader) 7345 continue; 7346 7347 // If the vector or the element that we insert into it are 7348 // instructions that are defined in this basic block then we can't 7349 // hoist this instruction. 7350 if (any_of(I->operands(), [L](Value *V) { 7351 auto *OpI = dyn_cast<Instruction>(V); 7352 return OpI && L->contains(OpI); 7353 })) 7354 continue; 7355 7356 // We can hoist this instruction. Move it to the pre-header. 7357 I->moveBefore(PreHeader->getTerminator()); 7358 } 7359 7360 // Make a list of all reachable blocks in our CSE queue. 7361 SmallVector<const DomTreeNode *, 8> CSEWorkList; 7362 CSEWorkList.reserve(CSEBlocks.size()); 7363 for (BasicBlock *BB : CSEBlocks) 7364 if (DomTreeNode *N = DT->getNode(BB)) { 7365 assert(DT->isReachableFromEntry(N)); 7366 CSEWorkList.push_back(N); 7367 } 7368 7369 // Sort blocks by domination. This ensures we visit a block after all blocks 7370 // dominating it are visited. 7371 llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) { 7372 assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && 7373 "Different nodes should have different DFS numbers"); 7374 return A->getDFSNumIn() < B->getDFSNumIn(); 7375 }); 7376 7377 // Less defined shuffles can be replaced by the more defined copies. 7378 // Between two shuffles one is less defined if it has the same vector operands 7379 // and its mask indeces are the same as in the first one or undefs. E.g. 7380 // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0, 7381 // poison, <0, 0, 0, 0>. 7382 auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2, 7383 SmallVectorImpl<int> &NewMask) { 7384 if (I1->getType() != I2->getType()) 7385 return false; 7386 auto *SI1 = dyn_cast<ShuffleVectorInst>(I1); 7387 auto *SI2 = dyn_cast<ShuffleVectorInst>(I2); 7388 if (!SI1 || !SI2) 7389 return I1->isIdenticalTo(I2); 7390 if (SI1->isIdenticalTo(SI2)) 7391 return true; 7392 for (int I = 0, E = SI1->getNumOperands(); I < E; ++I) 7393 if (SI1->getOperand(I) != SI2->getOperand(I)) 7394 return false; 7395 // Check if the second instruction is more defined than the first one. 7396 NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end()); 7397 ArrayRef<int> SM1 = SI1->getShuffleMask(); 7398 // Count trailing undefs in the mask to check the final number of used 7399 // registers. 7400 unsigned LastUndefsCnt = 0; 7401 for (int I = 0, E = NewMask.size(); I < E; ++I) { 7402 if (SM1[I] == UndefMaskElem) 7403 ++LastUndefsCnt; 7404 else 7405 LastUndefsCnt = 0; 7406 if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem && 7407 NewMask[I] != SM1[I]) 7408 return false; 7409 if (NewMask[I] == UndefMaskElem) 7410 NewMask[I] = SM1[I]; 7411 } 7412 // Check if the last undefs actually change the final number of used vector 7413 // registers. 7414 return SM1.size() - LastUndefsCnt > 1 && 7415 TTI->getNumberOfParts(SI1->getType()) == 7416 TTI->getNumberOfParts( 7417 FixedVectorType::get(SI1->getType()->getElementType(), 7418 SM1.size() - LastUndefsCnt)); 7419 }; 7420 // Perform O(N^2) search over the gather/shuffle sequences and merge identical 7421 // instructions. TODO: We can further optimize this scan if we split the 7422 // instructions into different buckets based on the insert lane. 7423 SmallVector<Instruction *, 16> Visited; 7424 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) { 7425 assert(*I && 7426 (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && 7427 "Worklist not sorted properly!"); 7428 BasicBlock *BB = (*I)->getBlock(); 7429 // For all instructions in blocks containing gather sequences: 7430 for (Instruction &In : llvm::make_early_inc_range(*BB)) { 7431 if (isDeleted(&In)) 7432 continue; 7433 if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) && 7434 !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In)) 7435 continue; 7436 7437 // Check if we can replace this instruction with any of the 7438 // visited instructions. 7439 bool Replaced = false; 7440 for (Instruction *&V : Visited) { 7441 SmallVector<int> NewMask; 7442 if (IsIdenticalOrLessDefined(&In, V, NewMask) && 7443 DT->dominates(V->getParent(), In.getParent())) { 7444 In.replaceAllUsesWith(V); 7445 eraseInstruction(&In); 7446 if (auto *SI = dyn_cast<ShuffleVectorInst>(V)) 7447 if (!NewMask.empty()) 7448 SI->setShuffleMask(NewMask); 7449 Replaced = true; 7450 break; 7451 } 7452 if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) && 7453 GatherShuffleSeq.contains(V) && 7454 IsIdenticalOrLessDefined(V, &In, NewMask) && 7455 DT->dominates(In.getParent(), V->getParent())) { 7456 In.moveAfter(V); 7457 V->replaceAllUsesWith(&In); 7458 eraseInstruction(V); 7459 if (auto *SI = dyn_cast<ShuffleVectorInst>(&In)) 7460 if (!NewMask.empty()) 7461 SI->setShuffleMask(NewMask); 7462 V = &In; 7463 Replaced = true; 7464 break; 7465 } 7466 } 7467 if (!Replaced) { 7468 assert(!is_contained(Visited, &In)); 7469 Visited.push_back(&In); 7470 } 7471 } 7472 } 7473 CSEBlocks.clear(); 7474 GatherShuffleSeq.clear(); 7475 } 7476 7477 BoUpSLP::ScheduleData * 7478 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) { 7479 ScheduleData *Bundle = nullptr; 7480 ScheduleData *PrevInBundle = nullptr; 7481 for (Value *V : VL) { 7482 ScheduleData *BundleMember = getScheduleData(V); 7483 assert(BundleMember && 7484 "no ScheduleData for bundle member " 7485 "(maybe not in same basic block)"); 7486 assert(BundleMember->isSchedulingEntity() && 7487 "bundle member already part of other bundle"); 7488 if (PrevInBundle) { 7489 PrevInBundle->NextInBundle = BundleMember; 7490 } else { 7491 Bundle = BundleMember; 7492 } 7493 7494 // Group the instructions to a bundle. 7495 BundleMember->FirstInBundle = Bundle; 7496 PrevInBundle = BundleMember; 7497 } 7498 assert(Bundle && "Failed to find schedule bundle"); 7499 return Bundle; 7500 } 7501 7502 // Groups the instructions to a bundle (which is then a single scheduling entity) 7503 // and schedules instructions until the bundle gets ready. 7504 Optional<BoUpSLP::ScheduleData *> 7505 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 7506 const InstructionsState &S) { 7507 // No need to schedule PHIs, insertelement, extractelement and extractvalue 7508 // instructions. 7509 if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue)) 7510 return nullptr; 7511 7512 // Initialize the instruction bundle. 7513 Instruction *OldScheduleEnd = ScheduleEnd; 7514 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n"); 7515 7516 auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule, 7517 ScheduleData *Bundle) { 7518 // The scheduling region got new instructions at the lower end (or it is a 7519 // new region for the first bundle). This makes it necessary to 7520 // recalculate all dependencies. 7521 // It is seldom that this needs to be done a second time after adding the 7522 // initial bundle to the region. 7523 if (ScheduleEnd != OldScheduleEnd) { 7524 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) 7525 doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); }); 7526 ReSchedule = true; 7527 } 7528 if (Bundle) { 7529 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle 7530 << " in block " << BB->getName() << "\n"); 7531 calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP); 7532 } 7533 7534 if (ReSchedule) { 7535 resetSchedule(); 7536 initialFillReadyList(ReadyInsts); 7537 } 7538 7539 // Now try to schedule the new bundle or (if no bundle) just calculate 7540 // dependencies. As soon as the bundle is "ready" it means that there are no 7541 // cyclic dependencies and we can schedule it. Note that's important that we 7542 // don't "schedule" the bundle yet (see cancelScheduling). 7543 while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) && 7544 !ReadyInsts.empty()) { 7545 ScheduleData *Picked = ReadyInsts.pop_back_val(); 7546 assert(Picked->isSchedulingEntity() && Picked->isReady() && 7547 "must be ready to schedule"); 7548 schedule(Picked, ReadyInsts); 7549 } 7550 }; 7551 7552 // Make sure that the scheduling region contains all 7553 // instructions of the bundle. 7554 for (Value *V : VL) { 7555 if (!extendSchedulingRegion(V, S)) { 7556 // If the scheduling region got new instructions at the lower end (or it 7557 // is a new region for the first bundle). This makes it necessary to 7558 // recalculate all dependencies. 7559 // Otherwise the compiler may crash trying to incorrectly calculate 7560 // dependencies and emit instruction in the wrong order at the actual 7561 // scheduling. 7562 TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr); 7563 return None; 7564 } 7565 } 7566 7567 bool ReSchedule = false; 7568 for (Value *V : VL) { 7569 ScheduleData *BundleMember = getScheduleData(V); 7570 assert(BundleMember && 7571 "no ScheduleData for bundle member (maybe not in same basic block)"); 7572 7573 // Make sure we don't leave the pieces of the bundle in the ready list when 7574 // whole bundle might not be ready. 7575 ReadyInsts.remove(BundleMember); 7576 7577 if (!BundleMember->IsScheduled) 7578 continue; 7579 // A bundle member was scheduled as single instruction before and now 7580 // needs to be scheduled as part of the bundle. We just get rid of the 7581 // existing schedule. 7582 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember 7583 << " was already scheduled\n"); 7584 ReSchedule = true; 7585 } 7586 7587 auto *Bundle = buildBundle(VL); 7588 TryScheduleBundleImpl(ReSchedule, Bundle); 7589 if (!Bundle->isReady()) { 7590 cancelScheduling(VL, S.OpValue); 7591 return None; 7592 } 7593 return Bundle; 7594 } 7595 7596 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL, 7597 Value *OpValue) { 7598 if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue)) 7599 return; 7600 7601 ScheduleData *Bundle = getScheduleData(OpValue); 7602 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n"); 7603 assert(!Bundle->IsScheduled && 7604 "Can't cancel bundle which is already scheduled"); 7605 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() && 7606 "tried to unbundle something which is not a bundle"); 7607 7608 // Remove the bundle from the ready list. 7609 if (Bundle->isReady()) 7610 ReadyInsts.remove(Bundle); 7611 7612 // Un-bundle: make single instructions out of the bundle. 7613 ScheduleData *BundleMember = Bundle; 7614 while (BundleMember) { 7615 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links"); 7616 BundleMember->FirstInBundle = BundleMember; 7617 ScheduleData *Next = BundleMember->NextInBundle; 7618 BundleMember->NextInBundle = nullptr; 7619 if (BundleMember->unscheduledDepsInBundle() == 0) { 7620 ReadyInsts.insert(BundleMember); 7621 } 7622 BundleMember = Next; 7623 } 7624 } 7625 7626 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() { 7627 // Allocate a new ScheduleData for the instruction. 7628 if (ChunkPos >= ChunkSize) { 7629 ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize)); 7630 ChunkPos = 0; 7631 } 7632 return &(ScheduleDataChunks.back()[ChunkPos++]); 7633 } 7634 7635 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V, 7636 const InstructionsState &S) { 7637 if (getScheduleData(V, isOneOf(S, V))) 7638 return true; 7639 Instruction *I = dyn_cast<Instruction>(V); 7640 assert(I && "bundle member must be an instruction"); 7641 assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && 7642 "phi nodes/insertelements/extractelements/extractvalues don't need to " 7643 "be scheduled"); 7644 auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool { 7645 ScheduleData *ISD = getScheduleData(I); 7646 if (!ISD) 7647 return false; 7648 assert(isInSchedulingRegion(ISD) && 7649 "ScheduleData not in scheduling region"); 7650 ScheduleData *SD = allocateScheduleDataChunks(); 7651 SD->Inst = I; 7652 SD->init(SchedulingRegionID, S.OpValue); 7653 ExtraScheduleDataMap[I][S.OpValue] = SD; 7654 return true; 7655 }; 7656 if (CheckSheduleForI(I)) 7657 return true; 7658 if (!ScheduleStart) { 7659 // It's the first instruction in the new region. 7660 initScheduleData(I, I->getNextNode(), nullptr, nullptr); 7661 ScheduleStart = I; 7662 ScheduleEnd = I->getNextNode(); 7663 if (isOneOf(S, I) != I) 7664 CheckSheduleForI(I); 7665 assert(ScheduleEnd && "tried to vectorize a terminator?"); 7666 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n"); 7667 return true; 7668 } 7669 // Search up and down at the same time, because we don't know if the new 7670 // instruction is above or below the existing scheduling region. 7671 BasicBlock::reverse_iterator UpIter = 7672 ++ScheduleStart->getIterator().getReverse(); 7673 BasicBlock::reverse_iterator UpperEnd = BB->rend(); 7674 BasicBlock::iterator DownIter = ScheduleEnd->getIterator(); 7675 BasicBlock::iterator LowerEnd = BB->end(); 7676 while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I && 7677 &*DownIter != I) { 7678 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) { 7679 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n"); 7680 return false; 7681 } 7682 7683 ++UpIter; 7684 ++DownIter; 7685 } 7686 if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) { 7687 assert(I->getParent() == ScheduleStart->getParent() && 7688 "Instruction is in wrong basic block."); 7689 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion); 7690 ScheduleStart = I; 7691 if (isOneOf(S, I) != I) 7692 CheckSheduleForI(I); 7693 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I 7694 << "\n"); 7695 return true; 7696 } 7697 assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && 7698 "Expected to reach top of the basic block or instruction down the " 7699 "lower end."); 7700 assert(I->getParent() == ScheduleEnd->getParent() && 7701 "Instruction is in wrong basic block."); 7702 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion, 7703 nullptr); 7704 ScheduleEnd = I->getNextNode(); 7705 if (isOneOf(S, I) != I) 7706 CheckSheduleForI(I); 7707 assert(ScheduleEnd && "tried to vectorize a terminator?"); 7708 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n"); 7709 return true; 7710 } 7711 7712 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI, 7713 Instruction *ToI, 7714 ScheduleData *PrevLoadStore, 7715 ScheduleData *NextLoadStore) { 7716 ScheduleData *CurrentLoadStore = PrevLoadStore; 7717 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) { 7718 ScheduleData *SD = ScheduleDataMap[I]; 7719 if (!SD) { 7720 SD = allocateScheduleDataChunks(); 7721 ScheduleDataMap[I] = SD; 7722 SD->Inst = I; 7723 } 7724 assert(!isInSchedulingRegion(SD) && 7725 "new ScheduleData already in scheduling region"); 7726 SD->init(SchedulingRegionID, I); 7727 7728 if (I->mayReadOrWriteMemory() && 7729 (!isa<IntrinsicInst>(I) || 7730 (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect && 7731 cast<IntrinsicInst>(I)->getIntrinsicID() != 7732 Intrinsic::pseudoprobe))) { 7733 // Update the linked list of memory accessing instructions. 7734 if (CurrentLoadStore) { 7735 CurrentLoadStore->NextLoadStore = SD; 7736 } else { 7737 FirstLoadStoreInRegion = SD; 7738 } 7739 CurrentLoadStore = SD; 7740 } 7741 } 7742 if (NextLoadStore) { 7743 if (CurrentLoadStore) 7744 CurrentLoadStore->NextLoadStore = NextLoadStore; 7745 } else { 7746 LastLoadStoreInRegion = CurrentLoadStore; 7747 } 7748 } 7749 7750 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD, 7751 bool InsertInReadyList, 7752 BoUpSLP *SLP) { 7753 assert(SD->isSchedulingEntity()); 7754 7755 SmallVector<ScheduleData *, 10> WorkList; 7756 WorkList.push_back(SD); 7757 7758 while (!WorkList.empty()) { 7759 ScheduleData *SD = WorkList.pop_back_val(); 7760 for (ScheduleData *BundleMember = SD; BundleMember; 7761 BundleMember = BundleMember->NextInBundle) { 7762 assert(isInSchedulingRegion(BundleMember)); 7763 if (BundleMember->hasValidDependencies()) 7764 continue; 7765 7766 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember 7767 << "\n"); 7768 BundleMember->Dependencies = 0; 7769 BundleMember->resetUnscheduledDeps(); 7770 7771 // Handle def-use chain dependencies. 7772 if (BundleMember->OpValue != BundleMember->Inst) { 7773 if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) { 7774 BundleMember->Dependencies++; 7775 ScheduleData *DestBundle = UseSD->FirstInBundle; 7776 if (!DestBundle->IsScheduled) 7777 BundleMember->incrementUnscheduledDeps(1); 7778 if (!DestBundle->hasValidDependencies()) 7779 WorkList.push_back(DestBundle); 7780 } 7781 } else { 7782 for (User *U : BundleMember->Inst->users()) { 7783 if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) { 7784 BundleMember->Dependencies++; 7785 ScheduleData *DestBundle = UseSD->FirstInBundle; 7786 if (!DestBundle->IsScheduled) 7787 BundleMember->incrementUnscheduledDeps(1); 7788 if (!DestBundle->hasValidDependencies()) 7789 WorkList.push_back(DestBundle); 7790 } 7791 } 7792 } 7793 7794 // Handle the memory dependencies (if any). 7795 ScheduleData *DepDest = BundleMember->NextLoadStore; 7796 if (!DepDest) 7797 continue; 7798 Instruction *SrcInst = BundleMember->Inst; 7799 assert(SrcInst->mayReadOrWriteMemory() && 7800 "NextLoadStore list for non memory effecting bundle?"); 7801 MemoryLocation SrcLoc = getLocation(SrcInst); 7802 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory(); 7803 unsigned numAliased = 0; 7804 unsigned DistToSrc = 1; 7805 7806 for ( ; DepDest; DepDest = DepDest->NextLoadStore) { 7807 assert(isInSchedulingRegion(DepDest)); 7808 7809 // We have two limits to reduce the complexity: 7810 // 1) AliasedCheckLimit: It's a small limit to reduce calls to 7811 // SLP->isAliased (which is the expensive part in this loop). 7812 // 2) MaxMemDepDistance: It's for very large blocks and it aborts 7813 // the whole loop (even if the loop is fast, it's quadratic). 7814 // It's important for the loop break condition (see below) to 7815 // check this limit even between two read-only instructions. 7816 if (DistToSrc >= MaxMemDepDistance || 7817 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) && 7818 (numAliased >= AliasedCheckLimit || 7819 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) { 7820 7821 // We increment the counter only if the locations are aliased 7822 // (instead of counting all alias checks). This gives a better 7823 // balance between reduced runtime and accurate dependencies. 7824 numAliased++; 7825 7826 DepDest->MemoryDependencies.push_back(BundleMember); 7827 BundleMember->Dependencies++; 7828 ScheduleData *DestBundle = DepDest->FirstInBundle; 7829 if (!DestBundle->IsScheduled) { 7830 BundleMember->incrementUnscheduledDeps(1); 7831 } 7832 if (!DestBundle->hasValidDependencies()) { 7833 WorkList.push_back(DestBundle); 7834 } 7835 } 7836 7837 // Example, explaining the loop break condition: Let's assume our 7838 // starting instruction is i0 and MaxMemDepDistance = 3. 7839 // 7840 // +--------v--v--v 7841 // i0,i1,i2,i3,i4,i5,i6,i7,i8 7842 // +--------^--^--^ 7843 // 7844 // MaxMemDepDistance let us stop alias-checking at i3 and we add 7845 // dependencies from i0 to i3,i4,.. (even if they are not aliased). 7846 // Previously we already added dependencies from i3 to i6,i7,i8 7847 // (because of MaxMemDepDistance). As we added a dependency from 7848 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8 7849 // and we can abort this loop at i6. 7850 if (DistToSrc >= 2 * MaxMemDepDistance) 7851 break; 7852 DistToSrc++; 7853 } 7854 } 7855 if (InsertInReadyList && SD->isReady()) { 7856 ReadyInsts.insert(SD); 7857 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst 7858 << "\n"); 7859 } 7860 } 7861 } 7862 7863 void BoUpSLP::BlockScheduling::resetSchedule() { 7864 assert(ScheduleStart && 7865 "tried to reset schedule on block which has not been scheduled"); 7866 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 7867 doForAllOpcodes(I, [&](ScheduleData *SD) { 7868 assert(isInSchedulingRegion(SD) && 7869 "ScheduleData not in scheduling region"); 7870 SD->IsScheduled = false; 7871 SD->resetUnscheduledDeps(); 7872 }); 7873 } 7874 ReadyInsts.clear(); 7875 } 7876 7877 void BoUpSLP::scheduleBlock(BlockScheduling *BS) { 7878 if (!BS->ScheduleStart) 7879 return; 7880 7881 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n"); 7882 7883 // A key point - if we got here, pre-scheduling was able to find a valid 7884 // scheduling of the sub-graph of the scheduling window which consists 7885 // of all vector bundles and their transitive users. As such, we do not 7886 // need to reschedule anything *outside of* that subgraph. 7887 7888 BS->resetSchedule(); 7889 7890 // For the real scheduling we use a more sophisticated ready-list: it is 7891 // sorted by the original instruction location. This lets the final schedule 7892 // be as close as possible to the original instruction order. 7893 DenseMap<ScheduleData *, unsigned> OriginalOrder; 7894 auto ScheduleDataCompare = [&](ScheduleData *SD1, ScheduleData *SD2) { 7895 return OriginalOrder[SD2] < OriginalOrder[SD1]; 7896 }; 7897 std::set<ScheduleData *, decltype(ScheduleDataCompare)> 7898 ReadyInsts(ScheduleDataCompare); 7899 7900 // Ensure that all dependency data is updated (for nodes in the sub-graph) 7901 // and fill the ready-list with initial instructions. 7902 int Idx = 0; 7903 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; 7904 I = I->getNextNode()) { 7905 BS->doForAllOpcodes(I, [&](ScheduleData *SD) { 7906 assert((isVectorLikeInstWithConstOps(SD->Inst) || 7907 SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) && 7908 "scheduler and vectorizer bundle mismatch"); 7909 OriginalOrder[SD->FirstInBundle] = Idx++; 7910 7911 if (SD->isSchedulingEntity() && SD->isPartOfBundle()) 7912 BS->calculateDependencies(SD, false, this); 7913 }); 7914 } 7915 BS->initialFillReadyList(ReadyInsts); 7916 7917 Instruction *LastScheduledInst = BS->ScheduleEnd; 7918 7919 // Do the "real" scheduling. 7920 while (!ReadyInsts.empty()) { 7921 ScheduleData *picked = *ReadyInsts.begin(); 7922 ReadyInsts.erase(ReadyInsts.begin()); 7923 7924 // Move the scheduled instruction(s) to their dedicated places, if not 7925 // there yet. 7926 for (ScheduleData *BundleMember = picked; BundleMember; 7927 BundleMember = BundleMember->NextInBundle) { 7928 Instruction *pickedInst = BundleMember->Inst; 7929 if (pickedInst->getNextNode() != LastScheduledInst) 7930 pickedInst->moveBefore(LastScheduledInst); 7931 LastScheduledInst = pickedInst; 7932 } 7933 7934 BS->schedule(picked, ReadyInsts); 7935 } 7936 7937 // Check that we didn't break any of our invariants. 7938 #ifdef EXPENSIVE_CHECKS 7939 BS->verify(); 7940 #endif 7941 7942 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS) 7943 // Check that all schedulable entities got scheduled 7944 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) { 7945 BS->doForAllOpcodes(I, [&](ScheduleData *SD) { 7946 if (SD->isSchedulingEntity() && SD->hasValidDependencies()) { 7947 assert(SD->IsScheduled && "must be scheduled at this point"); 7948 } 7949 }); 7950 } 7951 #endif 7952 7953 // Avoid duplicate scheduling of the block. 7954 BS->ScheduleStart = nullptr; 7955 } 7956 7957 unsigned BoUpSLP::getVectorElementSize(Value *V) { 7958 // If V is a store, just return the width of the stored value (or value 7959 // truncated just before storing) without traversing the expression tree. 7960 // This is the common case. 7961 if (auto *Store = dyn_cast<StoreInst>(V)) { 7962 if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand())) 7963 return DL->getTypeSizeInBits(Trunc->getSrcTy()); 7964 return DL->getTypeSizeInBits(Store->getValueOperand()->getType()); 7965 } 7966 7967 if (auto *IEI = dyn_cast<InsertElementInst>(V)) 7968 return getVectorElementSize(IEI->getOperand(1)); 7969 7970 auto E = InstrElementSize.find(V); 7971 if (E != InstrElementSize.end()) 7972 return E->second; 7973 7974 // If V is not a store, we can traverse the expression tree to find loads 7975 // that feed it. The type of the loaded value may indicate a more suitable 7976 // width than V's type. We want to base the vector element size on the width 7977 // of memory operations where possible. 7978 SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist; 7979 SmallPtrSet<Instruction *, 16> Visited; 7980 if (auto *I = dyn_cast<Instruction>(V)) { 7981 Worklist.emplace_back(I, I->getParent()); 7982 Visited.insert(I); 7983 } 7984 7985 // Traverse the expression tree in bottom-up order looking for loads. If we 7986 // encounter an instruction we don't yet handle, we give up. 7987 auto Width = 0u; 7988 while (!Worklist.empty()) { 7989 Instruction *I; 7990 BasicBlock *Parent; 7991 std::tie(I, Parent) = Worklist.pop_back_val(); 7992 7993 // We should only be looking at scalar instructions here. If the current 7994 // instruction has a vector type, skip. 7995 auto *Ty = I->getType(); 7996 if (isa<VectorType>(Ty)) 7997 continue; 7998 7999 // If the current instruction is a load, update MaxWidth to reflect the 8000 // width of the loaded value. 8001 if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) || 8002 isa<ExtractValueInst>(I)) 8003 Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty)); 8004 8005 // Otherwise, we need to visit the operands of the instruction. We only 8006 // handle the interesting cases from buildTree here. If an operand is an 8007 // instruction we haven't yet visited and from the same basic block as the 8008 // user or the use is a PHI node, we add it to the worklist. 8009 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8010 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) || 8011 isa<UnaryOperator>(I)) { 8012 for (Use &U : I->operands()) 8013 if (auto *J = dyn_cast<Instruction>(U.get())) 8014 if (Visited.insert(J).second && 8015 (isa<PHINode>(I) || J->getParent() == Parent)) 8016 Worklist.emplace_back(J, J->getParent()); 8017 } else { 8018 break; 8019 } 8020 } 8021 8022 // If we didn't encounter a memory access in the expression tree, or if we 8023 // gave up for some reason, just return the width of V. Otherwise, return the 8024 // maximum width we found. 8025 if (!Width) { 8026 if (auto *CI = dyn_cast<CmpInst>(V)) 8027 V = CI->getOperand(0); 8028 Width = DL->getTypeSizeInBits(V->getType()); 8029 } 8030 8031 for (Instruction *I : Visited) 8032 InstrElementSize[I] = Width; 8033 8034 return Width; 8035 } 8036 8037 // Determine if a value V in a vectorizable expression Expr can be demoted to a 8038 // smaller type with a truncation. We collect the values that will be demoted 8039 // in ToDemote and additional roots that require investigating in Roots. 8040 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr, 8041 SmallVectorImpl<Value *> &ToDemote, 8042 SmallVectorImpl<Value *> &Roots) { 8043 // We can always demote constants. 8044 if (isa<Constant>(V)) { 8045 ToDemote.push_back(V); 8046 return true; 8047 } 8048 8049 // If the value is not an instruction in the expression with only one use, it 8050 // cannot be demoted. 8051 auto *I = dyn_cast<Instruction>(V); 8052 if (!I || !I->hasOneUse() || !Expr.count(I)) 8053 return false; 8054 8055 switch (I->getOpcode()) { 8056 8057 // We can always demote truncations and extensions. Since truncations can 8058 // seed additional demotion, we save the truncated value. 8059 case Instruction::Trunc: 8060 Roots.push_back(I->getOperand(0)); 8061 break; 8062 case Instruction::ZExt: 8063 case Instruction::SExt: 8064 if (isa<ExtractElementInst>(I->getOperand(0)) || 8065 isa<InsertElementInst>(I->getOperand(0))) 8066 return false; 8067 break; 8068 8069 // We can demote certain binary operations if we can demote both of their 8070 // operands. 8071 case Instruction::Add: 8072 case Instruction::Sub: 8073 case Instruction::Mul: 8074 case Instruction::And: 8075 case Instruction::Or: 8076 case Instruction::Xor: 8077 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) || 8078 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots)) 8079 return false; 8080 break; 8081 8082 // We can demote selects if we can demote their true and false values. 8083 case Instruction::Select: { 8084 SelectInst *SI = cast<SelectInst>(I); 8085 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) || 8086 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots)) 8087 return false; 8088 break; 8089 } 8090 8091 // We can demote phis if we can demote all their incoming operands. Note that 8092 // we don't need to worry about cycles since we ensure single use above. 8093 case Instruction::PHI: { 8094 PHINode *PN = cast<PHINode>(I); 8095 for (Value *IncValue : PN->incoming_values()) 8096 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots)) 8097 return false; 8098 break; 8099 } 8100 8101 // Otherwise, conservatively give up. 8102 default: 8103 return false; 8104 } 8105 8106 // Record the value that we can demote. 8107 ToDemote.push_back(V); 8108 return true; 8109 } 8110 8111 void BoUpSLP::computeMinimumValueSizes() { 8112 // If there are no external uses, the expression tree must be rooted by a 8113 // store. We can't demote in-memory values, so there is nothing to do here. 8114 if (ExternalUses.empty()) 8115 return; 8116 8117 // We only attempt to truncate integer expressions. 8118 auto &TreeRoot = VectorizableTree[0]->Scalars; 8119 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType()); 8120 if (!TreeRootIT) 8121 return; 8122 8123 // If the expression is not rooted by a store, these roots should have 8124 // external uses. We will rely on InstCombine to rewrite the expression in 8125 // the narrower type. However, InstCombine only rewrites single-use values. 8126 // This means that if a tree entry other than a root is used externally, it 8127 // must have multiple uses and InstCombine will not rewrite it. The code 8128 // below ensures that only the roots are used externally. 8129 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end()); 8130 for (auto &EU : ExternalUses) 8131 if (!Expr.erase(EU.Scalar)) 8132 return; 8133 if (!Expr.empty()) 8134 return; 8135 8136 // Collect the scalar values of the vectorizable expression. We will use this 8137 // context to determine which values can be demoted. If we see a truncation, 8138 // we mark it as seeding another demotion. 8139 for (auto &EntryPtr : VectorizableTree) 8140 Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end()); 8141 8142 // Ensure the roots of the vectorizable tree don't form a cycle. They must 8143 // have a single external user that is not in the vectorizable tree. 8144 for (auto *Root : TreeRoot) 8145 if (!Root->hasOneUse() || Expr.count(*Root->user_begin())) 8146 return; 8147 8148 // Conservatively determine if we can actually truncate the roots of the 8149 // expression. Collect the values that can be demoted in ToDemote and 8150 // additional roots that require investigating in Roots. 8151 SmallVector<Value *, 32> ToDemote; 8152 SmallVector<Value *, 4> Roots; 8153 for (auto *Root : TreeRoot) 8154 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots)) 8155 return; 8156 8157 // The maximum bit width required to represent all the values that can be 8158 // demoted without loss of precision. It would be safe to truncate the roots 8159 // of the expression to this width. 8160 auto MaxBitWidth = 8u; 8161 8162 // We first check if all the bits of the roots are demanded. If they're not, 8163 // we can truncate the roots to this narrower type. 8164 for (auto *Root : TreeRoot) { 8165 auto Mask = DB->getDemandedBits(cast<Instruction>(Root)); 8166 MaxBitWidth = std::max<unsigned>( 8167 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth); 8168 } 8169 8170 // True if the roots can be zero-extended back to their original type, rather 8171 // than sign-extended. We know that if the leading bits are not demanded, we 8172 // can safely zero-extend. So we initialize IsKnownPositive to True. 8173 bool IsKnownPositive = true; 8174 8175 // If all the bits of the roots are demanded, we can try a little harder to 8176 // compute a narrower type. This can happen, for example, if the roots are 8177 // getelementptr indices. InstCombine promotes these indices to the pointer 8178 // width. Thus, all their bits are technically demanded even though the 8179 // address computation might be vectorized in a smaller type. 8180 // 8181 // We start by looking at each entry that can be demoted. We compute the 8182 // maximum bit width required to store the scalar by using ValueTracking to 8183 // compute the number of high-order bits we can truncate. 8184 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) && 8185 llvm::all_of(TreeRoot, [](Value *R) { 8186 assert(R->hasOneUse() && "Root should have only one use!"); 8187 return isa<GetElementPtrInst>(R->user_back()); 8188 })) { 8189 MaxBitWidth = 8u; 8190 8191 // Determine if the sign bit of all the roots is known to be zero. If not, 8192 // IsKnownPositive is set to False. 8193 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) { 8194 KnownBits Known = computeKnownBits(R, *DL); 8195 return Known.isNonNegative(); 8196 }); 8197 8198 // Determine the maximum number of bits required to store the scalar 8199 // values. 8200 for (auto *Scalar : ToDemote) { 8201 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT); 8202 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType()); 8203 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth); 8204 } 8205 8206 // If we can't prove that the sign bit is zero, we must add one to the 8207 // maximum bit width to account for the unknown sign bit. This preserves 8208 // the existing sign bit so we can safely sign-extend the root back to the 8209 // original type. Otherwise, if we know the sign bit is zero, we will 8210 // zero-extend the root instead. 8211 // 8212 // FIXME: This is somewhat suboptimal, as there will be cases where adding 8213 // one to the maximum bit width will yield a larger-than-necessary 8214 // type. In general, we need to add an extra bit only if we can't 8215 // prove that the upper bit of the original type is equal to the 8216 // upper bit of the proposed smaller type. If these two bits are the 8217 // same (either zero or one) we know that sign-extending from the 8218 // smaller type will result in the same value. Here, since we can't 8219 // yet prove this, we are just making the proposed smaller type 8220 // larger to ensure correctness. 8221 if (!IsKnownPositive) 8222 ++MaxBitWidth; 8223 } 8224 8225 // Round MaxBitWidth up to the next power-of-two. 8226 if (!isPowerOf2_64(MaxBitWidth)) 8227 MaxBitWidth = NextPowerOf2(MaxBitWidth); 8228 8229 // If the maximum bit width we compute is less than the with of the roots' 8230 // type, we can proceed with the narrowing. Otherwise, do nothing. 8231 if (MaxBitWidth >= TreeRootIT->getBitWidth()) 8232 return; 8233 8234 // If we can truncate the root, we must collect additional values that might 8235 // be demoted as a result. That is, those seeded by truncations we will 8236 // modify. 8237 while (!Roots.empty()) 8238 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots); 8239 8240 // Finally, map the values we can demote to the maximum bit with we computed. 8241 for (auto *Scalar : ToDemote) 8242 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive); 8243 } 8244 8245 namespace { 8246 8247 /// The SLPVectorizer Pass. 8248 struct SLPVectorizer : public FunctionPass { 8249 SLPVectorizerPass Impl; 8250 8251 /// Pass identification, replacement for typeid 8252 static char ID; 8253 8254 explicit SLPVectorizer() : FunctionPass(ID) { 8255 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); 8256 } 8257 8258 bool doInitialization(Module &M) override { return false; } 8259 8260 bool runOnFunction(Function &F) override { 8261 if (skipFunction(F)) 8262 return false; 8263 8264 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 8265 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 8266 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 8267 auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr; 8268 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 8269 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 8270 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 8271 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 8272 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); 8273 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 8274 8275 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 8276 } 8277 8278 void getAnalysisUsage(AnalysisUsage &AU) const override { 8279 FunctionPass::getAnalysisUsage(AU); 8280 AU.addRequired<AssumptionCacheTracker>(); 8281 AU.addRequired<ScalarEvolutionWrapperPass>(); 8282 AU.addRequired<AAResultsWrapperPass>(); 8283 AU.addRequired<TargetTransformInfoWrapperPass>(); 8284 AU.addRequired<LoopInfoWrapperPass>(); 8285 AU.addRequired<DominatorTreeWrapperPass>(); 8286 AU.addRequired<DemandedBitsWrapperPass>(); 8287 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 8288 AU.addRequired<InjectTLIMappingsLegacy>(); 8289 AU.addPreserved<LoopInfoWrapperPass>(); 8290 AU.addPreserved<DominatorTreeWrapperPass>(); 8291 AU.addPreserved<AAResultsWrapperPass>(); 8292 AU.addPreserved<GlobalsAAWrapperPass>(); 8293 AU.setPreservesCFG(); 8294 } 8295 }; 8296 8297 } // end anonymous namespace 8298 8299 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) { 8300 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 8301 auto *TTI = &AM.getResult<TargetIRAnalysis>(F); 8302 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F); 8303 auto *AA = &AM.getResult<AAManager>(F); 8304 auto *LI = &AM.getResult<LoopAnalysis>(F); 8305 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 8306 auto *AC = &AM.getResult<AssumptionAnalysis>(F); 8307 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F); 8308 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 8309 8310 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 8311 if (!Changed) 8312 return PreservedAnalyses::all(); 8313 8314 PreservedAnalyses PA; 8315 PA.preserveSet<CFGAnalyses>(); 8316 return PA; 8317 } 8318 8319 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_, 8320 TargetTransformInfo *TTI_, 8321 TargetLibraryInfo *TLI_, AAResults *AA_, 8322 LoopInfo *LI_, DominatorTree *DT_, 8323 AssumptionCache *AC_, DemandedBits *DB_, 8324 OptimizationRemarkEmitter *ORE_) { 8325 if (!RunSLPVectorization) 8326 return false; 8327 SE = SE_; 8328 TTI = TTI_; 8329 TLI = TLI_; 8330 AA = AA_; 8331 LI = LI_; 8332 DT = DT_; 8333 AC = AC_; 8334 DB = DB_; 8335 DL = &F.getParent()->getDataLayout(); 8336 8337 Stores.clear(); 8338 GEPs.clear(); 8339 bool Changed = false; 8340 8341 // If the target claims to have no vector registers don't attempt 8342 // vectorization. 8343 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) { 8344 LLVM_DEBUG( 8345 dbgs() << "SLP: Didn't find any vector registers for target, abort.\n"); 8346 return false; 8347 } 8348 8349 // Don't vectorize when the attribute NoImplicitFloat is used. 8350 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) 8351 return false; 8352 8353 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"); 8354 8355 // Use the bottom up slp vectorizer to construct chains that start with 8356 // store instructions. 8357 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_); 8358 8359 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to 8360 // delete instructions. 8361 8362 // Update DFS numbers now so that we can use them for ordering. 8363 DT->updateDFSNumbers(); 8364 8365 // Scan the blocks in the function in post order. 8366 for (auto BB : post_order(&F.getEntryBlock())) { 8367 collectSeedInstructions(BB); 8368 8369 // Vectorize trees that end at stores. 8370 if (!Stores.empty()) { 8371 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size() 8372 << " underlying objects.\n"); 8373 Changed |= vectorizeStoreChains(R); 8374 } 8375 8376 // Vectorize trees that end at reductions. 8377 Changed |= vectorizeChainsInBlock(BB, R); 8378 8379 // Vectorize the index computations of getelementptr instructions. This 8380 // is primarily intended to catch gather-like idioms ending at 8381 // non-consecutive loads. 8382 if (!GEPs.empty()) { 8383 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size() 8384 << " underlying objects.\n"); 8385 Changed |= vectorizeGEPIndices(BB, R); 8386 } 8387 } 8388 8389 if (Changed) { 8390 R.optimizeGatherSequence(); 8391 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n"); 8392 } 8393 return Changed; 8394 } 8395 8396 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R, 8397 unsigned Idx) { 8398 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size() 8399 << "\n"); 8400 const unsigned Sz = R.getVectorElementSize(Chain[0]); 8401 const unsigned MinVF = R.getMinVecRegSize() / Sz; 8402 unsigned VF = Chain.size(); 8403 8404 if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF) 8405 return false; 8406 8407 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx 8408 << "\n"); 8409 8410 R.buildTree(Chain); 8411 if (R.isTreeTinyAndNotFullyVectorizable()) 8412 return false; 8413 if (R.isLoadCombineCandidate()) 8414 return false; 8415 R.reorderTopToBottom(); 8416 R.reorderBottomToTop(); 8417 R.buildExternalUses(); 8418 8419 R.computeMinimumValueSizes(); 8420 8421 InstructionCost Cost = R.getTreeCost(); 8422 8423 LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n"); 8424 if (Cost < -SLPCostThreshold) { 8425 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n"); 8426 8427 using namespace ore; 8428 8429 R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized", 8430 cast<StoreInst>(Chain[0])) 8431 << "Stores SLP vectorized with cost " << NV("Cost", Cost) 8432 << " and with tree size " 8433 << NV("TreeSize", R.getTreeSize())); 8434 8435 R.vectorizeTree(); 8436 return true; 8437 } 8438 8439 return false; 8440 } 8441 8442 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores, 8443 BoUpSLP &R) { 8444 // We may run into multiple chains that merge into a single chain. We mark the 8445 // stores that we vectorized so that we don't visit the same store twice. 8446 BoUpSLP::ValueSet VectorizedStores; 8447 bool Changed = false; 8448 8449 int E = Stores.size(); 8450 SmallBitVector Tails(E, false); 8451 int MaxIter = MaxStoreLookup.getValue(); 8452 SmallVector<std::pair<int, int>, 16> ConsecutiveChain( 8453 E, std::make_pair(E, INT_MAX)); 8454 SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false)); 8455 int IterCnt; 8456 auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter, 8457 &CheckedPairs, 8458 &ConsecutiveChain](int K, int Idx) { 8459 if (IterCnt >= MaxIter) 8460 return true; 8461 if (CheckedPairs[Idx].test(K)) 8462 return ConsecutiveChain[K].second == 1 && 8463 ConsecutiveChain[K].first == Idx; 8464 ++IterCnt; 8465 CheckedPairs[Idx].set(K); 8466 CheckedPairs[K].set(Idx); 8467 Optional<int> Diff = getPointersDiff( 8468 Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(), 8469 Stores[Idx]->getValueOperand()->getType(), 8470 Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true); 8471 if (!Diff || *Diff == 0) 8472 return false; 8473 int Val = *Diff; 8474 if (Val < 0) { 8475 if (ConsecutiveChain[Idx].second > -Val) { 8476 Tails.set(K); 8477 ConsecutiveChain[Idx] = std::make_pair(K, -Val); 8478 } 8479 return false; 8480 } 8481 if (ConsecutiveChain[K].second <= Val) 8482 return false; 8483 8484 Tails.set(Idx); 8485 ConsecutiveChain[K] = std::make_pair(Idx, Val); 8486 return Val == 1; 8487 }; 8488 // Do a quadratic search on all of the given stores in reverse order and find 8489 // all of the pairs of stores that follow each other. 8490 for (int Idx = E - 1; Idx >= 0; --Idx) { 8491 // If a store has multiple consecutive store candidates, search according 8492 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ... 8493 // This is because usually pairing with immediate succeeding or preceding 8494 // candidate create the best chance to find slp vectorization opportunity. 8495 const int MaxLookDepth = std::max(E - Idx, Idx + 1); 8496 IterCnt = 0; 8497 for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset) 8498 if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) || 8499 (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx))) 8500 break; 8501 } 8502 8503 // Tracks if we tried to vectorize stores starting from the given tail 8504 // already. 8505 SmallBitVector TriedTails(E, false); 8506 // For stores that start but don't end a link in the chain: 8507 for (int Cnt = E; Cnt > 0; --Cnt) { 8508 int I = Cnt - 1; 8509 if (ConsecutiveChain[I].first == E || Tails.test(I)) 8510 continue; 8511 // We found a store instr that starts a chain. Now follow the chain and try 8512 // to vectorize it. 8513 BoUpSLP::ValueList Operands; 8514 // Collect the chain into a list. 8515 while (I != E && !VectorizedStores.count(Stores[I])) { 8516 Operands.push_back(Stores[I]); 8517 Tails.set(I); 8518 if (ConsecutiveChain[I].second != 1) { 8519 // Mark the new end in the chain and go back, if required. It might be 8520 // required if the original stores come in reversed order, for example. 8521 if (ConsecutiveChain[I].first != E && 8522 Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) && 8523 !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) { 8524 TriedTails.set(I); 8525 Tails.reset(ConsecutiveChain[I].first); 8526 if (Cnt < ConsecutiveChain[I].first + 2) 8527 Cnt = ConsecutiveChain[I].first + 2; 8528 } 8529 break; 8530 } 8531 // Move to the next value in the chain. 8532 I = ConsecutiveChain[I].first; 8533 } 8534 assert(!Operands.empty() && "Expected non-empty list of stores."); 8535 8536 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 8537 unsigned EltSize = R.getVectorElementSize(Operands[0]); 8538 unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize); 8539 8540 unsigned MinVF = R.getMinVF(EltSize); 8541 unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store), 8542 MaxElts); 8543 8544 // FIXME: Is division-by-2 the correct step? Should we assert that the 8545 // register size is a power-of-2? 8546 unsigned StartIdx = 0; 8547 for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) { 8548 for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) { 8549 ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size); 8550 if (!VectorizedStores.count(Slice.front()) && 8551 !VectorizedStores.count(Slice.back()) && 8552 vectorizeStoreChain(Slice, R, Cnt)) { 8553 // Mark the vectorized stores so that we don't vectorize them again. 8554 VectorizedStores.insert(Slice.begin(), Slice.end()); 8555 Changed = true; 8556 // If we vectorized initial block, no need to try to vectorize it 8557 // again. 8558 if (Cnt == StartIdx) 8559 StartIdx += Size; 8560 Cnt += Size; 8561 continue; 8562 } 8563 ++Cnt; 8564 } 8565 // Check if the whole array was vectorized already - exit. 8566 if (StartIdx >= Operands.size()) 8567 break; 8568 } 8569 } 8570 8571 return Changed; 8572 } 8573 8574 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) { 8575 // Initialize the collections. We will make a single pass over the block. 8576 Stores.clear(); 8577 GEPs.clear(); 8578 8579 // Visit the store and getelementptr instructions in BB and organize them in 8580 // Stores and GEPs according to the underlying objects of their pointer 8581 // operands. 8582 for (Instruction &I : *BB) { 8583 // Ignore store instructions that are volatile or have a pointer operand 8584 // that doesn't point to a scalar type. 8585 if (auto *SI = dyn_cast<StoreInst>(&I)) { 8586 if (!SI->isSimple()) 8587 continue; 8588 if (!isValidElementType(SI->getValueOperand()->getType())) 8589 continue; 8590 Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI); 8591 } 8592 8593 // Ignore getelementptr instructions that have more than one index, a 8594 // constant index, or a pointer operand that doesn't point to a scalar 8595 // type. 8596 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 8597 auto Idx = GEP->idx_begin()->get(); 8598 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx)) 8599 continue; 8600 if (!isValidElementType(Idx->getType())) 8601 continue; 8602 if (GEP->getType()->isVectorTy()) 8603 continue; 8604 GEPs[GEP->getPointerOperand()].push_back(GEP); 8605 } 8606 } 8607 } 8608 8609 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { 8610 if (!A || !B) 8611 return false; 8612 if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B)) 8613 return false; 8614 Value *VL[] = {A, B}; 8615 return tryToVectorizeList(VL, R); 8616 } 8617 8618 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, 8619 bool LimitForRegisterSize) { 8620 if (VL.size() < 2) 8621 return false; 8622 8623 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " 8624 << VL.size() << ".\n"); 8625 8626 // Check that all of the parts are instructions of the same type, 8627 // we permit an alternate opcode via InstructionsState. 8628 InstructionsState S = getSameOpcode(VL); 8629 if (!S.getOpcode()) 8630 return false; 8631 8632 Instruction *I0 = cast<Instruction>(S.OpValue); 8633 // Make sure invalid types (including vector type) are rejected before 8634 // determining vectorization factor for scalar instructions. 8635 for (Value *V : VL) { 8636 Type *Ty = V->getType(); 8637 if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) { 8638 // NOTE: the following will give user internal llvm type name, which may 8639 // not be useful. 8640 R.getORE()->emit([&]() { 8641 std::string type_str; 8642 llvm::raw_string_ostream rso(type_str); 8643 Ty->print(rso); 8644 return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0) 8645 << "Cannot SLP vectorize list: type " 8646 << rso.str() + " is unsupported by vectorizer"; 8647 }); 8648 return false; 8649 } 8650 } 8651 8652 unsigned Sz = R.getVectorElementSize(I0); 8653 unsigned MinVF = R.getMinVF(Sz); 8654 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF); 8655 MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF); 8656 if (MaxVF < 2) { 8657 R.getORE()->emit([&]() { 8658 return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0) 8659 << "Cannot SLP vectorize list: vectorization factor " 8660 << "less than 2 is not supported"; 8661 }); 8662 return false; 8663 } 8664 8665 bool Changed = false; 8666 bool CandidateFound = false; 8667 InstructionCost MinCost = SLPCostThreshold.getValue(); 8668 Type *ScalarTy = VL[0]->getType(); 8669 if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 8670 ScalarTy = IE->getOperand(1)->getType(); 8671 8672 unsigned NextInst = 0, MaxInst = VL.size(); 8673 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) { 8674 // No actual vectorization should happen, if number of parts is the same as 8675 // provided vectorization factor (i.e. the scalar type is used for vector 8676 // code during codegen). 8677 auto *VecTy = FixedVectorType::get(ScalarTy, VF); 8678 if (TTI->getNumberOfParts(VecTy) == VF) 8679 continue; 8680 for (unsigned I = NextInst; I < MaxInst; ++I) { 8681 unsigned OpsWidth = 0; 8682 8683 if (I + VF > MaxInst) 8684 OpsWidth = MaxInst - I; 8685 else 8686 OpsWidth = VF; 8687 8688 if (!isPowerOf2_32(OpsWidth)) 8689 continue; 8690 8691 if ((LimitForRegisterSize && OpsWidth < MaxVF) || 8692 (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2)) 8693 break; 8694 8695 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth); 8696 // Check that a previous iteration of this loop did not delete the Value. 8697 if (llvm::any_of(Ops, [&R](Value *V) { 8698 auto *I = dyn_cast<Instruction>(V); 8699 return I && R.isDeleted(I); 8700 })) 8701 continue; 8702 8703 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " 8704 << "\n"); 8705 8706 R.buildTree(Ops); 8707 if (R.isTreeTinyAndNotFullyVectorizable()) 8708 continue; 8709 R.reorderTopToBottom(); 8710 R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front())); 8711 R.buildExternalUses(); 8712 8713 R.computeMinimumValueSizes(); 8714 InstructionCost Cost = R.getTreeCost(); 8715 CandidateFound = true; 8716 MinCost = std::min(MinCost, Cost); 8717 8718 if (Cost < -SLPCostThreshold) { 8719 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n"); 8720 R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList", 8721 cast<Instruction>(Ops[0])) 8722 << "SLP vectorized with cost " << ore::NV("Cost", Cost) 8723 << " and with tree size " 8724 << ore::NV("TreeSize", R.getTreeSize())); 8725 8726 R.vectorizeTree(); 8727 // Move to the next bundle. 8728 I += VF - 1; 8729 NextInst = I + 1; 8730 Changed = true; 8731 } 8732 } 8733 } 8734 8735 if (!Changed && CandidateFound) { 8736 R.getORE()->emit([&]() { 8737 return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0) 8738 << "List vectorization was possible but not beneficial with cost " 8739 << ore::NV("Cost", MinCost) << " >= " 8740 << ore::NV("Treshold", -SLPCostThreshold); 8741 }); 8742 } else if (!Changed) { 8743 R.getORE()->emit([&]() { 8744 return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0) 8745 << "Cannot SLP vectorize list: vectorization was impossible" 8746 << " with available vectorization factors"; 8747 }); 8748 } 8749 return Changed; 8750 } 8751 8752 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) { 8753 if (!I) 8754 return false; 8755 8756 if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) 8757 return false; 8758 8759 Value *P = I->getParent(); 8760 8761 // Vectorize in current basic block only. 8762 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0)); 8763 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1)); 8764 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P) 8765 return false; 8766 8767 // Try to vectorize V. 8768 if (tryToVectorizePair(Op0, Op1, R)) 8769 return true; 8770 8771 auto *A = dyn_cast<BinaryOperator>(Op0); 8772 auto *B = dyn_cast<BinaryOperator>(Op1); 8773 // Try to skip B. 8774 if (B && B->hasOneUse()) { 8775 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); 8776 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); 8777 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R)) 8778 return true; 8779 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R)) 8780 return true; 8781 } 8782 8783 // Try to skip A. 8784 if (A && A->hasOneUse()) { 8785 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); 8786 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); 8787 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R)) 8788 return true; 8789 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R)) 8790 return true; 8791 } 8792 return false; 8793 } 8794 8795 namespace { 8796 8797 /// Model horizontal reductions. 8798 /// 8799 /// A horizontal reduction is a tree of reduction instructions that has values 8800 /// that can be put into a vector as its leaves. For example: 8801 /// 8802 /// mul mul mul mul 8803 /// \ / \ / 8804 /// + + 8805 /// \ / 8806 /// + 8807 /// This tree has "mul" as its leaf values and "+" as its reduction 8808 /// instructions. A reduction can feed into a store or a binary operation 8809 /// feeding a phi. 8810 /// ... 8811 /// \ / 8812 /// + 8813 /// | 8814 /// phi += 8815 /// 8816 /// Or: 8817 /// ... 8818 /// \ / 8819 /// + 8820 /// | 8821 /// *p = 8822 /// 8823 class HorizontalReduction { 8824 using ReductionOpsType = SmallVector<Value *, 16>; 8825 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>; 8826 ReductionOpsListType ReductionOps; 8827 SmallVector<Value *, 32> ReducedVals; 8828 // Use map vector to make stable output. 8829 MapVector<Instruction *, Value *> ExtraArgs; 8830 WeakTrackingVH ReductionRoot; 8831 /// The type of reduction operation. 8832 RecurKind RdxKind; 8833 8834 const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max(); 8835 8836 static bool isCmpSelMinMax(Instruction *I) { 8837 return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) && 8838 RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I)); 8839 } 8840 8841 // And/or are potentially poison-safe logical patterns like: 8842 // select x, y, false 8843 // select x, true, y 8844 static bool isBoolLogicOp(Instruction *I) { 8845 return match(I, m_LogicalAnd(m_Value(), m_Value())) || 8846 match(I, m_LogicalOr(m_Value(), m_Value())); 8847 } 8848 8849 /// Checks if instruction is associative and can be vectorized. 8850 static bool isVectorizable(RecurKind Kind, Instruction *I) { 8851 if (Kind == RecurKind::None) 8852 return false; 8853 8854 // Integer ops that map to select instructions or intrinsics are fine. 8855 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) || 8856 isBoolLogicOp(I)) 8857 return true; 8858 8859 if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) { 8860 // FP min/max are associative except for NaN and -0.0. We do not 8861 // have to rule out -0.0 here because the intrinsic semantics do not 8862 // specify a fixed result for it. 8863 return I->getFastMathFlags().noNaNs(); 8864 } 8865 8866 return I->isAssociative(); 8867 } 8868 8869 static Value *getRdxOperand(Instruction *I, unsigned Index) { 8870 // Poison-safe 'or' takes the form: select X, true, Y 8871 // To make that work with the normal operand processing, we skip the 8872 // true value operand. 8873 // TODO: Change the code and data structures to handle this without a hack. 8874 if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1) 8875 return I->getOperand(2); 8876 return I->getOperand(Index); 8877 } 8878 8879 /// Checks if the ParentStackElem.first should be marked as a reduction 8880 /// operation with an extra argument or as extra argument itself. 8881 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem, 8882 Value *ExtraArg) { 8883 if (ExtraArgs.count(ParentStackElem.first)) { 8884 ExtraArgs[ParentStackElem.first] = nullptr; 8885 // We ran into something like: 8886 // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg. 8887 // The whole ParentStackElem.first should be considered as an extra value 8888 // in this case. 8889 // Do not perform analysis of remaining operands of ParentStackElem.first 8890 // instruction, this whole instruction is an extra argument. 8891 ParentStackElem.second = INVALID_OPERAND_INDEX; 8892 } else { 8893 // We ran into something like: 8894 // ParentStackElem.first += ... + ExtraArg + ... 8895 ExtraArgs[ParentStackElem.first] = ExtraArg; 8896 } 8897 } 8898 8899 /// Creates reduction operation with the current opcode. 8900 static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS, 8901 Value *RHS, const Twine &Name, bool UseSelect) { 8902 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind); 8903 switch (Kind) { 8904 case RecurKind::Or: 8905 if (UseSelect && 8906 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 8907 return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name); 8908 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8909 Name); 8910 case RecurKind::And: 8911 if (UseSelect && 8912 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 8913 return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name); 8914 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8915 Name); 8916 case RecurKind::Add: 8917 case RecurKind::Mul: 8918 case RecurKind::Xor: 8919 case RecurKind::FAdd: 8920 case RecurKind::FMul: 8921 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8922 Name); 8923 case RecurKind::FMax: 8924 return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS); 8925 case RecurKind::FMin: 8926 return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS); 8927 case RecurKind::SMax: 8928 if (UseSelect) { 8929 Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name); 8930 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8931 } 8932 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS); 8933 case RecurKind::SMin: 8934 if (UseSelect) { 8935 Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name); 8936 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8937 } 8938 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS); 8939 case RecurKind::UMax: 8940 if (UseSelect) { 8941 Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name); 8942 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8943 } 8944 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS); 8945 case RecurKind::UMin: 8946 if (UseSelect) { 8947 Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name); 8948 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8949 } 8950 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS); 8951 default: 8952 llvm_unreachable("Unknown reduction operation."); 8953 } 8954 } 8955 8956 /// Creates reduction operation with the current opcode with the IR flags 8957 /// from \p ReductionOps. 8958 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 8959 Value *RHS, const Twine &Name, 8960 const ReductionOpsListType &ReductionOps) { 8961 bool UseSelect = ReductionOps.size() == 2 || 8962 // Logical or/and. 8963 (ReductionOps.size() == 1 && 8964 isa<SelectInst>(ReductionOps.front().front())); 8965 assert((!UseSelect || ReductionOps.size() != 2 || 8966 isa<SelectInst>(ReductionOps[1][0])) && 8967 "Expected cmp + select pairs for reduction"); 8968 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect); 8969 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 8970 if (auto *Sel = dyn_cast<SelectInst>(Op)) { 8971 propagateIRFlags(Sel->getCondition(), ReductionOps[0]); 8972 propagateIRFlags(Op, ReductionOps[1]); 8973 return Op; 8974 } 8975 } 8976 propagateIRFlags(Op, ReductionOps[0]); 8977 return Op; 8978 } 8979 8980 /// Creates reduction operation with the current opcode with the IR flags 8981 /// from \p I. 8982 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 8983 Value *RHS, const Twine &Name, Instruction *I) { 8984 auto *SelI = dyn_cast<SelectInst>(I); 8985 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr); 8986 if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 8987 if (auto *Sel = dyn_cast<SelectInst>(Op)) 8988 propagateIRFlags(Sel->getCondition(), SelI->getCondition()); 8989 } 8990 propagateIRFlags(Op, I); 8991 return Op; 8992 } 8993 8994 static RecurKind getRdxKind(Instruction *I) { 8995 assert(I && "Expected instruction for reduction matching"); 8996 if (match(I, m_Add(m_Value(), m_Value()))) 8997 return RecurKind::Add; 8998 if (match(I, m_Mul(m_Value(), m_Value()))) 8999 return RecurKind::Mul; 9000 if (match(I, m_And(m_Value(), m_Value())) || 9001 match(I, m_LogicalAnd(m_Value(), m_Value()))) 9002 return RecurKind::And; 9003 if (match(I, m_Or(m_Value(), m_Value())) || 9004 match(I, m_LogicalOr(m_Value(), m_Value()))) 9005 return RecurKind::Or; 9006 if (match(I, m_Xor(m_Value(), m_Value()))) 9007 return RecurKind::Xor; 9008 if (match(I, m_FAdd(m_Value(), m_Value()))) 9009 return RecurKind::FAdd; 9010 if (match(I, m_FMul(m_Value(), m_Value()))) 9011 return RecurKind::FMul; 9012 9013 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value()))) 9014 return RecurKind::FMax; 9015 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value()))) 9016 return RecurKind::FMin; 9017 9018 // This matches either cmp+select or intrinsics. SLP is expected to handle 9019 // either form. 9020 // TODO: If we are canonicalizing to intrinsics, we can remove several 9021 // special-case paths that deal with selects. 9022 if (match(I, m_SMax(m_Value(), m_Value()))) 9023 return RecurKind::SMax; 9024 if (match(I, m_SMin(m_Value(), m_Value()))) 9025 return RecurKind::SMin; 9026 if (match(I, m_UMax(m_Value(), m_Value()))) 9027 return RecurKind::UMax; 9028 if (match(I, m_UMin(m_Value(), m_Value()))) 9029 return RecurKind::UMin; 9030 9031 if (auto *Select = dyn_cast<SelectInst>(I)) { 9032 // Try harder: look for min/max pattern based on instructions producing 9033 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2). 9034 // During the intermediate stages of SLP, it's very common to have 9035 // pattern like this (since optimizeGatherSequence is run only once 9036 // at the end): 9037 // %1 = extractelement <2 x i32> %a, i32 0 9038 // %2 = extractelement <2 x i32> %a, i32 1 9039 // %cond = icmp sgt i32 %1, %2 9040 // %3 = extractelement <2 x i32> %a, i32 0 9041 // %4 = extractelement <2 x i32> %a, i32 1 9042 // %select = select i1 %cond, i32 %3, i32 %4 9043 CmpInst::Predicate Pred; 9044 Instruction *L1; 9045 Instruction *L2; 9046 9047 Value *LHS = Select->getTrueValue(); 9048 Value *RHS = Select->getFalseValue(); 9049 Value *Cond = Select->getCondition(); 9050 9051 // TODO: Support inverse predicates. 9052 if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) { 9053 if (!isa<ExtractElementInst>(RHS) || 9054 !L2->isIdenticalTo(cast<Instruction>(RHS))) 9055 return RecurKind::None; 9056 } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) { 9057 if (!isa<ExtractElementInst>(LHS) || 9058 !L1->isIdenticalTo(cast<Instruction>(LHS))) 9059 return RecurKind::None; 9060 } else { 9061 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS)) 9062 return RecurKind::None; 9063 if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) || 9064 !L1->isIdenticalTo(cast<Instruction>(LHS)) || 9065 !L2->isIdenticalTo(cast<Instruction>(RHS))) 9066 return RecurKind::None; 9067 } 9068 9069 switch (Pred) { 9070 default: 9071 return RecurKind::None; 9072 case CmpInst::ICMP_SGT: 9073 case CmpInst::ICMP_SGE: 9074 return RecurKind::SMax; 9075 case CmpInst::ICMP_SLT: 9076 case CmpInst::ICMP_SLE: 9077 return RecurKind::SMin; 9078 case CmpInst::ICMP_UGT: 9079 case CmpInst::ICMP_UGE: 9080 return RecurKind::UMax; 9081 case CmpInst::ICMP_ULT: 9082 case CmpInst::ICMP_ULE: 9083 return RecurKind::UMin; 9084 } 9085 } 9086 return RecurKind::None; 9087 } 9088 9089 /// Get the index of the first operand. 9090 static unsigned getFirstOperandIndex(Instruction *I) { 9091 return isCmpSelMinMax(I) ? 1 : 0; 9092 } 9093 9094 /// Total number of operands in the reduction operation. 9095 static unsigned getNumberOfOperands(Instruction *I) { 9096 return isCmpSelMinMax(I) ? 3 : 2; 9097 } 9098 9099 /// Checks if the instruction is in basic block \p BB. 9100 /// For a cmp+sel min/max reduction check that both ops are in \p BB. 9101 static bool hasSameParent(Instruction *I, BasicBlock *BB) { 9102 if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) { 9103 auto *Sel = cast<SelectInst>(I); 9104 auto *Cmp = dyn_cast<Instruction>(Sel->getCondition()); 9105 return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB; 9106 } 9107 return I->getParent() == BB; 9108 } 9109 9110 /// Expected number of uses for reduction operations/reduced values. 9111 static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) { 9112 if (IsCmpSelMinMax) { 9113 // SelectInst must be used twice while the condition op must have single 9114 // use only. 9115 if (auto *Sel = dyn_cast<SelectInst>(I)) 9116 return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse(); 9117 return I->hasNUses(2); 9118 } 9119 9120 // Arithmetic reduction operation must be used once only. 9121 return I->hasOneUse(); 9122 } 9123 9124 /// Initializes the list of reduction operations. 9125 void initReductionOps(Instruction *I) { 9126 if (isCmpSelMinMax(I)) 9127 ReductionOps.assign(2, ReductionOpsType()); 9128 else 9129 ReductionOps.assign(1, ReductionOpsType()); 9130 } 9131 9132 /// Add all reduction operations for the reduction instruction \p I. 9133 void addReductionOps(Instruction *I) { 9134 if (isCmpSelMinMax(I)) { 9135 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition()); 9136 ReductionOps[1].emplace_back(I); 9137 } else { 9138 ReductionOps[0].emplace_back(I); 9139 } 9140 } 9141 9142 static Value *getLHS(RecurKind Kind, Instruction *I) { 9143 if (Kind == RecurKind::None) 9144 return nullptr; 9145 return I->getOperand(getFirstOperandIndex(I)); 9146 } 9147 static Value *getRHS(RecurKind Kind, Instruction *I) { 9148 if (Kind == RecurKind::None) 9149 return nullptr; 9150 return I->getOperand(getFirstOperandIndex(I) + 1); 9151 } 9152 9153 public: 9154 HorizontalReduction() = default; 9155 9156 /// Try to find a reduction tree. 9157 bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) { 9158 assert((!Phi || is_contained(Phi->operands(), Inst)) && 9159 "Phi needs to use the binary operator"); 9160 assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || 9161 isa<IntrinsicInst>(Inst)) && 9162 "Expected binop, select, or intrinsic for reduction matching"); 9163 RdxKind = getRdxKind(Inst); 9164 9165 // We could have a initial reductions that is not an add. 9166 // r *= v1 + v2 + v3 + v4 9167 // In such a case start looking for a tree rooted in the first '+'. 9168 if (Phi) { 9169 if (getLHS(RdxKind, Inst) == Phi) { 9170 Phi = nullptr; 9171 Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst)); 9172 if (!Inst) 9173 return false; 9174 RdxKind = getRdxKind(Inst); 9175 } else if (getRHS(RdxKind, Inst) == Phi) { 9176 Phi = nullptr; 9177 Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst)); 9178 if (!Inst) 9179 return false; 9180 RdxKind = getRdxKind(Inst); 9181 } 9182 } 9183 9184 if (!isVectorizable(RdxKind, Inst)) 9185 return false; 9186 9187 // Analyze "regular" integer/FP types for reductions - no target-specific 9188 // types or pointers. 9189 Type *Ty = Inst->getType(); 9190 if (!isValidElementType(Ty) || Ty->isPointerTy()) 9191 return false; 9192 9193 // Though the ultimate reduction may have multiple uses, its condition must 9194 // have only single use. 9195 if (auto *Sel = dyn_cast<SelectInst>(Inst)) 9196 if (!Sel->getCondition()->hasOneUse()) 9197 return false; 9198 9199 ReductionRoot = Inst; 9200 9201 // The opcode for leaf values that we perform a reduction on. 9202 // For example: load(x) + load(y) + load(z) + fptoui(w) 9203 // The leaf opcode for 'w' does not match, so we don't include it as a 9204 // potential candidate for the reduction. 9205 unsigned LeafOpcode = 0; 9206 9207 // Post-order traverse the reduction tree starting at Inst. We only handle 9208 // true trees containing binary operators or selects. 9209 SmallVector<std::pair<Instruction *, unsigned>, 32> Stack; 9210 Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst))); 9211 initReductionOps(Inst); 9212 while (!Stack.empty()) { 9213 Instruction *TreeN = Stack.back().first; 9214 unsigned EdgeToVisit = Stack.back().second++; 9215 const RecurKind TreeRdxKind = getRdxKind(TreeN); 9216 bool IsReducedValue = TreeRdxKind != RdxKind; 9217 9218 // Postorder visit. 9219 if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) { 9220 if (IsReducedValue) 9221 ReducedVals.push_back(TreeN); 9222 else { 9223 auto ExtraArgsIter = ExtraArgs.find(TreeN); 9224 if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) { 9225 // Check if TreeN is an extra argument of its parent operation. 9226 if (Stack.size() <= 1) { 9227 // TreeN can't be an extra argument as it is a root reduction 9228 // operation. 9229 return false; 9230 } 9231 // Yes, TreeN is an extra argument, do not add it to a list of 9232 // reduction operations. 9233 // Stack[Stack.size() - 2] always points to the parent operation. 9234 markExtraArg(Stack[Stack.size() - 2], TreeN); 9235 ExtraArgs.erase(TreeN); 9236 } else 9237 addReductionOps(TreeN); 9238 } 9239 // Retract. 9240 Stack.pop_back(); 9241 continue; 9242 } 9243 9244 // Visit operands. 9245 Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit); 9246 auto *EdgeInst = dyn_cast<Instruction>(EdgeVal); 9247 if (!EdgeInst) { 9248 // Edge value is not a reduction instruction or a leaf instruction. 9249 // (It may be a constant, function argument, or something else.) 9250 markExtraArg(Stack.back(), EdgeVal); 9251 continue; 9252 } 9253 RecurKind EdgeRdxKind = getRdxKind(EdgeInst); 9254 // Continue analysis if the next operand is a reduction operation or 9255 // (possibly) a leaf value. If the leaf value opcode is not set, 9256 // the first met operation != reduction operation is considered as the 9257 // leaf opcode. 9258 // Only handle trees in the current basic block. 9259 // Each tree node needs to have minimal number of users except for the 9260 // ultimate reduction. 9261 const bool IsRdxInst = EdgeRdxKind == RdxKind; 9262 if (EdgeInst != Phi && EdgeInst != Inst && 9263 hasSameParent(EdgeInst, Inst->getParent()) && 9264 hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) && 9265 (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) { 9266 if (IsRdxInst) { 9267 // We need to be able to reassociate the reduction operations. 9268 if (!isVectorizable(EdgeRdxKind, EdgeInst)) { 9269 // I is an extra argument for TreeN (its parent operation). 9270 markExtraArg(Stack.back(), EdgeInst); 9271 continue; 9272 } 9273 } else if (!LeafOpcode) { 9274 LeafOpcode = EdgeInst->getOpcode(); 9275 } 9276 Stack.push_back( 9277 std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst))); 9278 continue; 9279 } 9280 // I is an extra argument for TreeN (its parent operation). 9281 markExtraArg(Stack.back(), EdgeInst); 9282 } 9283 return true; 9284 } 9285 9286 /// Attempt to vectorize the tree found by matchAssociativeReduction. 9287 Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) { 9288 // If there are a sufficient number of reduction values, reduce 9289 // to a nearby power-of-2. We can safely generate oversized 9290 // vectors and rely on the backend to split them to legal sizes. 9291 unsigned NumReducedVals = ReducedVals.size(); 9292 if (NumReducedVals < 4) 9293 return nullptr; 9294 9295 // Intersect the fast-math-flags from all reduction operations. 9296 FastMathFlags RdxFMF; 9297 RdxFMF.set(); 9298 for (ReductionOpsType &RdxOp : ReductionOps) { 9299 for (Value *RdxVal : RdxOp) { 9300 if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal)) 9301 RdxFMF &= FPMO->getFastMathFlags(); 9302 } 9303 } 9304 9305 IRBuilder<> Builder(cast<Instruction>(ReductionRoot)); 9306 Builder.setFastMathFlags(RdxFMF); 9307 9308 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues; 9309 // The same extra argument may be used several times, so log each attempt 9310 // to use it. 9311 for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) { 9312 assert(Pair.first && "DebugLoc must be set."); 9313 ExternallyUsedValues[Pair.second].push_back(Pair.first); 9314 } 9315 9316 // The compare instruction of a min/max is the insertion point for new 9317 // instructions and may be replaced with a new compare instruction. 9318 auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) { 9319 assert(isa<SelectInst>(RdxRootInst) && 9320 "Expected min/max reduction to have select root instruction"); 9321 Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition(); 9322 assert(isa<Instruction>(ScalarCond) && 9323 "Expected min/max reduction to have compare condition"); 9324 return cast<Instruction>(ScalarCond); 9325 }; 9326 9327 // The reduction root is used as the insertion point for new instructions, 9328 // so set it as externally used to prevent it from being deleted. 9329 ExternallyUsedValues[ReductionRoot]; 9330 SmallVector<Value *, 16> IgnoreList; 9331 for (ReductionOpsType &RdxOp : ReductionOps) 9332 IgnoreList.append(RdxOp.begin(), RdxOp.end()); 9333 9334 unsigned ReduxWidth = PowerOf2Floor(NumReducedVals); 9335 if (NumReducedVals > ReduxWidth) { 9336 // In the loop below, we are building a tree based on a window of 9337 // 'ReduxWidth' values. 9338 // If the operands of those values have common traits (compare predicate, 9339 // constant operand, etc), then we want to group those together to 9340 // minimize the cost of the reduction. 9341 9342 // TODO: This should be extended to count common operands for 9343 // compares and binops. 9344 9345 // Step 1: Count the number of times each compare predicate occurs. 9346 SmallDenseMap<unsigned, unsigned> PredCountMap; 9347 for (Value *RdxVal : ReducedVals) { 9348 CmpInst::Predicate Pred; 9349 if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value()))) 9350 ++PredCountMap[Pred]; 9351 } 9352 // Step 2: Sort the values so the most common predicates come first. 9353 stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) { 9354 CmpInst::Predicate PredA, PredB; 9355 if (match(A, m_Cmp(PredA, m_Value(), m_Value())) && 9356 match(B, m_Cmp(PredB, m_Value(), m_Value()))) { 9357 return PredCountMap[PredA] > PredCountMap[PredB]; 9358 } 9359 return false; 9360 }); 9361 } 9362 9363 Value *VectorizedTree = nullptr; 9364 unsigned i = 0; 9365 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) { 9366 ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth); 9367 V.buildTree(VL, IgnoreList); 9368 if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) 9369 break; 9370 if (V.isLoadCombineReductionCandidate(RdxKind)) 9371 break; 9372 V.reorderTopToBottom(); 9373 V.reorderBottomToTop(/*IgnoreReorder=*/true); 9374 V.buildExternalUses(ExternallyUsedValues); 9375 9376 // For a poison-safe boolean logic reduction, do not replace select 9377 // instructions with logic ops. All reduced values will be frozen (see 9378 // below) to prevent leaking poison. 9379 if (isa<SelectInst>(ReductionRoot) && 9380 isBoolLogicOp(cast<Instruction>(ReductionRoot)) && 9381 NumReducedVals != ReduxWidth) 9382 break; 9383 9384 V.computeMinimumValueSizes(); 9385 9386 // Estimate cost. 9387 InstructionCost TreeCost = 9388 V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth)); 9389 InstructionCost ReductionCost = 9390 getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF); 9391 InstructionCost Cost = TreeCost + ReductionCost; 9392 if (!Cost.isValid()) { 9393 LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n"); 9394 return nullptr; 9395 } 9396 if (Cost >= -SLPCostThreshold) { 9397 V.getORE()->emit([&]() { 9398 return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial", 9399 cast<Instruction>(VL[0])) 9400 << "Vectorizing horizontal reduction is possible" 9401 << "but not beneficial with cost " << ore::NV("Cost", Cost) 9402 << " and threshold " 9403 << ore::NV("Threshold", -SLPCostThreshold); 9404 }); 9405 break; 9406 } 9407 9408 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" 9409 << Cost << ". (HorRdx)\n"); 9410 V.getORE()->emit([&]() { 9411 return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction", 9412 cast<Instruction>(VL[0])) 9413 << "Vectorized horizontal reduction with cost " 9414 << ore::NV("Cost", Cost) << " and with tree size " 9415 << ore::NV("TreeSize", V.getTreeSize()); 9416 }); 9417 9418 // Vectorize a tree. 9419 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc(); 9420 Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues); 9421 9422 // Emit a reduction. If the root is a select (min/max idiom), the insert 9423 // point is the compare condition of that select. 9424 Instruction *RdxRootInst = cast<Instruction>(ReductionRoot); 9425 if (isCmpSelMinMax(RdxRootInst)) 9426 Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst)); 9427 else 9428 Builder.SetInsertPoint(RdxRootInst); 9429 9430 // To prevent poison from leaking across what used to be sequential, safe, 9431 // scalar boolean logic operations, the reduction operand must be frozen. 9432 if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst)) 9433 VectorizedRoot = Builder.CreateFreeze(VectorizedRoot); 9434 9435 Value *ReducedSubTree = 9436 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI); 9437 9438 if (!VectorizedTree) { 9439 // Initialize the final value in the reduction. 9440 VectorizedTree = ReducedSubTree; 9441 } else { 9442 // Update the final value in the reduction. 9443 Builder.SetCurrentDebugLocation(Loc); 9444 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 9445 ReducedSubTree, "op.rdx", ReductionOps); 9446 } 9447 i += ReduxWidth; 9448 ReduxWidth = PowerOf2Floor(NumReducedVals - i); 9449 } 9450 9451 if (VectorizedTree) { 9452 // Finish the reduction. 9453 for (; i < NumReducedVals; ++i) { 9454 auto *I = cast<Instruction>(ReducedVals[i]); 9455 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 9456 VectorizedTree = 9457 createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps); 9458 } 9459 for (auto &Pair : ExternallyUsedValues) { 9460 // Add each externally used value to the final reduction. 9461 for (auto *I : Pair.second) { 9462 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 9463 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 9464 Pair.first, "op.extra", I); 9465 } 9466 } 9467 9468 ReductionRoot->replaceAllUsesWith(VectorizedTree); 9469 9470 // Mark all scalar reduction ops for deletion, they are replaced by the 9471 // vector reductions. 9472 V.eraseInstructions(IgnoreList); 9473 } 9474 return VectorizedTree; 9475 } 9476 9477 unsigned numReductionValues() const { return ReducedVals.size(); } 9478 9479 private: 9480 /// Calculate the cost of a reduction. 9481 InstructionCost getReductionCost(TargetTransformInfo *TTI, 9482 Value *FirstReducedVal, unsigned ReduxWidth, 9483 FastMathFlags FMF) { 9484 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 9485 Type *ScalarTy = FirstReducedVal->getType(); 9486 FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth); 9487 InstructionCost VectorCost, ScalarCost; 9488 switch (RdxKind) { 9489 case RecurKind::Add: 9490 case RecurKind::Mul: 9491 case RecurKind::Or: 9492 case RecurKind::And: 9493 case RecurKind::Xor: 9494 case RecurKind::FAdd: 9495 case RecurKind::FMul: { 9496 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind); 9497 VectorCost = 9498 TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind); 9499 ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind); 9500 break; 9501 } 9502 case RecurKind::FMax: 9503 case RecurKind::FMin: { 9504 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 9505 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 9506 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, 9507 /*IsUnsigned=*/false, CostKind); 9508 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 9509 ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy, 9510 SclCondTy, RdxPred, CostKind) + 9511 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 9512 SclCondTy, RdxPred, CostKind); 9513 break; 9514 } 9515 case RecurKind::SMax: 9516 case RecurKind::SMin: 9517 case RecurKind::UMax: 9518 case RecurKind::UMin: { 9519 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 9520 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 9521 bool IsUnsigned = 9522 RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin; 9523 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned, 9524 CostKind); 9525 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 9526 ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy, 9527 SclCondTy, RdxPred, CostKind) + 9528 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 9529 SclCondTy, RdxPred, CostKind); 9530 break; 9531 } 9532 default: 9533 llvm_unreachable("Expected arithmetic or min/max reduction operation"); 9534 } 9535 9536 // Scalar cost is repeated for N-1 elements. 9537 ScalarCost *= (ReduxWidth - 1); 9538 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost 9539 << " for reduction that starts with " << *FirstReducedVal 9540 << " (It is a splitting reduction)\n"); 9541 return VectorCost - ScalarCost; 9542 } 9543 9544 /// Emit a horizontal reduction of the vectorized value. 9545 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder, 9546 unsigned ReduxWidth, const TargetTransformInfo *TTI) { 9547 assert(VectorizedValue && "Need to have a vectorized tree node"); 9548 assert(isPowerOf2_32(ReduxWidth) && 9549 "We only handle power-of-two reductions for now"); 9550 assert(RdxKind != RecurKind::FMulAdd && 9551 "A call to the llvm.fmuladd intrinsic is not handled yet"); 9552 9553 ++NumVectorInstructions; 9554 return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind); 9555 } 9556 }; 9557 9558 } // end anonymous namespace 9559 9560 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) { 9561 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) 9562 return cast<FixedVectorType>(IE->getType())->getNumElements(); 9563 9564 unsigned AggregateSize = 1; 9565 auto *IV = cast<InsertValueInst>(InsertInst); 9566 Type *CurrentType = IV->getType(); 9567 do { 9568 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 9569 for (auto *Elt : ST->elements()) 9570 if (Elt != ST->getElementType(0)) // check homogeneity 9571 return None; 9572 AggregateSize *= ST->getNumElements(); 9573 CurrentType = ST->getElementType(0); 9574 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 9575 AggregateSize *= AT->getNumElements(); 9576 CurrentType = AT->getElementType(); 9577 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) { 9578 AggregateSize *= VT->getNumElements(); 9579 return AggregateSize; 9580 } else if (CurrentType->isSingleValueType()) { 9581 return AggregateSize; 9582 } else { 9583 return None; 9584 } 9585 } while (true); 9586 } 9587 9588 static void findBuildAggregate_rec(Instruction *LastInsertInst, 9589 TargetTransformInfo *TTI, 9590 SmallVectorImpl<Value *> &BuildVectorOpds, 9591 SmallVectorImpl<Value *> &InsertElts, 9592 unsigned OperandOffset) { 9593 do { 9594 Value *InsertedOperand = LastInsertInst->getOperand(1); 9595 Optional<unsigned> OperandIndex = 9596 getInsertIndex(LastInsertInst, OperandOffset); 9597 if (!OperandIndex) 9598 return; 9599 if (isa<InsertElementInst>(InsertedOperand) || 9600 isa<InsertValueInst>(InsertedOperand)) { 9601 findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI, 9602 BuildVectorOpds, InsertElts, *OperandIndex); 9603 9604 } else { 9605 BuildVectorOpds[*OperandIndex] = InsertedOperand; 9606 InsertElts[*OperandIndex] = LastInsertInst; 9607 } 9608 LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0)); 9609 } while (LastInsertInst != nullptr && 9610 (isa<InsertValueInst>(LastInsertInst) || 9611 isa<InsertElementInst>(LastInsertInst)) && 9612 LastInsertInst->hasOneUse()); 9613 } 9614 9615 /// Recognize construction of vectors like 9616 /// %ra = insertelement <4 x float> poison, float %s0, i32 0 9617 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1 9618 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2 9619 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3 9620 /// starting from the last insertelement or insertvalue instruction. 9621 /// 9622 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>}, 9623 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on. 9624 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples. 9625 /// 9626 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type. 9627 /// 9628 /// \return true if it matches. 9629 static bool findBuildAggregate(Instruction *LastInsertInst, 9630 TargetTransformInfo *TTI, 9631 SmallVectorImpl<Value *> &BuildVectorOpds, 9632 SmallVectorImpl<Value *> &InsertElts) { 9633 9634 assert((isa<InsertElementInst>(LastInsertInst) || 9635 isa<InsertValueInst>(LastInsertInst)) && 9636 "Expected insertelement or insertvalue instruction!"); 9637 9638 assert((BuildVectorOpds.empty() && InsertElts.empty()) && 9639 "Expected empty result vectors!"); 9640 9641 Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst); 9642 if (!AggregateSize) 9643 return false; 9644 BuildVectorOpds.resize(*AggregateSize); 9645 InsertElts.resize(*AggregateSize); 9646 9647 findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0); 9648 llvm::erase_value(BuildVectorOpds, nullptr); 9649 llvm::erase_value(InsertElts, nullptr); 9650 if (BuildVectorOpds.size() >= 2) 9651 return true; 9652 9653 return false; 9654 } 9655 9656 /// Try and get a reduction value from a phi node. 9657 /// 9658 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions 9659 /// if they come from either \p ParentBB or a containing loop latch. 9660 /// 9661 /// \returns A candidate reduction value if possible, or \code nullptr \endcode 9662 /// if not possible. 9663 static Value *getReductionValue(const DominatorTree *DT, PHINode *P, 9664 BasicBlock *ParentBB, LoopInfo *LI) { 9665 // There are situations where the reduction value is not dominated by the 9666 // reduction phi. Vectorizing such cases has been reported to cause 9667 // miscompiles. See PR25787. 9668 auto DominatedReduxValue = [&](Value *R) { 9669 return isa<Instruction>(R) && 9670 DT->dominates(P->getParent(), cast<Instruction>(R)->getParent()); 9671 }; 9672 9673 Value *Rdx = nullptr; 9674 9675 // Return the incoming value if it comes from the same BB as the phi node. 9676 if (P->getIncomingBlock(0) == ParentBB) { 9677 Rdx = P->getIncomingValue(0); 9678 } else if (P->getIncomingBlock(1) == ParentBB) { 9679 Rdx = P->getIncomingValue(1); 9680 } 9681 9682 if (Rdx && DominatedReduxValue(Rdx)) 9683 return Rdx; 9684 9685 // Otherwise, check whether we have a loop latch to look at. 9686 Loop *BBL = LI->getLoopFor(ParentBB); 9687 if (!BBL) 9688 return nullptr; 9689 BasicBlock *BBLatch = BBL->getLoopLatch(); 9690 if (!BBLatch) 9691 return nullptr; 9692 9693 // There is a loop latch, return the incoming value if it comes from 9694 // that. This reduction pattern occasionally turns up. 9695 if (P->getIncomingBlock(0) == BBLatch) { 9696 Rdx = P->getIncomingValue(0); 9697 } else if (P->getIncomingBlock(1) == BBLatch) { 9698 Rdx = P->getIncomingValue(1); 9699 } 9700 9701 if (Rdx && DominatedReduxValue(Rdx)) 9702 return Rdx; 9703 9704 return nullptr; 9705 } 9706 9707 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) { 9708 if (match(I, m_BinOp(m_Value(V0), m_Value(V1)))) 9709 return true; 9710 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1)))) 9711 return true; 9712 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1)))) 9713 return true; 9714 if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1)))) 9715 return true; 9716 if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1)))) 9717 return true; 9718 if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1)))) 9719 return true; 9720 if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1)))) 9721 return true; 9722 return false; 9723 } 9724 9725 /// Attempt to reduce a horizontal reduction. 9726 /// If it is legal to match a horizontal reduction feeding the phi node \a P 9727 /// with reduction operators \a Root (or one of its operands) in a basic block 9728 /// \a BB, then check if it can be done. If horizontal reduction is not found 9729 /// and root instruction is a binary operation, vectorization of the operands is 9730 /// attempted. 9731 /// \returns true if a horizontal reduction was matched and reduced or operands 9732 /// of one of the binary instruction were vectorized. 9733 /// \returns false if a horizontal reduction was not matched (or not possible) 9734 /// or no vectorization of any binary operation feeding \a Root instruction was 9735 /// performed. 9736 static bool tryToVectorizeHorReductionOrInstOperands( 9737 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, 9738 TargetTransformInfo *TTI, 9739 const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) { 9740 if (!ShouldVectorizeHor) 9741 return false; 9742 9743 if (!Root) 9744 return false; 9745 9746 if (Root->getParent() != BB || isa<PHINode>(Root)) 9747 return false; 9748 // Start analysis starting from Root instruction. If horizontal reduction is 9749 // found, try to vectorize it. If it is not a horizontal reduction or 9750 // vectorization is not possible or not effective, and currently analyzed 9751 // instruction is a binary operation, try to vectorize the operands, using 9752 // pre-order DFS traversal order. If the operands were not vectorized, repeat 9753 // the same procedure considering each operand as a possible root of the 9754 // horizontal reduction. 9755 // Interrupt the process if the Root instruction itself was vectorized or all 9756 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized. 9757 // Skip the analysis of CmpInsts.Compiler implements postanalysis of the 9758 // CmpInsts so we can skip extra attempts in 9759 // tryToVectorizeHorReductionOrInstOperands and save compile time. 9760 std::queue<std::pair<Instruction *, unsigned>> Stack; 9761 Stack.emplace(Root, 0); 9762 SmallPtrSet<Value *, 8> VisitedInstrs; 9763 SmallVector<WeakTrackingVH> PostponedInsts; 9764 bool Res = false; 9765 auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0, 9766 Value *&B1) -> Value * { 9767 bool IsBinop = matchRdxBop(Inst, B0, B1); 9768 bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value())); 9769 if (IsBinop || IsSelect) { 9770 HorizontalReduction HorRdx; 9771 if (HorRdx.matchAssociativeReduction(P, Inst)) 9772 return HorRdx.tryToReduce(R, TTI); 9773 } 9774 return nullptr; 9775 }; 9776 while (!Stack.empty()) { 9777 Instruction *Inst; 9778 unsigned Level; 9779 std::tie(Inst, Level) = Stack.front(); 9780 Stack.pop(); 9781 // Do not try to analyze instruction that has already been vectorized. 9782 // This may happen when we vectorize instruction operands on a previous 9783 // iteration while stack was populated before that happened. 9784 if (R.isDeleted(Inst)) 9785 continue; 9786 Value *B0 = nullptr, *B1 = nullptr; 9787 if (Value *V = TryToReduce(Inst, B0, B1)) { 9788 Res = true; 9789 // Set P to nullptr to avoid re-analysis of phi node in 9790 // matchAssociativeReduction function unless this is the root node. 9791 P = nullptr; 9792 if (auto *I = dyn_cast<Instruction>(V)) { 9793 // Try to find another reduction. 9794 Stack.emplace(I, Level); 9795 continue; 9796 } 9797 } else { 9798 bool IsBinop = B0 && B1; 9799 if (P && IsBinop) { 9800 Inst = dyn_cast<Instruction>(B0); 9801 if (Inst == P) 9802 Inst = dyn_cast<Instruction>(B1); 9803 if (!Inst) { 9804 // Set P to nullptr to avoid re-analysis of phi node in 9805 // matchAssociativeReduction function unless this is the root node. 9806 P = nullptr; 9807 continue; 9808 } 9809 } 9810 // Set P to nullptr to avoid re-analysis of phi node in 9811 // matchAssociativeReduction function unless this is the root node. 9812 P = nullptr; 9813 // Do not try to vectorize CmpInst operands, this is done separately. 9814 // Final attempt for binop args vectorization should happen after the loop 9815 // to try to find reductions. 9816 if (!isa<CmpInst>(Inst)) 9817 PostponedInsts.push_back(Inst); 9818 } 9819 9820 // Try to vectorize operands. 9821 // Continue analysis for the instruction from the same basic block only to 9822 // save compile time. 9823 if (++Level < RecursionMaxDepth) 9824 for (auto *Op : Inst->operand_values()) 9825 if (VisitedInstrs.insert(Op).second) 9826 if (auto *I = dyn_cast<Instruction>(Op)) 9827 // Do not try to vectorize CmpInst operands, this is done 9828 // separately. 9829 if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) && 9830 I->getParent() == BB) 9831 Stack.emplace(I, Level); 9832 } 9833 // Try to vectorized binops where reductions were not found. 9834 for (Value *V : PostponedInsts) 9835 if (auto *Inst = dyn_cast<Instruction>(V)) 9836 if (!R.isDeleted(Inst)) 9837 Res |= Vectorize(Inst, R); 9838 return Res; 9839 } 9840 9841 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V, 9842 BasicBlock *BB, BoUpSLP &R, 9843 TargetTransformInfo *TTI) { 9844 auto *I = dyn_cast_or_null<Instruction>(V); 9845 if (!I) 9846 return false; 9847 9848 if (!isa<BinaryOperator>(I)) 9849 P = nullptr; 9850 // Try to match and vectorize a horizontal reduction. 9851 auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool { 9852 return tryToVectorize(I, R); 9853 }; 9854 return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, 9855 ExtraVectorization); 9856 } 9857 9858 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI, 9859 BasicBlock *BB, BoUpSLP &R) { 9860 const DataLayout &DL = BB->getModule()->getDataLayout(); 9861 if (!R.canMapToVector(IVI->getType(), DL)) 9862 return false; 9863 9864 SmallVector<Value *, 16> BuildVectorOpds; 9865 SmallVector<Value *, 16> BuildVectorInsts; 9866 if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts)) 9867 return false; 9868 9869 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n"); 9870 // Aggregate value is unlikely to be processed in vector register. 9871 return tryToVectorizeList(BuildVectorOpds, R); 9872 } 9873 9874 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI, 9875 BasicBlock *BB, BoUpSLP &R) { 9876 SmallVector<Value *, 16> BuildVectorInsts; 9877 SmallVector<Value *, 16> BuildVectorOpds; 9878 SmallVector<int> Mask; 9879 if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) || 9880 (llvm::all_of( 9881 BuildVectorOpds, 9882 [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) && 9883 isFixedVectorShuffle(BuildVectorOpds, Mask))) 9884 return false; 9885 9886 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n"); 9887 return tryToVectorizeList(BuildVectorInsts, R); 9888 } 9889 9890 template <typename T> 9891 static bool 9892 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming, 9893 function_ref<unsigned(T *)> Limit, 9894 function_ref<bool(T *, T *)> Comparator, 9895 function_ref<bool(T *, T *)> AreCompatible, 9896 function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper, 9897 bool LimitForRegisterSize) { 9898 bool Changed = false; 9899 // Sort by type, parent, operands. 9900 stable_sort(Incoming, Comparator); 9901 9902 // Try to vectorize elements base on their type. 9903 SmallVector<T *> Candidates; 9904 for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) { 9905 // Look for the next elements with the same type, parent and operand 9906 // kinds. 9907 auto *SameTypeIt = IncIt; 9908 while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt)) 9909 ++SameTypeIt; 9910 9911 // Try to vectorize them. 9912 unsigned NumElts = (SameTypeIt - IncIt); 9913 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes (" 9914 << NumElts << ")\n"); 9915 // The vectorization is a 3-state attempt: 9916 // 1. Try to vectorize instructions with the same/alternate opcodes with the 9917 // size of maximal register at first. 9918 // 2. Try to vectorize remaining instructions with the same type, if 9919 // possible. This may result in the better vectorization results rather than 9920 // if we try just to vectorize instructions with the same/alternate opcodes. 9921 // 3. Final attempt to try to vectorize all instructions with the 9922 // same/alternate ops only, this may result in some extra final 9923 // vectorization. 9924 if (NumElts > 1 && 9925 TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) { 9926 // Success start over because instructions might have been changed. 9927 Changed = true; 9928 } else if (NumElts < Limit(*IncIt) && 9929 (Candidates.empty() || 9930 Candidates.front()->getType() == (*IncIt)->getType())) { 9931 Candidates.append(IncIt, std::next(IncIt, NumElts)); 9932 } 9933 // Final attempt to vectorize instructions with the same types. 9934 if (Candidates.size() > 1 && 9935 (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) { 9936 if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) { 9937 // Success start over because instructions might have been changed. 9938 Changed = true; 9939 } else if (LimitForRegisterSize) { 9940 // Try to vectorize using small vectors. 9941 for (auto *It = Candidates.begin(), *End = Candidates.end(); 9942 It != End;) { 9943 auto *SameTypeIt = It; 9944 while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It)) 9945 ++SameTypeIt; 9946 unsigned NumElts = (SameTypeIt - It); 9947 if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts), 9948 /*LimitForRegisterSize=*/false)) 9949 Changed = true; 9950 It = SameTypeIt; 9951 } 9952 } 9953 Candidates.clear(); 9954 } 9955 9956 // Start over at the next instruction of a different type (or the end). 9957 IncIt = SameTypeIt; 9958 } 9959 return Changed; 9960 } 9961 9962 /// Compare two cmp instructions. If IsCompatibility is true, function returns 9963 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding 9964 /// operands. If IsCompatibility is false, function implements strict weak 9965 /// ordering relation between two cmp instructions, returning true if the first 9966 /// instruction is "less" than the second, i.e. its predicate is less than the 9967 /// predicate of the second or the operands IDs are less than the operands IDs 9968 /// of the second cmp instruction. 9969 template <bool IsCompatibility> 9970 static bool compareCmp(Value *V, Value *V2, 9971 function_ref<bool(Instruction *)> IsDeleted) { 9972 auto *CI1 = cast<CmpInst>(V); 9973 auto *CI2 = cast<CmpInst>(V2); 9974 if (IsDeleted(CI2) || !isValidElementType(CI2->getType())) 9975 return false; 9976 if (CI1->getOperand(0)->getType()->getTypeID() < 9977 CI2->getOperand(0)->getType()->getTypeID()) 9978 return !IsCompatibility; 9979 if (CI1->getOperand(0)->getType()->getTypeID() > 9980 CI2->getOperand(0)->getType()->getTypeID()) 9981 return false; 9982 CmpInst::Predicate Pred1 = CI1->getPredicate(); 9983 CmpInst::Predicate Pred2 = CI2->getPredicate(); 9984 CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1); 9985 CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2); 9986 CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1); 9987 CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2); 9988 if (BasePred1 < BasePred2) 9989 return !IsCompatibility; 9990 if (BasePred1 > BasePred2) 9991 return false; 9992 // Compare operands. 9993 bool LEPreds = Pred1 <= Pred2; 9994 bool GEPreds = Pred1 >= Pred2; 9995 for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) { 9996 auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1); 9997 auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1); 9998 if (Op1->getValueID() < Op2->getValueID()) 9999 return !IsCompatibility; 10000 if (Op1->getValueID() > Op2->getValueID()) 10001 return false; 10002 if (auto *I1 = dyn_cast<Instruction>(Op1)) 10003 if (auto *I2 = dyn_cast<Instruction>(Op2)) { 10004 if (I1->getParent() != I2->getParent()) 10005 return false; 10006 InstructionsState S = getSameOpcode({I1, I2}); 10007 if (S.getOpcode()) 10008 continue; 10009 return false; 10010 } 10011 } 10012 return IsCompatibility; 10013 } 10014 10015 bool SLPVectorizerPass::vectorizeSimpleInstructions( 10016 SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R, 10017 bool AtTerminator) { 10018 bool OpsChanged = false; 10019 SmallVector<Instruction *, 4> PostponedCmps; 10020 for (auto *I : reverse(Instructions)) { 10021 if (R.isDeleted(I)) 10022 continue; 10023 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) 10024 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R); 10025 else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) 10026 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R); 10027 else if (isa<CmpInst>(I)) 10028 PostponedCmps.push_back(I); 10029 } 10030 if (AtTerminator) { 10031 // Try to find reductions first. 10032 for (Instruction *I : PostponedCmps) { 10033 if (R.isDeleted(I)) 10034 continue; 10035 for (Value *Op : I->operands()) 10036 OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI); 10037 } 10038 // Try to vectorize operands as vector bundles. 10039 for (Instruction *I : PostponedCmps) { 10040 if (R.isDeleted(I)) 10041 continue; 10042 OpsChanged |= tryToVectorize(I, R); 10043 } 10044 // Try to vectorize list of compares. 10045 // Sort by type, compare predicate, etc. 10046 auto &&CompareSorter = [&R](Value *V, Value *V2) { 10047 return compareCmp<false>(V, V2, 10048 [&R](Instruction *I) { return R.isDeleted(I); }); 10049 }; 10050 10051 auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) { 10052 if (V1 == V2) 10053 return true; 10054 return compareCmp<true>(V1, V2, 10055 [&R](Instruction *I) { return R.isDeleted(I); }); 10056 }; 10057 auto Limit = [&R](Value *V) { 10058 unsigned EltSize = R.getVectorElementSize(V); 10059 return std::max(2U, R.getMaxVecRegSize() / EltSize); 10060 }; 10061 10062 SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end()); 10063 OpsChanged |= tryToVectorizeSequence<Value>( 10064 Vals, Limit, CompareSorter, AreCompatibleCompares, 10065 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 10066 // Exclude possible reductions from other blocks. 10067 bool ArePossiblyReducedInOtherBlock = 10068 any_of(Candidates, [](Value *V) { 10069 return any_of(V->users(), [V](User *U) { 10070 return isa<SelectInst>(U) && 10071 cast<SelectInst>(U)->getParent() != 10072 cast<Instruction>(V)->getParent(); 10073 }); 10074 }); 10075 if (ArePossiblyReducedInOtherBlock) 10076 return false; 10077 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 10078 }, 10079 /*LimitForRegisterSize=*/true); 10080 Instructions.clear(); 10081 } else { 10082 // Insert in reverse order since the PostponedCmps vector was filled in 10083 // reverse order. 10084 Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend()); 10085 } 10086 return OpsChanged; 10087 } 10088 10089 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { 10090 bool Changed = false; 10091 SmallVector<Value *, 4> Incoming; 10092 SmallPtrSet<Value *, 16> VisitedInstrs; 10093 // Maps phi nodes to the non-phi nodes found in the use tree for each phi 10094 // node. Allows better to identify the chains that can be vectorized in the 10095 // better way. 10096 DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes; 10097 auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) { 10098 assert(isValidElementType(V1->getType()) && 10099 isValidElementType(V2->getType()) && 10100 "Expected vectorizable types only."); 10101 // It is fine to compare type IDs here, since we expect only vectorizable 10102 // types, like ints, floats and pointers, we don't care about other type. 10103 if (V1->getType()->getTypeID() < V2->getType()->getTypeID()) 10104 return true; 10105 if (V1->getType()->getTypeID() > V2->getType()->getTypeID()) 10106 return false; 10107 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 10108 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 10109 if (Opcodes1.size() < Opcodes2.size()) 10110 return true; 10111 if (Opcodes1.size() > Opcodes2.size()) 10112 return false; 10113 Optional<bool> ConstOrder; 10114 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 10115 // Undefs are compatible with any other value. 10116 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) { 10117 if (!ConstOrder) 10118 ConstOrder = 10119 !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]); 10120 continue; 10121 } 10122 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 10123 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 10124 DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent()); 10125 DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent()); 10126 if (!NodeI1) 10127 return NodeI2 != nullptr; 10128 if (!NodeI2) 10129 return false; 10130 assert((NodeI1 == NodeI2) == 10131 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 10132 "Different nodes should have different DFS numbers"); 10133 if (NodeI1 != NodeI2) 10134 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 10135 InstructionsState S = getSameOpcode({I1, I2}); 10136 if (S.getOpcode()) 10137 continue; 10138 return I1->getOpcode() < I2->getOpcode(); 10139 } 10140 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) { 10141 if (!ConstOrder) 10142 ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID(); 10143 continue; 10144 } 10145 if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID()) 10146 return true; 10147 if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID()) 10148 return false; 10149 } 10150 return ConstOrder && *ConstOrder; 10151 }; 10152 auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) { 10153 if (V1 == V2) 10154 return true; 10155 if (V1->getType() != V2->getType()) 10156 return false; 10157 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 10158 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 10159 if (Opcodes1.size() != Opcodes2.size()) 10160 return false; 10161 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 10162 // Undefs are compatible with any other value. 10163 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) 10164 continue; 10165 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 10166 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 10167 if (I1->getParent() != I2->getParent()) 10168 return false; 10169 InstructionsState S = getSameOpcode({I1, I2}); 10170 if (S.getOpcode()) 10171 continue; 10172 return false; 10173 } 10174 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) 10175 continue; 10176 if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID()) 10177 return false; 10178 } 10179 return true; 10180 }; 10181 auto Limit = [&R](Value *V) { 10182 unsigned EltSize = R.getVectorElementSize(V); 10183 return std::max(2U, R.getMaxVecRegSize() / EltSize); 10184 }; 10185 10186 bool HaveVectorizedPhiNodes = false; 10187 do { 10188 // Collect the incoming values from the PHIs. 10189 Incoming.clear(); 10190 for (Instruction &I : *BB) { 10191 PHINode *P = dyn_cast<PHINode>(&I); 10192 if (!P) 10193 break; 10194 10195 // No need to analyze deleted, vectorized and non-vectorizable 10196 // instructions. 10197 if (!VisitedInstrs.count(P) && !R.isDeleted(P) && 10198 isValidElementType(P->getType())) 10199 Incoming.push_back(P); 10200 } 10201 10202 // Find the corresponding non-phi nodes for better matching when trying to 10203 // build the tree. 10204 for (Value *V : Incoming) { 10205 SmallVectorImpl<Value *> &Opcodes = 10206 PHIToOpcodes.try_emplace(V).first->getSecond(); 10207 if (!Opcodes.empty()) 10208 continue; 10209 SmallVector<Value *, 4> Nodes(1, V); 10210 SmallPtrSet<Value *, 4> Visited; 10211 while (!Nodes.empty()) { 10212 auto *PHI = cast<PHINode>(Nodes.pop_back_val()); 10213 if (!Visited.insert(PHI).second) 10214 continue; 10215 for (Value *V : PHI->incoming_values()) { 10216 if (auto *PHI1 = dyn_cast<PHINode>((V))) { 10217 Nodes.push_back(PHI1); 10218 continue; 10219 } 10220 Opcodes.emplace_back(V); 10221 } 10222 } 10223 } 10224 10225 HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>( 10226 Incoming, Limit, PHICompare, AreCompatiblePHIs, 10227 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 10228 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 10229 }, 10230 /*LimitForRegisterSize=*/true); 10231 Changed |= HaveVectorizedPhiNodes; 10232 VisitedInstrs.insert(Incoming.begin(), Incoming.end()); 10233 } while (HaveVectorizedPhiNodes); 10234 10235 VisitedInstrs.clear(); 10236 10237 SmallVector<Instruction *, 8> PostProcessInstructions; 10238 SmallDenseSet<Instruction *, 4> KeyNodes; 10239 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 10240 // Skip instructions with scalable type. The num of elements is unknown at 10241 // compile-time for scalable type. 10242 if (isa<ScalableVectorType>(it->getType())) 10243 continue; 10244 10245 // Skip instructions marked for the deletion. 10246 if (R.isDeleted(&*it)) 10247 continue; 10248 // We may go through BB multiple times so skip the one we have checked. 10249 if (!VisitedInstrs.insert(&*it).second) { 10250 if (it->use_empty() && KeyNodes.contains(&*it) && 10251 vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 10252 it->isTerminator())) { 10253 // We would like to start over since some instructions are deleted 10254 // and the iterator may become invalid value. 10255 Changed = true; 10256 it = BB->begin(); 10257 e = BB->end(); 10258 } 10259 continue; 10260 } 10261 10262 if (isa<DbgInfoIntrinsic>(it)) 10263 continue; 10264 10265 // Try to vectorize reductions that use PHINodes. 10266 if (PHINode *P = dyn_cast<PHINode>(it)) { 10267 // Check that the PHI is a reduction PHI. 10268 if (P->getNumIncomingValues() == 2) { 10269 // Try to match and vectorize a horizontal reduction. 10270 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R, 10271 TTI)) { 10272 Changed = true; 10273 it = BB->begin(); 10274 e = BB->end(); 10275 continue; 10276 } 10277 } 10278 // Try to vectorize the incoming values of the PHI, to catch reductions 10279 // that feed into PHIs. 10280 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) { 10281 // Skip if the incoming block is the current BB for now. Also, bypass 10282 // unreachable IR for efficiency and to avoid crashing. 10283 // TODO: Collect the skipped incoming values and try to vectorize them 10284 // after processing BB. 10285 if (BB == P->getIncomingBlock(I) || 10286 !DT->isReachableFromEntry(P->getIncomingBlock(I))) 10287 continue; 10288 10289 Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I), 10290 P->getIncomingBlock(I), R, TTI); 10291 } 10292 continue; 10293 } 10294 10295 // Ran into an instruction without users, like terminator, or function call 10296 // with ignored return value, store. Ignore unused instructions (basing on 10297 // instruction type, except for CallInst and InvokeInst). 10298 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) || 10299 isa<InvokeInst>(it))) { 10300 KeyNodes.insert(&*it); 10301 bool OpsChanged = false; 10302 if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) { 10303 for (auto *V : it->operand_values()) { 10304 // Try to match and vectorize a horizontal reduction. 10305 OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI); 10306 } 10307 } 10308 // Start vectorization of post-process list of instructions from the 10309 // top-tree instructions to try to vectorize as many instructions as 10310 // possible. 10311 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 10312 it->isTerminator()); 10313 if (OpsChanged) { 10314 // We would like to start over since some instructions are deleted 10315 // and the iterator may become invalid value. 10316 Changed = true; 10317 it = BB->begin(); 10318 e = BB->end(); 10319 continue; 10320 } 10321 } 10322 10323 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) || 10324 isa<InsertValueInst>(it)) 10325 PostProcessInstructions.push_back(&*it); 10326 } 10327 10328 return Changed; 10329 } 10330 10331 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) { 10332 auto Changed = false; 10333 for (auto &Entry : GEPs) { 10334 // If the getelementptr list has fewer than two elements, there's nothing 10335 // to do. 10336 if (Entry.second.size() < 2) 10337 continue; 10338 10339 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length " 10340 << Entry.second.size() << ".\n"); 10341 10342 // Process the GEP list in chunks suitable for the target's supported 10343 // vector size. If a vector register can't hold 1 element, we are done. We 10344 // are trying to vectorize the index computations, so the maximum number of 10345 // elements is based on the size of the index expression, rather than the 10346 // size of the GEP itself (the target's pointer size). 10347 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 10348 unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin()); 10349 if (MaxVecRegSize < EltSize) 10350 continue; 10351 10352 unsigned MaxElts = MaxVecRegSize / EltSize; 10353 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) { 10354 auto Len = std::min<unsigned>(BE - BI, MaxElts); 10355 ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len); 10356 10357 // Initialize a set a candidate getelementptrs. Note that we use a 10358 // SetVector here to preserve program order. If the index computations 10359 // are vectorizable and begin with loads, we want to minimize the chance 10360 // of having to reorder them later. 10361 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end()); 10362 10363 // Some of the candidates may have already been vectorized after we 10364 // initially collected them. If so, they are marked as deleted, so remove 10365 // them from the set of candidates. 10366 Candidates.remove_if( 10367 [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); }); 10368 10369 // Remove from the set of candidates all pairs of getelementptrs with 10370 // constant differences. Such getelementptrs are likely not good 10371 // candidates for vectorization in a bottom-up phase since one can be 10372 // computed from the other. We also ensure all candidate getelementptr 10373 // indices are unique. 10374 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) { 10375 auto *GEPI = GEPList[I]; 10376 if (!Candidates.count(GEPI)) 10377 continue; 10378 auto *SCEVI = SE->getSCEV(GEPList[I]); 10379 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) { 10380 auto *GEPJ = GEPList[J]; 10381 auto *SCEVJ = SE->getSCEV(GEPList[J]); 10382 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) { 10383 Candidates.remove(GEPI); 10384 Candidates.remove(GEPJ); 10385 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) { 10386 Candidates.remove(GEPJ); 10387 } 10388 } 10389 } 10390 10391 // We break out of the above computation as soon as we know there are 10392 // fewer than two candidates remaining. 10393 if (Candidates.size() < 2) 10394 continue; 10395 10396 // Add the single, non-constant index of each candidate to the bundle. We 10397 // ensured the indices met these constraints when we originally collected 10398 // the getelementptrs. 10399 SmallVector<Value *, 16> Bundle(Candidates.size()); 10400 auto BundleIndex = 0u; 10401 for (auto *V : Candidates) { 10402 auto *GEP = cast<GetElementPtrInst>(V); 10403 auto *GEPIdx = GEP->idx_begin()->get(); 10404 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)); 10405 Bundle[BundleIndex++] = GEPIdx; 10406 } 10407 10408 // Try and vectorize the indices. We are currently only interested in 10409 // gather-like cases of the form: 10410 // 10411 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ... 10412 // 10413 // where the loads of "a", the loads of "b", and the subtractions can be 10414 // performed in parallel. It's likely that detecting this pattern in a 10415 // bottom-up phase will be simpler and less costly than building a 10416 // full-blown top-down phase beginning at the consecutive loads. 10417 Changed |= tryToVectorizeList(Bundle, R); 10418 } 10419 } 10420 return Changed; 10421 } 10422 10423 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) { 10424 bool Changed = false; 10425 // Sort by type, base pointers and values operand. Value operands must be 10426 // compatible (have the same opcode, same parent), otherwise it is 10427 // definitely not profitable to try to vectorize them. 10428 auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) { 10429 if (V->getPointerOperandType()->getTypeID() < 10430 V2->getPointerOperandType()->getTypeID()) 10431 return true; 10432 if (V->getPointerOperandType()->getTypeID() > 10433 V2->getPointerOperandType()->getTypeID()) 10434 return false; 10435 // UndefValues are compatible with all other values. 10436 if (isa<UndefValue>(V->getValueOperand()) || 10437 isa<UndefValue>(V2->getValueOperand())) 10438 return false; 10439 if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand())) 10440 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 10441 DomTreeNodeBase<llvm::BasicBlock> *NodeI1 = 10442 DT->getNode(I1->getParent()); 10443 DomTreeNodeBase<llvm::BasicBlock> *NodeI2 = 10444 DT->getNode(I2->getParent()); 10445 assert(NodeI1 && "Should only process reachable instructions"); 10446 assert(NodeI1 && "Should only process reachable instructions"); 10447 assert((NodeI1 == NodeI2) == 10448 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 10449 "Different nodes should have different DFS numbers"); 10450 if (NodeI1 != NodeI2) 10451 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 10452 InstructionsState S = getSameOpcode({I1, I2}); 10453 if (S.getOpcode()) 10454 return false; 10455 return I1->getOpcode() < I2->getOpcode(); 10456 } 10457 if (isa<Constant>(V->getValueOperand()) && 10458 isa<Constant>(V2->getValueOperand())) 10459 return false; 10460 return V->getValueOperand()->getValueID() < 10461 V2->getValueOperand()->getValueID(); 10462 }; 10463 10464 auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) { 10465 if (V1 == V2) 10466 return true; 10467 if (V1->getPointerOperandType() != V2->getPointerOperandType()) 10468 return false; 10469 // Undefs are compatible with any other value. 10470 if (isa<UndefValue>(V1->getValueOperand()) || 10471 isa<UndefValue>(V2->getValueOperand())) 10472 return true; 10473 if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand())) 10474 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 10475 if (I1->getParent() != I2->getParent()) 10476 return false; 10477 InstructionsState S = getSameOpcode({I1, I2}); 10478 return S.getOpcode() > 0; 10479 } 10480 if (isa<Constant>(V1->getValueOperand()) && 10481 isa<Constant>(V2->getValueOperand())) 10482 return true; 10483 return V1->getValueOperand()->getValueID() == 10484 V2->getValueOperand()->getValueID(); 10485 }; 10486 auto Limit = [&R, this](StoreInst *SI) { 10487 unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType()); 10488 return R.getMinVF(EltSize); 10489 }; 10490 10491 // Attempt to sort and vectorize each of the store-groups. 10492 for (auto &Pair : Stores) { 10493 if (Pair.second.size() < 2) 10494 continue; 10495 10496 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " 10497 << Pair.second.size() << ".\n"); 10498 10499 if (!isValidElementType(Pair.second.front()->getValueOperand()->getType())) 10500 continue; 10501 10502 Changed |= tryToVectorizeSequence<StoreInst>( 10503 Pair.second, Limit, StoreSorter, AreCompatibleStores, 10504 [this, &R](ArrayRef<StoreInst *> Candidates, bool) { 10505 return vectorizeStores(Candidates, R); 10506 }, 10507 /*LimitForRegisterSize=*/false); 10508 } 10509 return Changed; 10510 } 10511 10512 char SLPVectorizer::ID = 0; 10513 10514 static const char lv_name[] = "SLP Vectorizer"; 10515 10516 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false) 10517 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 10518 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 10519 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10520 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 10521 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 10522 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) 10523 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 10524 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy) 10525 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) 10526 10527 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); } 10528