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/DerivedTypes.h" 57 #include "llvm/IR/Dominators.h" 58 #include "llvm/IR/Function.h" 59 #include "llvm/IR/IRBuilder.h" 60 #include "llvm/IR/InstrTypes.h" 61 #include "llvm/IR/Instruction.h" 62 #include "llvm/IR/Instructions.h" 63 #include "llvm/IR/IntrinsicInst.h" 64 #include "llvm/IR/Intrinsics.h" 65 #include "llvm/IR/Module.h" 66 #include "llvm/IR/Operator.h" 67 #include "llvm/IR/PatternMatch.h" 68 #include "llvm/IR/Type.h" 69 #include "llvm/IR/Use.h" 70 #include "llvm/IR/User.h" 71 #include "llvm/IR/Value.h" 72 #include "llvm/IR/ValueHandle.h" 73 #ifdef EXPENSIVE_CHECKS 74 #include "llvm/IR/Verifier.h" 75 #endif 76 #include "llvm/Pass.h" 77 #include "llvm/Support/Casting.h" 78 #include "llvm/Support/CommandLine.h" 79 #include "llvm/Support/Compiler.h" 80 #include "llvm/Support/DOTGraphTraits.h" 81 #include "llvm/Support/Debug.h" 82 #include "llvm/Support/ErrorHandling.h" 83 #include "llvm/Support/GraphWriter.h" 84 #include "llvm/Support/InstructionCost.h" 85 #include "llvm/Support/KnownBits.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include "llvm/Transforms/Utils/InjectTLIMappings.h" 89 #include "llvm/Transforms/Utils/Local.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 // The maximum depth that the look-ahead score heuristic will explore 168 // when it probing among candidates for vectorization tree roots. 169 // The higher this value, the higher the compilation time overhead but unlike 170 // similar limit for operands ordering this is less frequently used, hence 171 // impact of higher value is less noticeable. 172 static cl::opt<int> RootLookAheadMaxDepth( 173 "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden, 174 cl::desc("The maximum look-ahead depth for searching best rooting option")); 175 176 static cl::opt<bool> 177 ViewSLPTree("view-slp-tree", cl::Hidden, 178 cl::desc("Display the SLP trees with Graphviz")); 179 180 // Limit the number of alias checks. The limit is chosen so that 181 // it has no negative effect on the llvm benchmarks. 182 static const unsigned AliasedCheckLimit = 10; 183 184 // Another limit for the alias checks: The maximum distance between load/store 185 // instructions where alias checks are done. 186 // This limit is useful for very large basic blocks. 187 static const unsigned MaxMemDepDistance = 160; 188 189 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling 190 /// regions to be handled. 191 static const int MinScheduleRegionSize = 16; 192 193 /// Predicate for the element types that the SLP vectorizer supports. 194 /// 195 /// The most important thing to filter here are types which are invalid in LLVM 196 /// vectors. We also filter target specific types which have absolutely no 197 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just 198 /// avoids spending time checking the cost model and realizing that they will 199 /// be inevitably scalarized. 200 static bool isValidElementType(Type *Ty) { 201 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() && 202 !Ty->isPPC_FP128Ty(); 203 } 204 205 /// \returns True if the value is a constant (but not globals/constant 206 /// expressions). 207 static bool isConstant(Value *V) { 208 return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V); 209 } 210 211 /// Checks if \p V is one of vector-like instructions, i.e. undef, 212 /// insertelement/extractelement with constant indices for fixed vector type or 213 /// extractvalue instruction. 214 static bool isVectorLikeInstWithConstOps(Value *V) { 215 if (!isa<InsertElementInst, ExtractElementInst>(V) && 216 !isa<ExtractValueInst, UndefValue>(V)) 217 return false; 218 auto *I = dyn_cast<Instruction>(V); 219 if (!I || isa<ExtractValueInst>(I)) 220 return true; 221 if (!isa<FixedVectorType>(I->getOperand(0)->getType())) 222 return false; 223 if (isa<ExtractElementInst>(I)) 224 return isConstant(I->getOperand(1)); 225 assert(isa<InsertElementInst>(V) && "Expected only insertelement."); 226 return isConstant(I->getOperand(2)); 227 } 228 229 /// \returns true if all of the instructions in \p VL are in the same block or 230 /// false otherwise. 231 static bool allSameBlock(ArrayRef<Value *> VL) { 232 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 233 if (!I0) 234 return false; 235 if (all_of(VL, isVectorLikeInstWithConstOps)) 236 return true; 237 238 BasicBlock *BB = I0->getParent(); 239 for (int I = 1, E = VL.size(); I < E; I++) { 240 auto *II = dyn_cast<Instruction>(VL[I]); 241 if (!II) 242 return false; 243 244 if (BB != II->getParent()) 245 return false; 246 } 247 return true; 248 } 249 250 /// \returns True if all of the values in \p VL are constants (but not 251 /// globals/constant expressions). 252 static bool allConstant(ArrayRef<Value *> VL) { 253 // Constant expressions and globals can't be vectorized like normal integer/FP 254 // constants. 255 return all_of(VL, isConstant); 256 } 257 258 /// \returns True if all of the values in \p VL are identical or some of them 259 /// are UndefValue. 260 static bool isSplat(ArrayRef<Value *> VL) { 261 Value *FirstNonUndef = nullptr; 262 for (Value *V : VL) { 263 if (isa<UndefValue>(V)) 264 continue; 265 if (!FirstNonUndef) { 266 FirstNonUndef = V; 267 continue; 268 } 269 if (V != FirstNonUndef) 270 return false; 271 } 272 return FirstNonUndef != nullptr; 273 } 274 275 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator. 276 static bool isCommutative(Instruction *I) { 277 if (auto *Cmp = dyn_cast<CmpInst>(I)) 278 return Cmp->isCommutative(); 279 if (auto *BO = dyn_cast<BinaryOperator>(I)) 280 return BO->isCommutative(); 281 // TODO: This should check for generic Instruction::isCommutative(), but 282 // we need to confirm that the caller code correctly handles Intrinsics 283 // for example (does not have 2 operands). 284 return false; 285 } 286 287 /// Checks if the given value is actually an undefined constant vector. 288 static bool isUndefVector(const Value *V) { 289 if (isa<UndefValue>(V)) 290 return true; 291 auto *C = dyn_cast<Constant>(V); 292 if (!C) 293 return false; 294 if (!C->containsUndefOrPoisonElement()) 295 return false; 296 auto *VecTy = dyn_cast<FixedVectorType>(C->getType()); 297 if (!VecTy) 298 return false; 299 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) { 300 if (Constant *Elem = C->getAggregateElement(I)) 301 if (!isa<UndefValue>(Elem)) 302 return false; 303 } 304 return true; 305 } 306 307 /// Checks if the vector of instructions can be represented as a shuffle, like: 308 /// %x0 = extractelement <4 x i8> %x, i32 0 309 /// %x3 = extractelement <4 x i8> %x, i32 3 310 /// %y1 = extractelement <4 x i8> %y, i32 1 311 /// %y2 = extractelement <4 x i8> %y, i32 2 312 /// %x0x0 = mul i8 %x0, %x0 313 /// %x3x3 = mul i8 %x3, %x3 314 /// %y1y1 = mul i8 %y1, %y1 315 /// %y2y2 = mul i8 %y2, %y2 316 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0 317 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1 318 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2 319 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3 320 /// ret <4 x i8> %ins4 321 /// can be transformed into: 322 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5, 323 /// i32 6> 324 /// %2 = mul <4 x i8> %1, %1 325 /// ret <4 x i8> %2 326 /// We convert this initially to something like: 327 /// %x0 = extractelement <4 x i8> %x, i32 0 328 /// %x3 = extractelement <4 x i8> %x, i32 3 329 /// %y1 = extractelement <4 x i8> %y, i32 1 330 /// %y2 = extractelement <4 x i8> %y, i32 2 331 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0 332 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1 333 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2 334 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3 335 /// %5 = mul <4 x i8> %4, %4 336 /// %6 = extractelement <4 x i8> %5, i32 0 337 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0 338 /// %7 = extractelement <4 x i8> %5, i32 1 339 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1 340 /// %8 = extractelement <4 x i8> %5, i32 2 341 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2 342 /// %9 = extractelement <4 x i8> %5, i32 3 343 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3 344 /// ret <4 x i8> %ins4 345 /// InstCombiner transforms this into a shuffle and vector mul 346 /// Mask will return the Shuffle Mask equivalent to the extracted elements. 347 /// TODO: Can we split off and reuse the shuffle mask detection from 348 /// TargetTransformInfo::getInstructionThroughput? 349 static Optional<TargetTransformInfo::ShuffleKind> 350 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) { 351 const auto *It = 352 find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); }); 353 if (It == VL.end()) 354 return None; 355 auto *EI0 = cast<ExtractElementInst>(*It); 356 if (isa<ScalableVectorType>(EI0->getVectorOperandType())) 357 return None; 358 unsigned Size = 359 cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements(); 360 Value *Vec1 = nullptr; 361 Value *Vec2 = nullptr; 362 enum ShuffleMode { Unknown, Select, Permute }; 363 ShuffleMode CommonShuffleMode = Unknown; 364 Mask.assign(VL.size(), UndefMaskElem); 365 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 366 // Undef can be represented as an undef element in a vector. 367 if (isa<UndefValue>(VL[I])) 368 continue; 369 auto *EI = cast<ExtractElementInst>(VL[I]); 370 if (isa<ScalableVectorType>(EI->getVectorOperandType())) 371 return None; 372 auto *Vec = EI->getVectorOperand(); 373 // We can extractelement from undef or poison vector. 374 if (isUndefVector(Vec)) 375 continue; 376 // All vector operands must have the same number of vector elements. 377 if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size) 378 return None; 379 if (isa<UndefValue>(EI->getIndexOperand())) 380 continue; 381 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand()); 382 if (!Idx) 383 return None; 384 // Undefined behavior if Idx is negative or >= Size. 385 if (Idx->getValue().uge(Size)) 386 continue; 387 unsigned IntIdx = Idx->getValue().getZExtValue(); 388 Mask[I] = IntIdx; 389 // For correct shuffling we have to have at most 2 different vector operands 390 // in all extractelement instructions. 391 if (!Vec1 || Vec1 == Vec) { 392 Vec1 = Vec; 393 } else if (!Vec2 || Vec2 == Vec) { 394 Vec2 = Vec; 395 Mask[I] += Size; 396 } else { 397 return None; 398 } 399 if (CommonShuffleMode == Permute) 400 continue; 401 // If the extract index is not the same as the operation number, it is a 402 // permutation. 403 if (IntIdx != I) { 404 CommonShuffleMode = Permute; 405 continue; 406 } 407 CommonShuffleMode = Select; 408 } 409 // If we're not crossing lanes in different vectors, consider it as blending. 410 if (CommonShuffleMode == Select && Vec2) 411 return TargetTransformInfo::SK_Select; 412 // If Vec2 was never used, we have a permutation of a single vector, otherwise 413 // we have permutation of 2 vectors. 414 return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc 415 : TargetTransformInfo::SK_PermuteSingleSrc; 416 } 417 418 namespace { 419 420 /// Main data required for vectorization of instructions. 421 struct InstructionsState { 422 /// The very first instruction in the list with the main opcode. 423 Value *OpValue = nullptr; 424 425 /// The main/alternate instruction. 426 Instruction *MainOp = nullptr; 427 Instruction *AltOp = nullptr; 428 429 /// The main/alternate opcodes for the list of instructions. 430 unsigned getOpcode() const { 431 return MainOp ? MainOp->getOpcode() : 0; 432 } 433 434 unsigned getAltOpcode() const { 435 return AltOp ? AltOp->getOpcode() : 0; 436 } 437 438 /// Some of the instructions in the list have alternate opcodes. 439 bool isAltShuffle() const { return AltOp != MainOp; } 440 441 bool isOpcodeOrAlt(Instruction *I) const { 442 unsigned CheckedOpcode = I->getOpcode(); 443 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode; 444 } 445 446 InstructionsState() = delete; 447 InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp) 448 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {} 449 }; 450 451 } // end anonymous namespace 452 453 /// Chooses the correct key for scheduling data. If \p Op has the same (or 454 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p 455 /// OpValue. 456 static Value *isOneOf(const InstructionsState &S, Value *Op) { 457 auto *I = dyn_cast<Instruction>(Op); 458 if (I && S.isOpcodeOrAlt(I)) 459 return Op; 460 return S.OpValue; 461 } 462 463 /// \returns true if \p Opcode is allowed as part of of the main/alternate 464 /// instruction for SLP vectorization. 465 /// 466 /// Example of unsupported opcode is SDIV that can potentially cause UB if the 467 /// "shuffled out" lane would result in division by zero. 468 static bool isValidForAlternation(unsigned Opcode) { 469 if (Instruction::isIntDivRem(Opcode)) 470 return false; 471 472 return true; 473 } 474 475 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 476 unsigned BaseIndex = 0); 477 478 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e. 479 /// compatible instructions or constants, or just some other regular values. 480 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0, 481 Value *Op1) { 482 return (isConstant(BaseOp0) && isConstant(Op0)) || 483 (isConstant(BaseOp1) && isConstant(Op1)) || 484 (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) && 485 !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) || 486 getSameOpcode({BaseOp0, Op0}).getOpcode() || 487 getSameOpcode({BaseOp1, Op1}).getOpcode(); 488 } 489 490 /// \returns analysis of the Instructions in \p VL described in 491 /// InstructionsState, the Opcode that we suppose the whole list 492 /// could be vectorized even if its structure is diverse. 493 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 494 unsigned BaseIndex) { 495 // Make sure these are all Instructions. 496 if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); })) 497 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 498 499 bool IsCastOp = isa<CastInst>(VL[BaseIndex]); 500 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]); 501 bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]); 502 CmpInst::Predicate BasePred = 503 IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate() 504 : CmpInst::BAD_ICMP_PREDICATE; 505 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode(); 506 unsigned AltOpcode = Opcode; 507 unsigned AltIndex = BaseIndex; 508 509 // Check for one alternate opcode from another BinaryOperator. 510 // TODO - generalize to support all operators (types, calls etc.). 511 for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) { 512 unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode(); 513 if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) { 514 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 515 continue; 516 if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) && 517 isValidForAlternation(Opcode)) { 518 AltOpcode = InstOpcode; 519 AltIndex = Cnt; 520 continue; 521 } 522 } else if (IsCastOp && isa<CastInst>(VL[Cnt])) { 523 Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType(); 524 Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType(); 525 if (Ty0 == Ty1) { 526 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 527 continue; 528 if (Opcode == AltOpcode) { 529 assert(isValidForAlternation(Opcode) && 530 isValidForAlternation(InstOpcode) && 531 "Cast isn't safe for alternation, logic needs to be updated!"); 532 AltOpcode = InstOpcode; 533 AltIndex = Cnt; 534 continue; 535 } 536 } 537 } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) { 538 auto *BaseInst = cast<Instruction>(VL[BaseIndex]); 539 auto *Inst = cast<Instruction>(VL[Cnt]); 540 Type *Ty0 = BaseInst->getOperand(0)->getType(); 541 Type *Ty1 = Inst->getOperand(0)->getType(); 542 if (Ty0 == Ty1) { 543 Value *BaseOp0 = BaseInst->getOperand(0); 544 Value *BaseOp1 = BaseInst->getOperand(1); 545 Value *Op0 = Inst->getOperand(0); 546 Value *Op1 = Inst->getOperand(1); 547 CmpInst::Predicate CurrentPred = 548 cast<CmpInst>(VL[Cnt])->getPredicate(); 549 CmpInst::Predicate SwappedCurrentPred = 550 CmpInst::getSwappedPredicate(CurrentPred); 551 // Check for compatible operands. If the corresponding operands are not 552 // compatible - need to perform alternate vectorization. 553 if (InstOpcode == Opcode) { 554 if (BasePred == CurrentPred && 555 areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1)) 556 continue; 557 if (BasePred == SwappedCurrentPred && 558 areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0)) 559 continue; 560 if (E == 2 && 561 (BasePred == CurrentPred || BasePred == SwappedCurrentPred)) 562 continue; 563 auto *AltInst = cast<CmpInst>(VL[AltIndex]); 564 CmpInst::Predicate AltPred = AltInst->getPredicate(); 565 Value *AltOp0 = AltInst->getOperand(0); 566 Value *AltOp1 = AltInst->getOperand(1); 567 // Check if operands are compatible with alternate operands. 568 if (AltPred == CurrentPred && 569 areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1)) 570 continue; 571 if (AltPred == SwappedCurrentPred && 572 areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0)) 573 continue; 574 } 575 if (BaseIndex == AltIndex && BasePred != CurrentPred) { 576 assert(isValidForAlternation(Opcode) && 577 isValidForAlternation(InstOpcode) && 578 "Cast isn't safe for alternation, logic needs to be updated!"); 579 AltIndex = Cnt; 580 continue; 581 } 582 auto *AltInst = cast<CmpInst>(VL[AltIndex]); 583 CmpInst::Predicate AltPred = AltInst->getPredicate(); 584 if (BasePred == CurrentPred || BasePred == SwappedCurrentPred || 585 AltPred == CurrentPred || AltPred == SwappedCurrentPred) 586 continue; 587 } 588 } else if (InstOpcode == Opcode || InstOpcode == AltOpcode) 589 continue; 590 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 591 } 592 593 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]), 594 cast<Instruction>(VL[AltIndex])); 595 } 596 597 /// \returns true if all of the values in \p VL have the same type or false 598 /// otherwise. 599 static bool allSameType(ArrayRef<Value *> VL) { 600 Type *Ty = VL[0]->getType(); 601 for (int i = 1, e = VL.size(); i < e; i++) 602 if (VL[i]->getType() != Ty) 603 return false; 604 605 return true; 606 } 607 608 /// \returns True if Extract{Value,Element} instruction extracts element Idx. 609 static Optional<unsigned> getExtractIndex(Instruction *E) { 610 unsigned Opcode = E->getOpcode(); 611 assert((Opcode == Instruction::ExtractElement || 612 Opcode == Instruction::ExtractValue) && 613 "Expected extractelement or extractvalue instruction."); 614 if (Opcode == Instruction::ExtractElement) { 615 auto *CI = dyn_cast<ConstantInt>(E->getOperand(1)); 616 if (!CI) 617 return None; 618 return CI->getZExtValue(); 619 } 620 ExtractValueInst *EI = cast<ExtractValueInst>(E); 621 if (EI->getNumIndices() != 1) 622 return None; 623 return *EI->idx_begin(); 624 } 625 626 /// \returns True if in-tree use also needs extract. This refers to 627 /// possible scalar operand in vectorized instruction. 628 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, 629 TargetLibraryInfo *TLI) { 630 unsigned Opcode = UserInst->getOpcode(); 631 switch (Opcode) { 632 case Instruction::Load: { 633 LoadInst *LI = cast<LoadInst>(UserInst); 634 return (LI->getPointerOperand() == Scalar); 635 } 636 case Instruction::Store: { 637 StoreInst *SI = cast<StoreInst>(UserInst); 638 return (SI->getPointerOperand() == Scalar); 639 } 640 case Instruction::Call: { 641 CallInst *CI = cast<CallInst>(UserInst); 642 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 643 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 644 if (isVectorIntrinsicWithScalarOpAtArg(ID, i)) 645 return (CI->getArgOperand(i) == Scalar); 646 } 647 LLVM_FALLTHROUGH; 648 } 649 default: 650 return false; 651 } 652 } 653 654 /// \returns the AA location that is being access by the instruction. 655 static MemoryLocation getLocation(Instruction *I) { 656 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 657 return MemoryLocation::get(SI); 658 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 659 return MemoryLocation::get(LI); 660 return MemoryLocation(); 661 } 662 663 /// \returns True if the instruction is not a volatile or atomic load/store. 664 static bool isSimple(Instruction *I) { 665 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 666 return LI->isSimple(); 667 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 668 return SI->isSimple(); 669 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) 670 return !MI->isVolatile(); 671 return true; 672 } 673 674 /// Shuffles \p Mask in accordance with the given \p SubMask. 675 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) { 676 if (SubMask.empty()) 677 return; 678 if (Mask.empty()) { 679 Mask.append(SubMask.begin(), SubMask.end()); 680 return; 681 } 682 SmallVector<int> NewMask(SubMask.size(), UndefMaskElem); 683 int TermValue = std::min(Mask.size(), SubMask.size()); 684 for (int I = 0, E = SubMask.size(); I < E; ++I) { 685 if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem || 686 Mask[SubMask[I]] >= TermValue) 687 continue; 688 NewMask[I] = Mask[SubMask[I]]; 689 } 690 Mask.swap(NewMask); 691 } 692 693 /// Order may have elements assigned special value (size) which is out of 694 /// bounds. Such indices only appear on places which correspond to undef values 695 /// (see canReuseExtract for details) and used in order to avoid undef values 696 /// have effect on operands ordering. 697 /// The first loop below simply finds all unused indices and then the next loop 698 /// nest assigns these indices for undef values positions. 699 /// As an example below Order has two undef positions and they have assigned 700 /// values 3 and 7 respectively: 701 /// before: 6 9 5 4 9 2 1 0 702 /// after: 6 3 5 4 7 2 1 0 703 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) { 704 const unsigned Sz = Order.size(); 705 SmallBitVector UnusedIndices(Sz, /*t=*/true); 706 SmallBitVector MaskedIndices(Sz); 707 for (unsigned I = 0; I < Sz; ++I) { 708 if (Order[I] < Sz) 709 UnusedIndices.reset(Order[I]); 710 else 711 MaskedIndices.set(I); 712 } 713 if (MaskedIndices.none()) 714 return; 715 assert(UnusedIndices.count() == MaskedIndices.count() && 716 "Non-synced masked/available indices."); 717 int Idx = UnusedIndices.find_first(); 718 int MIdx = MaskedIndices.find_first(); 719 while (MIdx >= 0) { 720 assert(Idx >= 0 && "Indices must be synced."); 721 Order[MIdx] = Idx; 722 Idx = UnusedIndices.find_next(Idx); 723 MIdx = MaskedIndices.find_next(MIdx); 724 } 725 } 726 727 namespace llvm { 728 729 static void inversePermutation(ArrayRef<unsigned> Indices, 730 SmallVectorImpl<int> &Mask) { 731 Mask.clear(); 732 const unsigned E = Indices.size(); 733 Mask.resize(E, UndefMaskElem); 734 for (unsigned I = 0; I < E; ++I) 735 Mask[Indices[I]] = I; 736 } 737 738 /// \returns inserting index of InsertElement or InsertValue instruction, 739 /// using Offset as base offset for index. 740 static Optional<unsigned> getInsertIndex(const Value *InsertInst, 741 unsigned Offset = 0) { 742 int Index = Offset; 743 if (const auto *IE = dyn_cast<InsertElementInst>(InsertInst)) { 744 if (const auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) { 745 auto *VT = cast<FixedVectorType>(IE->getType()); 746 if (CI->getValue().uge(VT->getNumElements())) 747 return None; 748 Index *= VT->getNumElements(); 749 Index += CI->getZExtValue(); 750 return Index; 751 } 752 return None; 753 } 754 755 const auto *IV = cast<InsertValueInst>(InsertInst); 756 Type *CurrentType = IV->getType(); 757 for (unsigned I : IV->indices()) { 758 if (const auto *ST = dyn_cast<StructType>(CurrentType)) { 759 Index *= ST->getNumElements(); 760 CurrentType = ST->getElementType(I); 761 } else if (const auto *AT = dyn_cast<ArrayType>(CurrentType)) { 762 Index *= AT->getNumElements(); 763 CurrentType = AT->getElementType(); 764 } else { 765 return None; 766 } 767 Index += I; 768 } 769 return Index; 770 } 771 772 /// Reorders the list of scalars in accordance with the given \p Mask. 773 static void reorderScalars(SmallVectorImpl<Value *> &Scalars, 774 ArrayRef<int> Mask) { 775 assert(!Mask.empty() && "Expected non-empty mask."); 776 SmallVector<Value *> Prev(Scalars.size(), 777 UndefValue::get(Scalars.front()->getType())); 778 Prev.swap(Scalars); 779 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 780 if (Mask[I] != UndefMaskElem) 781 Scalars[Mask[I]] = Prev[I]; 782 } 783 784 /// Checks if the provided value does not require scheduling. It does not 785 /// require scheduling if this is not an instruction or it is an instruction 786 /// that does not read/write memory and all operands are either not instructions 787 /// or phi nodes or instructions from different blocks. 788 static bool areAllOperandsNonInsts(Value *V) { 789 auto *I = dyn_cast<Instruction>(V); 790 if (!I) 791 return true; 792 return !mayHaveNonDefUseDependency(*I) && 793 all_of(I->operands(), [I](Value *V) { 794 auto *IO = dyn_cast<Instruction>(V); 795 if (!IO) 796 return true; 797 return isa<PHINode>(IO) || IO->getParent() != I->getParent(); 798 }); 799 } 800 801 /// Checks if the provided value does not require scheduling. It does not 802 /// require scheduling if this is not an instruction or it is an instruction 803 /// that does not read/write memory and all users are phi nodes or instructions 804 /// from the different blocks. 805 static bool isUsedOutsideBlock(Value *V) { 806 auto *I = dyn_cast<Instruction>(V); 807 if (!I) 808 return true; 809 // Limits the number of uses to save compile time. 810 constexpr int UsesLimit = 8; 811 return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) && 812 all_of(I->users(), [I](User *U) { 813 auto *IU = dyn_cast<Instruction>(U); 814 if (!IU) 815 return true; 816 return IU->getParent() != I->getParent() || isa<PHINode>(IU); 817 }); 818 } 819 820 /// Checks if the specified value does not require scheduling. It does not 821 /// require scheduling if all operands and all users do not need to be scheduled 822 /// in the current basic block. 823 static bool doesNotNeedToBeScheduled(Value *V) { 824 return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V); 825 } 826 827 /// Checks if the specified array of instructions does not require scheduling. 828 /// It is so if all either instructions have operands that do not require 829 /// scheduling or their users do not require scheduling since they are phis or 830 /// in other basic blocks. 831 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) { 832 return !VL.empty() && 833 (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts)); 834 } 835 836 namespace slpvectorizer { 837 838 /// Bottom Up SLP Vectorizer. 839 class BoUpSLP { 840 struct TreeEntry; 841 struct ScheduleData; 842 843 public: 844 using ValueList = SmallVector<Value *, 8>; 845 using InstrList = SmallVector<Instruction *, 16>; 846 using ValueSet = SmallPtrSet<Value *, 16>; 847 using StoreList = SmallVector<StoreInst *, 8>; 848 using ExtraValueToDebugLocsMap = 849 MapVector<Value *, SmallVector<Instruction *, 2>>; 850 using OrdersType = SmallVector<unsigned, 4>; 851 852 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, 853 TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li, 854 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB, 855 const DataLayout *DL, OptimizationRemarkEmitter *ORE) 856 : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li), 857 DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) { 858 CodeMetrics::collectEphemeralValues(F, AC, EphValues); 859 // Use the vector register size specified by the target unless overridden 860 // by a command-line option. 861 // TODO: It would be better to limit the vectorization factor based on 862 // data type rather than just register size. For example, x86 AVX has 863 // 256-bit registers, but it does not support integer operations 864 // at that width (that requires AVX2). 865 if (MaxVectorRegSizeOption.getNumOccurrences()) 866 MaxVecRegSize = MaxVectorRegSizeOption; 867 else 868 MaxVecRegSize = 869 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) 870 .getFixedSize(); 871 872 if (MinVectorRegSizeOption.getNumOccurrences()) 873 MinVecRegSize = MinVectorRegSizeOption; 874 else 875 MinVecRegSize = TTI->getMinVectorRegisterBitWidth(); 876 } 877 878 /// Vectorize the tree that starts with the elements in \p VL. 879 /// Returns the vectorized root. 880 Value *vectorizeTree(); 881 882 /// Vectorize the tree but with the list of externally used values \p 883 /// ExternallyUsedValues. Values in this MapVector can be replaced but the 884 /// generated extractvalue instructions. 885 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues); 886 887 /// \returns the cost incurred by unwanted spills and fills, caused by 888 /// holding live values over call sites. 889 InstructionCost getSpillCost() const; 890 891 /// \returns the vectorization cost of the subtree that starts at \p VL. 892 /// A negative number means that this is profitable. 893 InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None); 894 895 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for 896 /// the purpose of scheduling and extraction in the \p UserIgnoreLst. 897 void buildTree(ArrayRef<Value *> Roots, 898 const SmallDenseSet<Value *> &UserIgnoreLst); 899 900 /// Construct a vectorizable tree that starts at \p Roots. 901 void buildTree(ArrayRef<Value *> Roots); 902 903 /// Builds external uses of the vectorized scalars, i.e. the list of 904 /// vectorized scalars to be extracted, their lanes and their scalar users. \p 905 /// ExternallyUsedValues contains additional list of external uses to handle 906 /// vectorization of reductions. 907 void 908 buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {}); 909 910 /// Clear the internal data structures that are created by 'buildTree'. 911 void deleteTree() { 912 VectorizableTree.clear(); 913 ScalarToTreeEntry.clear(); 914 MustGather.clear(); 915 ExternalUses.clear(); 916 for (auto &Iter : BlocksSchedules) { 917 BlockScheduling *BS = Iter.second.get(); 918 BS->clear(); 919 } 920 MinBWs.clear(); 921 InstrElementSize.clear(); 922 UserIgnoreList = nullptr; 923 } 924 925 unsigned getTreeSize() const { return VectorizableTree.size(); } 926 927 /// Perform LICM and CSE on the newly generated gather sequences. 928 void optimizeGatherSequence(); 929 930 /// Checks if the specified gather tree entry \p TE can be represented as a 931 /// shuffled vector entry + (possibly) permutation with other gathers. It 932 /// implements the checks only for possibly ordered scalars (Loads, 933 /// ExtractElement, ExtractValue), which can be part of the graph. 934 Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE); 935 936 /// Sort loads into increasing pointers offsets to allow greater clustering. 937 Optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE); 938 939 /// Gets reordering data for the given tree entry. If the entry is vectorized 940 /// - just return ReorderIndices, otherwise check if the scalars can be 941 /// reordered and return the most optimal order. 942 /// \param TopToBottom If true, include the order of vectorized stores and 943 /// insertelement nodes, otherwise skip them. 944 Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom); 945 946 /// Reorders the current graph to the most profitable order starting from the 947 /// root node to the leaf nodes. The best order is chosen only from the nodes 948 /// of the same size (vectorization factor). Smaller nodes are considered 949 /// parts of subgraph with smaller VF and they are reordered independently. We 950 /// can make it because we still need to extend smaller nodes to the wider VF 951 /// and we can merge reordering shuffles with the widening shuffles. 952 void reorderTopToBottom(); 953 954 /// Reorders the current graph to the most profitable order starting from 955 /// leaves to the root. It allows to rotate small subgraphs and reduce the 956 /// number of reshuffles if the leaf nodes use the same order. In this case we 957 /// can merge the orders and just shuffle user node instead of shuffling its 958 /// operands. Plus, even the leaf nodes have different orders, it allows to 959 /// sink reordering in the graph closer to the root node and merge it later 960 /// during analysis. 961 void reorderBottomToTop(bool IgnoreReorder = false); 962 963 /// \return The vector element size in bits to use when vectorizing the 964 /// expression tree ending at \p V. If V is a store, the size is the width of 965 /// the stored value. Otherwise, the size is the width of the largest loaded 966 /// value reaching V. This method is used by the vectorizer to calculate 967 /// vectorization factors. 968 unsigned getVectorElementSize(Value *V); 969 970 /// Compute the minimum type sizes required to represent the entries in a 971 /// vectorizable tree. 972 void computeMinimumValueSizes(); 973 974 // \returns maximum vector register size as set by TTI or overridden by cl::opt. 975 unsigned getMaxVecRegSize() const { 976 return MaxVecRegSize; 977 } 978 979 // \returns minimum vector register size as set by cl::opt. 980 unsigned getMinVecRegSize() const { 981 return MinVecRegSize; 982 } 983 984 unsigned getMinVF(unsigned Sz) const { 985 return std::max(2U, getMinVecRegSize() / Sz); 986 } 987 988 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const { 989 unsigned MaxVF = MaxVFOption.getNumOccurrences() ? 990 MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode); 991 return MaxVF ? MaxVF : UINT_MAX; 992 } 993 994 /// Check if homogeneous aggregate is isomorphic to some VectorType. 995 /// Accepts homogeneous multidimensional aggregate of scalars/vectors like 996 /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> }, 997 /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on. 998 /// 999 /// \returns number of elements in vector if isomorphism exists, 0 otherwise. 1000 unsigned canMapToVector(Type *T, const DataLayout &DL) const; 1001 1002 /// \returns True if the VectorizableTree is both tiny and not fully 1003 /// vectorizable. We do not vectorize such trees. 1004 bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const; 1005 1006 /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values 1007 /// can be load combined in the backend. Load combining may not be allowed in 1008 /// the IR optimizer, so we do not want to alter the pattern. For example, 1009 /// partially transforming a scalar bswap() pattern into vector code is 1010 /// effectively impossible for the backend to undo. 1011 /// TODO: If load combining is allowed in the IR optimizer, this analysis 1012 /// may not be necessary. 1013 bool isLoadCombineReductionCandidate(RecurKind RdxKind) const; 1014 1015 /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values 1016 /// can be load combined in the backend. Load combining may not be allowed in 1017 /// the IR optimizer, so we do not want to alter the pattern. For example, 1018 /// partially transforming a scalar bswap() pattern into vector code is 1019 /// effectively impossible for the backend to undo. 1020 /// TODO: If load combining is allowed in the IR optimizer, this analysis 1021 /// may not be necessary. 1022 bool isLoadCombineCandidate() const; 1023 1024 OptimizationRemarkEmitter *getORE() { return ORE; } 1025 1026 /// This structure holds any data we need about the edges being traversed 1027 /// during buildTree_rec(). We keep track of: 1028 /// (i) the user TreeEntry index, and 1029 /// (ii) the index of the edge. 1030 struct EdgeInfo { 1031 EdgeInfo() = default; 1032 EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx) 1033 : UserTE(UserTE), EdgeIdx(EdgeIdx) {} 1034 /// The user TreeEntry. 1035 TreeEntry *UserTE = nullptr; 1036 /// The operand index of the use. 1037 unsigned EdgeIdx = UINT_MAX; 1038 #ifndef NDEBUG 1039 friend inline raw_ostream &operator<<(raw_ostream &OS, 1040 const BoUpSLP::EdgeInfo &EI) { 1041 EI.dump(OS); 1042 return OS; 1043 } 1044 /// Debug print. 1045 void dump(raw_ostream &OS) const { 1046 OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null") 1047 << " EdgeIdx:" << EdgeIdx << "}"; 1048 } 1049 LLVM_DUMP_METHOD void dump() const { dump(dbgs()); } 1050 #endif 1051 }; 1052 1053 /// A helper class used for scoring candidates for two consecutive lanes. 1054 class LookAheadHeuristics { 1055 const DataLayout &DL; 1056 ScalarEvolution &SE; 1057 const BoUpSLP &R; 1058 int NumLanes; // Total number of lanes (aka vectorization factor). 1059 int MaxLevel; // The maximum recursion depth for accumulating score. 1060 1061 public: 1062 LookAheadHeuristics(const DataLayout &DL, ScalarEvolution &SE, 1063 const BoUpSLP &R, int NumLanes, int MaxLevel) 1064 : DL(DL), SE(SE), R(R), NumLanes(NumLanes), MaxLevel(MaxLevel) {} 1065 1066 // The hard-coded scores listed here are not very important, though it shall 1067 // be higher for better matches to improve the resulting cost. When 1068 // computing the scores of matching one sub-tree with another, we are 1069 // basically counting the number of values that are matching. So even if all 1070 // scores are set to 1, we would still get a decent matching result. 1071 // However, sometimes we have to break ties. For example we may have to 1072 // choose between matching loads vs matching opcodes. This is what these 1073 // scores are helping us with: they provide the order of preference. Also, 1074 // this is important if the scalar is externally used or used in another 1075 // tree entry node in the different lane. 1076 1077 /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]). 1078 static const int ScoreConsecutiveLoads = 4; 1079 /// The same load multiple times. This should have a better score than 1080 /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it 1081 /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for 1082 /// a vector load and 1.0 for a broadcast. 1083 static const int ScoreSplatLoads = 3; 1084 /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]). 1085 static const int ScoreReversedLoads = 3; 1086 /// ExtractElementInst from same vector and consecutive indexes. 1087 static const int ScoreConsecutiveExtracts = 4; 1088 /// ExtractElementInst from same vector and reversed indices. 1089 static const int ScoreReversedExtracts = 3; 1090 /// Constants. 1091 static const int ScoreConstants = 2; 1092 /// Instructions with the same opcode. 1093 static const int ScoreSameOpcode = 2; 1094 /// Instructions with alt opcodes (e.g, add + sub). 1095 static const int ScoreAltOpcodes = 1; 1096 /// Identical instructions (a.k.a. splat or broadcast). 1097 static const int ScoreSplat = 1; 1098 /// Matching with an undef is preferable to failing. 1099 static const int ScoreUndef = 1; 1100 /// Score for failing to find a decent match. 1101 static const int ScoreFail = 0; 1102 /// Score if all users are vectorized. 1103 static const int ScoreAllUserVectorized = 1; 1104 1105 /// \returns the score of placing \p V1 and \p V2 in consecutive lanes. 1106 /// \p U1 and \p U2 are the users of \p V1 and \p V2. 1107 /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p 1108 /// MainAltOps. 1109 int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2, 1110 ArrayRef<Value *> MainAltOps) const { 1111 if (V1 == V2) { 1112 if (isa<LoadInst>(V1)) { 1113 // Retruns true if the users of V1 and V2 won't need to be extracted. 1114 auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) { 1115 // Bail out if we have too many uses to save compilation time. 1116 static constexpr unsigned Limit = 8; 1117 if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit)) 1118 return false; 1119 1120 auto AllUsersVectorized = [U1, U2, this](Value *V) { 1121 return llvm::all_of(V->users(), [U1, U2, this](Value *U) { 1122 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr; 1123 }); 1124 }; 1125 return AllUsersVectorized(V1) && AllUsersVectorized(V2); 1126 }; 1127 // A broadcast of a load can be cheaper on some targets. 1128 if (R.TTI->isLegalBroadcastLoad(V1->getType(), 1129 ElementCount::getFixed(NumLanes)) && 1130 ((int)V1->getNumUses() == NumLanes || 1131 AllUsersAreInternal(V1, V2))) 1132 return LookAheadHeuristics::ScoreSplatLoads; 1133 } 1134 return LookAheadHeuristics::ScoreSplat; 1135 } 1136 1137 auto *LI1 = dyn_cast<LoadInst>(V1); 1138 auto *LI2 = dyn_cast<LoadInst>(V2); 1139 if (LI1 && LI2) { 1140 if (LI1->getParent() != LI2->getParent()) 1141 return LookAheadHeuristics::ScoreFail; 1142 1143 Optional<int> Dist = getPointersDiff( 1144 LI1->getType(), LI1->getPointerOperand(), LI2->getType(), 1145 LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true); 1146 if (!Dist || *Dist == 0) 1147 return LookAheadHeuristics::ScoreFail; 1148 // The distance is too large - still may be profitable to use masked 1149 // loads/gathers. 1150 if (std::abs(*Dist) > NumLanes / 2) 1151 return LookAheadHeuristics::ScoreAltOpcodes; 1152 // This still will detect consecutive loads, but we might have "holes" 1153 // in some cases. It is ok for non-power-2 vectorization and may produce 1154 // better results. It should not affect current vectorization. 1155 return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads 1156 : LookAheadHeuristics::ScoreReversedLoads; 1157 } 1158 1159 auto *C1 = dyn_cast<Constant>(V1); 1160 auto *C2 = dyn_cast<Constant>(V2); 1161 if (C1 && C2) 1162 return LookAheadHeuristics::ScoreConstants; 1163 1164 // Extracts from consecutive indexes of the same vector better score as 1165 // the extracts could be optimized away. 1166 Value *EV1; 1167 ConstantInt *Ex1Idx; 1168 if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) { 1169 // Undefs are always profitable for extractelements. 1170 if (isa<UndefValue>(V2)) 1171 return LookAheadHeuristics::ScoreConsecutiveExtracts; 1172 Value *EV2 = nullptr; 1173 ConstantInt *Ex2Idx = nullptr; 1174 if (match(V2, 1175 m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx), 1176 m_Undef())))) { 1177 // Undefs are always profitable for extractelements. 1178 if (!Ex2Idx) 1179 return LookAheadHeuristics::ScoreConsecutiveExtracts; 1180 if (isUndefVector(EV2) && EV2->getType() == EV1->getType()) 1181 return LookAheadHeuristics::ScoreConsecutiveExtracts; 1182 if (EV2 == EV1) { 1183 int Idx1 = Ex1Idx->getZExtValue(); 1184 int Idx2 = Ex2Idx->getZExtValue(); 1185 int Dist = Idx2 - Idx1; 1186 // The distance is too large - still may be profitable to use 1187 // shuffles. 1188 if (std::abs(Dist) == 0) 1189 return LookAheadHeuristics::ScoreSplat; 1190 if (std::abs(Dist) > NumLanes / 2) 1191 return LookAheadHeuristics::ScoreSameOpcode; 1192 return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts 1193 : LookAheadHeuristics::ScoreReversedExtracts; 1194 } 1195 return LookAheadHeuristics::ScoreAltOpcodes; 1196 } 1197 return LookAheadHeuristics::ScoreFail; 1198 } 1199 1200 auto *I1 = dyn_cast<Instruction>(V1); 1201 auto *I2 = dyn_cast<Instruction>(V2); 1202 if (I1 && I2) { 1203 if (I1->getParent() != I2->getParent()) 1204 return LookAheadHeuristics::ScoreFail; 1205 SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end()); 1206 Ops.push_back(I1); 1207 Ops.push_back(I2); 1208 InstructionsState S = getSameOpcode(Ops); 1209 // Note: Only consider instructions with <= 2 operands to avoid 1210 // complexity explosion. 1211 if (S.getOpcode() && 1212 (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() || 1213 !S.isAltShuffle()) && 1214 all_of(Ops, [&S](Value *V) { 1215 return cast<Instruction>(V)->getNumOperands() == 1216 S.MainOp->getNumOperands(); 1217 })) 1218 return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes 1219 : LookAheadHeuristics::ScoreSameOpcode; 1220 } 1221 1222 if (isa<UndefValue>(V2)) 1223 return LookAheadHeuristics::ScoreUndef; 1224 1225 return LookAheadHeuristics::ScoreFail; 1226 } 1227 1228 /// Go through the operands of \p LHS and \p RHS recursively until 1229 /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are 1230 /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands 1231 /// of \p U1 and \p U2), except at the beginning of the recursion where 1232 /// these are set to nullptr. 1233 /// 1234 /// For example: 1235 /// \verbatim 1236 /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1] 1237 /// \ / \ / \ / \ / 1238 /// + + + + 1239 /// G1 G2 G3 G4 1240 /// \endverbatim 1241 /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at 1242 /// each level recursively, accumulating the score. It starts from matching 1243 /// the additions at level 0, then moves on to the loads (level 1). The 1244 /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and 1245 /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while 1246 /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail. 1247 /// Please note that the order of the operands does not matter, as we 1248 /// evaluate the score of all profitable combinations of operands. In 1249 /// other words the score of G1 and G4 is the same as G1 and G2. This 1250 /// heuristic is based on ideas described in: 1251 /// Look-ahead SLP: Auto-vectorization in the presence of commutative 1252 /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha, 1253 /// Luís F. W. Góes 1254 int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1, 1255 Instruction *U2, int CurrLevel, 1256 ArrayRef<Value *> MainAltOps) const { 1257 1258 // Get the shallow score of V1 and V2. 1259 int ShallowScoreAtThisLevel = 1260 getShallowScore(LHS, RHS, U1, U2, MainAltOps); 1261 1262 // If reached MaxLevel, 1263 // or if V1 and V2 are not instructions, 1264 // or if they are SPLAT, 1265 // or if they are not consecutive, 1266 // or if profitable to vectorize loads or extractelements, early return 1267 // the current cost. 1268 auto *I1 = dyn_cast<Instruction>(LHS); 1269 auto *I2 = dyn_cast<Instruction>(RHS); 1270 if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 || 1271 ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail || 1272 (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) || 1273 (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) || 1274 (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) && 1275 ShallowScoreAtThisLevel)) 1276 return ShallowScoreAtThisLevel; 1277 assert(I1 && I2 && "Should have early exited."); 1278 1279 // Contains the I2 operand indexes that got matched with I1 operands. 1280 SmallSet<unsigned, 4> Op2Used; 1281 1282 // Recursion towards the operands of I1 and I2. We are trying all possible 1283 // operand pairs, and keeping track of the best score. 1284 for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands(); 1285 OpIdx1 != NumOperands1; ++OpIdx1) { 1286 // Try to pair op1I with the best operand of I2. 1287 int MaxTmpScore = 0; 1288 unsigned MaxOpIdx2 = 0; 1289 bool FoundBest = false; 1290 // If I2 is commutative try all combinations. 1291 unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1; 1292 unsigned ToIdx = isCommutative(I2) 1293 ? I2->getNumOperands() 1294 : std::min(I2->getNumOperands(), OpIdx1 + 1); 1295 assert(FromIdx <= ToIdx && "Bad index"); 1296 for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) { 1297 // Skip operands already paired with OpIdx1. 1298 if (Op2Used.count(OpIdx2)) 1299 continue; 1300 // Recursively calculate the cost at each level 1301 int TmpScore = 1302 getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2), 1303 I1, I2, CurrLevel + 1, None); 1304 // Look for the best score. 1305 if (TmpScore > LookAheadHeuristics::ScoreFail && 1306 TmpScore > MaxTmpScore) { 1307 MaxTmpScore = TmpScore; 1308 MaxOpIdx2 = OpIdx2; 1309 FoundBest = true; 1310 } 1311 } 1312 if (FoundBest) { 1313 // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it. 1314 Op2Used.insert(MaxOpIdx2); 1315 ShallowScoreAtThisLevel += MaxTmpScore; 1316 } 1317 } 1318 return ShallowScoreAtThisLevel; 1319 } 1320 }; 1321 /// A helper data structure to hold the operands of a vector of instructions. 1322 /// This supports a fixed vector length for all operand vectors. 1323 class VLOperands { 1324 /// For each operand we need (i) the value, and (ii) the opcode that it 1325 /// would be attached to if the expression was in a left-linearized form. 1326 /// This is required to avoid illegal operand reordering. 1327 /// For example: 1328 /// \verbatim 1329 /// 0 Op1 1330 /// |/ 1331 /// Op1 Op2 Linearized + Op2 1332 /// \ / ----------> |/ 1333 /// - - 1334 /// 1335 /// Op1 - Op2 (0 + Op1) - Op2 1336 /// \endverbatim 1337 /// 1338 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'. 1339 /// 1340 /// Another way to think of this is to track all the operations across the 1341 /// path from the operand all the way to the root of the tree and to 1342 /// calculate the operation that corresponds to this path. For example, the 1343 /// path from Op2 to the root crosses the RHS of the '-', therefore the 1344 /// corresponding operation is a '-' (which matches the one in the 1345 /// linearized tree, as shown above). 1346 /// 1347 /// For lack of a better term, we refer to this operation as Accumulated 1348 /// Path Operation (APO). 1349 struct OperandData { 1350 OperandData() = default; 1351 OperandData(Value *V, bool APO, bool IsUsed) 1352 : V(V), APO(APO), IsUsed(IsUsed) {} 1353 /// The operand value. 1354 Value *V = nullptr; 1355 /// TreeEntries only allow a single opcode, or an alternate sequence of 1356 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the 1357 /// APO. It is set to 'true' if 'V' is attached to an inverse operation 1358 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise 1359 /// (e.g., Add/Mul) 1360 bool APO = false; 1361 /// Helper data for the reordering function. 1362 bool IsUsed = false; 1363 }; 1364 1365 /// During operand reordering, we are trying to select the operand at lane 1366 /// that matches best with the operand at the neighboring lane. Our 1367 /// selection is based on the type of value we are looking for. For example, 1368 /// if the neighboring lane has a load, we need to look for a load that is 1369 /// accessing a consecutive address. These strategies are summarized in the 1370 /// 'ReorderingMode' enumerator. 1371 enum class ReorderingMode { 1372 Load, ///< Matching loads to consecutive memory addresses 1373 Opcode, ///< Matching instructions based on opcode (same or alternate) 1374 Constant, ///< Matching constants 1375 Splat, ///< Matching the same instruction multiple times (broadcast) 1376 Failed, ///< We failed to create a vectorizable group 1377 }; 1378 1379 using OperandDataVec = SmallVector<OperandData, 2>; 1380 1381 /// A vector of operand vectors. 1382 SmallVector<OperandDataVec, 4> OpsVec; 1383 1384 const DataLayout &DL; 1385 ScalarEvolution &SE; 1386 const BoUpSLP &R; 1387 1388 /// \returns the operand data at \p OpIdx and \p Lane. 1389 OperandData &getData(unsigned OpIdx, unsigned Lane) { 1390 return OpsVec[OpIdx][Lane]; 1391 } 1392 1393 /// \returns the operand data at \p OpIdx and \p Lane. Const version. 1394 const OperandData &getData(unsigned OpIdx, unsigned Lane) const { 1395 return OpsVec[OpIdx][Lane]; 1396 } 1397 1398 /// Clears the used flag for all entries. 1399 void clearUsed() { 1400 for (unsigned OpIdx = 0, NumOperands = getNumOperands(); 1401 OpIdx != NumOperands; ++OpIdx) 1402 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes; 1403 ++Lane) 1404 OpsVec[OpIdx][Lane].IsUsed = false; 1405 } 1406 1407 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2. 1408 void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) { 1409 std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]); 1410 } 1411 1412 /// \param Lane lane of the operands under analysis. 1413 /// \param OpIdx operand index in \p Lane lane we're looking the best 1414 /// candidate for. 1415 /// \param Idx operand index of the current candidate value. 1416 /// \returns The additional score due to possible broadcasting of the 1417 /// elements in the lane. It is more profitable to have power-of-2 unique 1418 /// elements in the lane, it will be vectorized with higher probability 1419 /// after removing duplicates. Currently the SLP vectorizer supports only 1420 /// vectorization of the power-of-2 number of unique scalars. 1421 int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { 1422 Value *IdxLaneV = getData(Idx, Lane).V; 1423 if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V) 1424 return 0; 1425 SmallPtrSet<Value *, 4> Uniques; 1426 for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) { 1427 if (Ln == Lane) 1428 continue; 1429 Value *OpIdxLnV = getData(OpIdx, Ln).V; 1430 if (!isa<Instruction>(OpIdxLnV)) 1431 return 0; 1432 Uniques.insert(OpIdxLnV); 1433 } 1434 int UniquesCount = Uniques.size(); 1435 int UniquesCntWithIdxLaneV = 1436 Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1; 1437 Value *OpIdxLaneV = getData(OpIdx, Lane).V; 1438 int UniquesCntWithOpIdxLaneV = 1439 Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1; 1440 if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV) 1441 return 0; 1442 return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) - 1443 UniquesCntWithOpIdxLaneV) - 1444 (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV); 1445 } 1446 1447 /// \param Lane lane of the operands under analysis. 1448 /// \param OpIdx operand index in \p Lane lane we're looking the best 1449 /// candidate for. 1450 /// \param Idx operand index of the current candidate value. 1451 /// \returns The additional score for the scalar which users are all 1452 /// vectorized. 1453 int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { 1454 Value *IdxLaneV = getData(Idx, Lane).V; 1455 Value *OpIdxLaneV = getData(OpIdx, Lane).V; 1456 // Do not care about number of uses for vector-like instructions 1457 // (extractelement/extractvalue with constant indices), they are extracts 1458 // themselves and already externally used. Vectorization of such 1459 // instructions does not add extra extractelement instruction, just may 1460 // remove it. 1461 if (isVectorLikeInstWithConstOps(IdxLaneV) && 1462 isVectorLikeInstWithConstOps(OpIdxLaneV)) 1463 return LookAheadHeuristics::ScoreAllUserVectorized; 1464 auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV); 1465 if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV)) 1466 return 0; 1467 return R.areAllUsersVectorized(IdxLaneI, None) 1468 ? LookAheadHeuristics::ScoreAllUserVectorized 1469 : 0; 1470 } 1471 1472 /// Score scaling factor for fully compatible instructions but with 1473 /// different number of external uses. Allows better selection of the 1474 /// instructions with less external uses. 1475 static const int ScoreScaleFactor = 10; 1476 1477 /// \Returns the look-ahead score, which tells us how much the sub-trees 1478 /// rooted at \p LHS and \p RHS match, the more they match the higher the 1479 /// score. This helps break ties in an informed way when we cannot decide on 1480 /// the order of the operands by just considering the immediate 1481 /// predecessors. 1482 int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps, 1483 int Lane, unsigned OpIdx, unsigned Idx, 1484 bool &IsUsed) { 1485 LookAheadHeuristics LookAhead(DL, SE, R, getNumLanes(), 1486 LookAheadMaxDepth); 1487 // Keep track of the instruction stack as we recurse into the operands 1488 // during the look-ahead score exploration. 1489 int Score = 1490 LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr, 1491 /*CurrLevel=*/1, MainAltOps); 1492 if (Score) { 1493 int SplatScore = getSplatScore(Lane, OpIdx, Idx); 1494 if (Score <= -SplatScore) { 1495 // Set the minimum score for splat-like sequence to avoid setting 1496 // failed state. 1497 Score = 1; 1498 } else { 1499 Score += SplatScore; 1500 // Scale score to see the difference between different operands 1501 // and similar operands but all vectorized/not all vectorized 1502 // uses. It does not affect actual selection of the best 1503 // compatible operand in general, just allows to select the 1504 // operand with all vectorized uses. 1505 Score *= ScoreScaleFactor; 1506 Score += getExternalUseScore(Lane, OpIdx, Idx); 1507 IsUsed = true; 1508 } 1509 } 1510 return Score; 1511 } 1512 1513 /// Best defined scores per lanes between the passes. Used to choose the 1514 /// best operand (with the highest score) between the passes. 1515 /// The key - {Operand Index, Lane}. 1516 /// The value - the best score between the passes for the lane and the 1517 /// operand. 1518 SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8> 1519 BestScoresPerLanes; 1520 1521 // Search all operands in Ops[*][Lane] for the one that matches best 1522 // Ops[OpIdx][LastLane] and return its opreand index. 1523 // If no good match can be found, return None. 1524 Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane, 1525 ArrayRef<ReorderingMode> ReorderingModes, 1526 ArrayRef<Value *> MainAltOps) { 1527 unsigned NumOperands = getNumOperands(); 1528 1529 // The operand of the previous lane at OpIdx. 1530 Value *OpLastLane = getData(OpIdx, LastLane).V; 1531 1532 // Our strategy mode for OpIdx. 1533 ReorderingMode RMode = ReorderingModes[OpIdx]; 1534 if (RMode == ReorderingMode::Failed) 1535 return None; 1536 1537 // The linearized opcode of the operand at OpIdx, Lane. 1538 bool OpIdxAPO = getData(OpIdx, Lane).APO; 1539 1540 // The best operand index and its score. 1541 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we 1542 // are using the score to differentiate between the two. 1543 struct BestOpData { 1544 Optional<unsigned> Idx = None; 1545 unsigned Score = 0; 1546 } BestOp; 1547 BestOp.Score = 1548 BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0) 1549 .first->second; 1550 1551 // Track if the operand must be marked as used. If the operand is set to 1552 // Score 1 explicitly (because of non power-of-2 unique scalars, we may 1553 // want to reestimate the operands again on the following iterations). 1554 bool IsUsed = 1555 RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant; 1556 // Iterate through all unused operands and look for the best. 1557 for (unsigned Idx = 0; Idx != NumOperands; ++Idx) { 1558 // Get the operand at Idx and Lane. 1559 OperandData &OpData = getData(Idx, Lane); 1560 Value *Op = OpData.V; 1561 bool OpAPO = OpData.APO; 1562 1563 // Skip already selected operands. 1564 if (OpData.IsUsed) 1565 continue; 1566 1567 // Skip if we are trying to move the operand to a position with a 1568 // different opcode in the linearized tree form. This would break the 1569 // semantics. 1570 if (OpAPO != OpIdxAPO) 1571 continue; 1572 1573 // Look for an operand that matches the current mode. 1574 switch (RMode) { 1575 case ReorderingMode::Load: 1576 case ReorderingMode::Constant: 1577 case ReorderingMode::Opcode: { 1578 bool LeftToRight = Lane > LastLane; 1579 Value *OpLeft = (LeftToRight) ? OpLastLane : Op; 1580 Value *OpRight = (LeftToRight) ? Op : OpLastLane; 1581 int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane, 1582 OpIdx, Idx, IsUsed); 1583 if (Score > static_cast<int>(BestOp.Score)) { 1584 BestOp.Idx = Idx; 1585 BestOp.Score = Score; 1586 BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score; 1587 } 1588 break; 1589 } 1590 case ReorderingMode::Splat: 1591 if (Op == OpLastLane) 1592 BestOp.Idx = Idx; 1593 break; 1594 case ReorderingMode::Failed: 1595 llvm_unreachable("Not expected Failed reordering mode."); 1596 } 1597 } 1598 1599 if (BestOp.Idx) { 1600 getData(*BestOp.Idx, Lane).IsUsed = IsUsed; 1601 return BestOp.Idx; 1602 } 1603 // If we could not find a good match return None. 1604 return None; 1605 } 1606 1607 /// Helper for reorderOperandVecs. 1608 /// \returns the lane that we should start reordering from. This is the one 1609 /// which has the least number of operands that can freely move about or 1610 /// less profitable because it already has the most optimal set of operands. 1611 unsigned getBestLaneToStartReordering() const { 1612 unsigned Min = UINT_MAX; 1613 unsigned SameOpNumber = 0; 1614 // std::pair<unsigned, unsigned> is used to implement a simple voting 1615 // algorithm and choose the lane with the least number of operands that 1616 // can freely move about or less profitable because it already has the 1617 // most optimal set of operands. The first unsigned is a counter for 1618 // voting, the second unsigned is the counter of lanes with instructions 1619 // with same/alternate opcodes and same parent basic block. 1620 MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap; 1621 // Try to be closer to the original results, if we have multiple lanes 1622 // with same cost. If 2 lanes have the same cost, use the one with the 1623 // lowest index. 1624 for (int I = getNumLanes(); I > 0; --I) { 1625 unsigned Lane = I - 1; 1626 OperandsOrderData NumFreeOpsHash = 1627 getMaxNumOperandsThatCanBeReordered(Lane); 1628 // Compare the number of operands that can move and choose the one with 1629 // the least number. 1630 if (NumFreeOpsHash.NumOfAPOs < Min) { 1631 Min = NumFreeOpsHash.NumOfAPOs; 1632 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; 1633 HashMap.clear(); 1634 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1635 } else if (NumFreeOpsHash.NumOfAPOs == Min && 1636 NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) { 1637 // Select the most optimal lane in terms of number of operands that 1638 // should be moved around. 1639 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; 1640 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1641 } else if (NumFreeOpsHash.NumOfAPOs == Min && 1642 NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) { 1643 auto It = HashMap.find(NumFreeOpsHash.Hash); 1644 if (It == HashMap.end()) 1645 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1646 else 1647 ++It->second.first; 1648 } 1649 } 1650 // Select the lane with the minimum counter. 1651 unsigned BestLane = 0; 1652 unsigned CntMin = UINT_MAX; 1653 for (const auto &Data : reverse(HashMap)) { 1654 if (Data.second.first < CntMin) { 1655 CntMin = Data.second.first; 1656 BestLane = Data.second.second; 1657 } 1658 } 1659 return BestLane; 1660 } 1661 1662 /// Data structure that helps to reorder operands. 1663 struct OperandsOrderData { 1664 /// The best number of operands with the same APOs, which can be 1665 /// reordered. 1666 unsigned NumOfAPOs = UINT_MAX; 1667 /// Number of operands with the same/alternate instruction opcode and 1668 /// parent. 1669 unsigned NumOpsWithSameOpcodeParent = 0; 1670 /// Hash for the actual operands ordering. 1671 /// Used to count operands, actually their position id and opcode 1672 /// value. It is used in the voting mechanism to find the lane with the 1673 /// least number of operands that can freely move about or less profitable 1674 /// because it already has the most optimal set of operands. Can be 1675 /// replaced with SmallVector<unsigned> instead but hash code is faster 1676 /// and requires less memory. 1677 unsigned Hash = 0; 1678 }; 1679 /// \returns the maximum number of operands that are allowed to be reordered 1680 /// for \p Lane and the number of compatible instructions(with the same 1681 /// parent/opcode). This is used as a heuristic for selecting the first lane 1682 /// to start operand reordering. 1683 OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const { 1684 unsigned CntTrue = 0; 1685 unsigned NumOperands = getNumOperands(); 1686 // Operands with the same APO can be reordered. We therefore need to count 1687 // how many of them we have for each APO, like this: Cnt[APO] = x. 1688 // Since we only have two APOs, namely true and false, we can avoid using 1689 // a map. Instead we can simply count the number of operands that 1690 // correspond to one of them (in this case the 'true' APO), and calculate 1691 // the other by subtracting it from the total number of operands. 1692 // Operands with the same instruction opcode and parent are more 1693 // profitable since we don't need to move them in many cases, with a high 1694 // probability such lane already can be vectorized effectively. 1695 bool AllUndefs = true; 1696 unsigned NumOpsWithSameOpcodeParent = 0; 1697 Instruction *OpcodeI = nullptr; 1698 BasicBlock *Parent = nullptr; 1699 unsigned Hash = 0; 1700 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1701 const OperandData &OpData = getData(OpIdx, Lane); 1702 if (OpData.APO) 1703 ++CntTrue; 1704 // Use Boyer-Moore majority voting for finding the majority opcode and 1705 // the number of times it occurs. 1706 if (auto *I = dyn_cast<Instruction>(OpData.V)) { 1707 if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() || 1708 I->getParent() != Parent) { 1709 if (NumOpsWithSameOpcodeParent == 0) { 1710 NumOpsWithSameOpcodeParent = 1; 1711 OpcodeI = I; 1712 Parent = I->getParent(); 1713 } else { 1714 --NumOpsWithSameOpcodeParent; 1715 } 1716 } else { 1717 ++NumOpsWithSameOpcodeParent; 1718 } 1719 } 1720 Hash = hash_combine( 1721 Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1))); 1722 AllUndefs = AllUndefs && isa<UndefValue>(OpData.V); 1723 } 1724 if (AllUndefs) 1725 return {}; 1726 OperandsOrderData Data; 1727 Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue); 1728 Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent; 1729 Data.Hash = Hash; 1730 return Data; 1731 } 1732 1733 /// Go through the instructions in VL and append their operands. 1734 void appendOperandsOfVL(ArrayRef<Value *> VL) { 1735 assert(!VL.empty() && "Bad VL"); 1736 assert((empty() || VL.size() == getNumLanes()) && 1737 "Expected same number of lanes"); 1738 assert(isa<Instruction>(VL[0]) && "Expected instruction"); 1739 unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands(); 1740 OpsVec.resize(NumOperands); 1741 unsigned NumLanes = VL.size(); 1742 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1743 OpsVec[OpIdx].resize(NumLanes); 1744 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 1745 assert(isa<Instruction>(VL[Lane]) && "Expected instruction"); 1746 // Our tree has just 3 nodes: the root and two operands. 1747 // It is therefore trivial to get the APO. We only need to check the 1748 // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or 1749 // RHS operand. The LHS operand of both add and sub is never attached 1750 // to an inversese operation in the linearized form, therefore its APO 1751 // is false. The RHS is true only if VL[Lane] is an inverse operation. 1752 1753 // Since operand reordering is performed on groups of commutative 1754 // operations or alternating sequences (e.g., +, -), we can safely 1755 // tell the inverse operations by checking commutativity. 1756 bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane])); 1757 bool APO = (OpIdx == 0) ? false : IsInverseOperation; 1758 OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx), 1759 APO, false}; 1760 } 1761 } 1762 } 1763 1764 /// \returns the number of operands. 1765 unsigned getNumOperands() const { return OpsVec.size(); } 1766 1767 /// \returns the number of lanes. 1768 unsigned getNumLanes() const { return OpsVec[0].size(); } 1769 1770 /// \returns the operand value at \p OpIdx and \p Lane. 1771 Value *getValue(unsigned OpIdx, unsigned Lane) const { 1772 return getData(OpIdx, Lane).V; 1773 } 1774 1775 /// \returns true if the data structure is empty. 1776 bool empty() const { return OpsVec.empty(); } 1777 1778 /// Clears the data. 1779 void clear() { OpsVec.clear(); } 1780 1781 /// \Returns true if there are enough operands identical to \p Op to fill 1782 /// the whole vector. 1783 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow. 1784 bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) { 1785 bool OpAPO = getData(OpIdx, Lane).APO; 1786 for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) { 1787 if (Ln == Lane) 1788 continue; 1789 // This is set to true if we found a candidate for broadcast at Lane. 1790 bool FoundCandidate = false; 1791 for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) { 1792 OperandData &Data = getData(OpI, Ln); 1793 if (Data.APO != OpAPO || Data.IsUsed) 1794 continue; 1795 if (Data.V == Op) { 1796 FoundCandidate = true; 1797 Data.IsUsed = true; 1798 break; 1799 } 1800 } 1801 if (!FoundCandidate) 1802 return false; 1803 } 1804 return true; 1805 } 1806 1807 public: 1808 /// Initialize with all the operands of the instruction vector \p RootVL. 1809 VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL, 1810 ScalarEvolution &SE, const BoUpSLP &R) 1811 : DL(DL), SE(SE), R(R) { 1812 // Append all the operands of RootVL. 1813 appendOperandsOfVL(RootVL); 1814 } 1815 1816 /// \Returns a value vector with the operands across all lanes for the 1817 /// opearnd at \p OpIdx. 1818 ValueList getVL(unsigned OpIdx) const { 1819 ValueList OpVL(OpsVec[OpIdx].size()); 1820 assert(OpsVec[OpIdx].size() == getNumLanes() && 1821 "Expected same num of lanes across all operands"); 1822 for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane) 1823 OpVL[Lane] = OpsVec[OpIdx][Lane].V; 1824 return OpVL; 1825 } 1826 1827 // Performs operand reordering for 2 or more operands. 1828 // The original operands are in OrigOps[OpIdx][Lane]. 1829 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'. 1830 void reorder() { 1831 unsigned NumOperands = getNumOperands(); 1832 unsigned NumLanes = getNumLanes(); 1833 // Each operand has its own mode. We are using this mode to help us select 1834 // the instructions for each lane, so that they match best with the ones 1835 // we have selected so far. 1836 SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands); 1837 1838 // This is a greedy single-pass algorithm. We are going over each lane 1839 // once and deciding on the best order right away with no back-tracking. 1840 // However, in order to increase its effectiveness, we start with the lane 1841 // that has operands that can move the least. For example, given the 1842 // following lanes: 1843 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd 1844 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st 1845 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd 1846 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th 1847 // we will start at Lane 1, since the operands of the subtraction cannot 1848 // be reordered. Then we will visit the rest of the lanes in a circular 1849 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3. 1850 1851 // Find the first lane that we will start our search from. 1852 unsigned FirstLane = getBestLaneToStartReordering(); 1853 1854 // Initialize the modes. 1855 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1856 Value *OpLane0 = getValue(OpIdx, FirstLane); 1857 // Keep track if we have instructions with all the same opcode on one 1858 // side. 1859 if (isa<LoadInst>(OpLane0)) 1860 ReorderingModes[OpIdx] = ReorderingMode::Load; 1861 else if (isa<Instruction>(OpLane0)) { 1862 // Check if OpLane0 should be broadcast. 1863 if (shouldBroadcast(OpLane0, OpIdx, FirstLane)) 1864 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1865 else 1866 ReorderingModes[OpIdx] = ReorderingMode::Opcode; 1867 } 1868 else if (isa<Constant>(OpLane0)) 1869 ReorderingModes[OpIdx] = ReorderingMode::Constant; 1870 else if (isa<Argument>(OpLane0)) 1871 // Our best hope is a Splat. It may save some cost in some cases. 1872 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1873 else 1874 // NOTE: This should be unreachable. 1875 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1876 } 1877 1878 // Check that we don't have same operands. No need to reorder if operands 1879 // are just perfect diamond or shuffled diamond match. Do not do it only 1880 // for possible broadcasts or non-power of 2 number of scalars (just for 1881 // now). 1882 auto &&SkipReordering = [this]() { 1883 SmallPtrSet<Value *, 4> UniqueValues; 1884 ArrayRef<OperandData> Op0 = OpsVec.front(); 1885 for (const OperandData &Data : Op0) 1886 UniqueValues.insert(Data.V); 1887 for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) { 1888 if (any_of(Op, [&UniqueValues](const OperandData &Data) { 1889 return !UniqueValues.contains(Data.V); 1890 })) 1891 return false; 1892 } 1893 // TODO: Check if we can remove a check for non-power-2 number of 1894 // scalars after full support of non-power-2 vectorization. 1895 return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size()); 1896 }; 1897 1898 // If the initial strategy fails for any of the operand indexes, then we 1899 // perform reordering again in a second pass. This helps avoid assigning 1900 // high priority to the failed strategy, and should improve reordering for 1901 // the non-failed operand indexes. 1902 for (int Pass = 0; Pass != 2; ++Pass) { 1903 // Check if no need to reorder operands since they're are perfect or 1904 // shuffled diamond match. 1905 // Need to to do it to avoid extra external use cost counting for 1906 // shuffled matches, which may cause regressions. 1907 if (SkipReordering()) 1908 break; 1909 // Skip the second pass if the first pass did not fail. 1910 bool StrategyFailed = false; 1911 // Mark all operand data as free to use. 1912 clearUsed(); 1913 // We keep the original operand order for the FirstLane, so reorder the 1914 // rest of the lanes. We are visiting the nodes in a circular fashion, 1915 // using FirstLane as the center point and increasing the radius 1916 // distance. 1917 SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands); 1918 for (unsigned I = 0; I < NumOperands; ++I) 1919 MainAltOps[I].push_back(getData(I, FirstLane).V); 1920 1921 for (unsigned Distance = 1; Distance != NumLanes; ++Distance) { 1922 // Visit the lane on the right and then the lane on the left. 1923 for (int Direction : {+1, -1}) { 1924 int Lane = FirstLane + Direction * Distance; 1925 if (Lane < 0 || Lane >= (int)NumLanes) 1926 continue; 1927 int LastLane = Lane - Direction; 1928 assert(LastLane >= 0 && LastLane < (int)NumLanes && 1929 "Out of bounds"); 1930 // Look for a good match for each operand. 1931 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1932 // Search for the operand that matches SortedOps[OpIdx][Lane-1]. 1933 Optional<unsigned> BestIdx = getBestOperand( 1934 OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]); 1935 // By not selecting a value, we allow the operands that follow to 1936 // select a better matching value. We will get a non-null value in 1937 // the next run of getBestOperand(). 1938 if (BestIdx) { 1939 // Swap the current operand with the one returned by 1940 // getBestOperand(). 1941 swap(OpIdx, *BestIdx, Lane); 1942 } else { 1943 // We failed to find a best operand, set mode to 'Failed'. 1944 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1945 // Enable the second pass. 1946 StrategyFailed = true; 1947 } 1948 // Try to get the alternate opcode and follow it during analysis. 1949 if (MainAltOps[OpIdx].size() != 2) { 1950 OperandData &AltOp = getData(OpIdx, Lane); 1951 InstructionsState OpS = 1952 getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V}); 1953 if (OpS.getOpcode() && OpS.isAltShuffle()) 1954 MainAltOps[OpIdx].push_back(AltOp.V); 1955 } 1956 } 1957 } 1958 } 1959 // Skip second pass if the strategy did not fail. 1960 if (!StrategyFailed) 1961 break; 1962 } 1963 } 1964 1965 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1966 LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) { 1967 switch (RMode) { 1968 case ReorderingMode::Load: 1969 return "Load"; 1970 case ReorderingMode::Opcode: 1971 return "Opcode"; 1972 case ReorderingMode::Constant: 1973 return "Constant"; 1974 case ReorderingMode::Splat: 1975 return "Splat"; 1976 case ReorderingMode::Failed: 1977 return "Failed"; 1978 } 1979 llvm_unreachable("Unimplemented Reordering Type"); 1980 } 1981 1982 LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode, 1983 raw_ostream &OS) { 1984 return OS << getModeStr(RMode); 1985 } 1986 1987 /// Debug print. 1988 LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) { 1989 printMode(RMode, dbgs()); 1990 } 1991 1992 friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) { 1993 return printMode(RMode, OS); 1994 } 1995 1996 LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const { 1997 const unsigned Indent = 2; 1998 unsigned Cnt = 0; 1999 for (const OperandDataVec &OpDataVec : OpsVec) { 2000 OS << "Operand " << Cnt++ << "\n"; 2001 for (const OperandData &OpData : OpDataVec) { 2002 OS.indent(Indent) << "{"; 2003 if (Value *V = OpData.V) 2004 OS << *V; 2005 else 2006 OS << "null"; 2007 OS << ", APO:" << OpData.APO << "}\n"; 2008 } 2009 OS << "\n"; 2010 } 2011 return OS; 2012 } 2013 2014 /// Debug print. 2015 LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 2016 #endif 2017 }; 2018 2019 /// Evaluate each pair in \p Candidates and return index into \p Candidates 2020 /// for a pair which have highest score deemed to have best chance to form 2021 /// root of profitable tree to vectorize. Return None if no candidate scored 2022 /// above the LookAheadHeuristics::ScoreFail. 2023 /// \param Limit Lower limit of the cost, considered to be good enough score. 2024 Optional<int> 2025 findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates, 2026 int Limit = LookAheadHeuristics::ScoreFail) { 2027 LookAheadHeuristics LookAhead(*DL, *SE, *this, /*NumLanes=*/2, 2028 RootLookAheadMaxDepth); 2029 int BestScore = Limit; 2030 Optional<int> Index = None; 2031 for (int I : seq<int>(0, Candidates.size())) { 2032 int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first, 2033 Candidates[I].second, 2034 /*U1=*/nullptr, /*U2=*/nullptr, 2035 /*Level=*/1, None); 2036 if (Score > BestScore) { 2037 BestScore = Score; 2038 Index = I; 2039 } 2040 } 2041 return Index; 2042 } 2043 2044 /// Checks if the instruction is marked for deletion. 2045 bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); } 2046 2047 /// Removes an instruction from its block and eventually deletes it. 2048 /// It's like Instruction::eraseFromParent() except that the actual deletion 2049 /// is delayed until BoUpSLP is destructed. 2050 void eraseInstruction(Instruction *I) { 2051 DeletedInstructions.insert(I); 2052 } 2053 2054 /// Checks if the instruction was already analyzed for being possible 2055 /// reduction root. 2056 bool isAnalyzedReductionRoot(Instruction *I) const { 2057 return AnalyzedReductionsRoots.count(I); 2058 } 2059 /// Register given instruction as already analyzed for being possible 2060 /// reduction root. 2061 void analyzedReductionRoot(Instruction *I) { 2062 AnalyzedReductionsRoots.insert(I); 2063 } 2064 /// Checks if the provided list of reduced values was checked already for 2065 /// vectorization. 2066 bool areAnalyzedReductionVals(ArrayRef<Value *> VL) { 2067 return AnalyzedReductionVals.contains(hash_value(VL)); 2068 } 2069 /// Adds the list of reduced values to list of already checked values for the 2070 /// vectorization. 2071 void analyzedReductionVals(ArrayRef<Value *> VL) { 2072 AnalyzedReductionVals.insert(hash_value(VL)); 2073 } 2074 /// Clear the list of the analyzed reduction root instructions. 2075 void clearReductionData() { 2076 AnalyzedReductionsRoots.clear(); 2077 AnalyzedReductionVals.clear(); 2078 } 2079 /// Checks if the given value is gathered in one of the nodes. 2080 bool isAnyGathered(const SmallDenseSet<Value *> &Vals) const { 2081 return any_of(MustGather, [&](Value *V) { return Vals.contains(V); }); 2082 } 2083 2084 ~BoUpSLP(); 2085 2086 private: 2087 /// Check if the operands on the edges \p Edges of the \p UserTE allows 2088 /// reordering (i.e. the operands can be reordered because they have only one 2089 /// user and reordarable). 2090 /// \param ReorderableGathers List of all gather nodes that require reordering 2091 /// (e.g., gather of extractlements or partially vectorizable loads). 2092 /// \param GatherOps List of gather operand nodes for \p UserTE that require 2093 /// reordering, subset of \p NonVectorized. 2094 bool 2095 canReorderOperands(TreeEntry *UserTE, 2096 SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges, 2097 ArrayRef<TreeEntry *> ReorderableGathers, 2098 SmallVectorImpl<TreeEntry *> &GatherOps); 2099 2100 /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph, 2101 /// if any. If it is not vectorized (gather node), returns nullptr. 2102 TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) { 2103 ArrayRef<Value *> VL = UserTE->getOperand(OpIdx); 2104 TreeEntry *TE = nullptr; 2105 const auto *It = find_if(VL, [this, &TE](Value *V) { 2106 TE = getTreeEntry(V); 2107 return TE; 2108 }); 2109 if (It != VL.end() && TE->isSame(VL)) 2110 return TE; 2111 return nullptr; 2112 } 2113 2114 /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph, 2115 /// if any. If it is not vectorized (gather node), returns nullptr. 2116 const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE, 2117 unsigned OpIdx) const { 2118 return const_cast<BoUpSLP *>(this)->getVectorizedOperand( 2119 const_cast<TreeEntry *>(UserTE), OpIdx); 2120 } 2121 2122 /// Checks if all users of \p I are the part of the vectorization tree. 2123 bool areAllUsersVectorized(Instruction *I, 2124 ArrayRef<Value *> VectorizedVals) const; 2125 2126 /// \returns the cost of the vectorizable entry. 2127 InstructionCost getEntryCost(const TreeEntry *E, 2128 ArrayRef<Value *> VectorizedVals); 2129 2130 /// This is the recursive part of buildTree. 2131 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, 2132 const EdgeInfo &EI); 2133 2134 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can 2135 /// be vectorized to use the original vector (or aggregate "bitcast" to a 2136 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise 2137 /// returns false, setting \p CurrentOrder to either an empty vector or a 2138 /// non-identity permutation that allows to reuse extract instructions. 2139 bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 2140 SmallVectorImpl<unsigned> &CurrentOrder) const; 2141 2142 /// Vectorize a single entry in the tree. 2143 Value *vectorizeTree(TreeEntry *E); 2144 2145 /// Vectorize a single entry in the tree, starting in \p VL. 2146 Value *vectorizeTree(ArrayRef<Value *> VL); 2147 2148 /// Create a new vector from a list of scalar values. Produces a sequence 2149 /// which exploits values reused across lanes, and arranges the inserts 2150 /// for ease of later optimization. 2151 Value *createBuildVector(ArrayRef<Value *> VL); 2152 2153 /// \returns the scalarization cost for this type. Scalarization in this 2154 /// context means the creation of vectors from a group of scalars. If \p 2155 /// NeedToShuffle is true, need to add a cost of reshuffling some of the 2156 /// vector elements. 2157 InstructionCost getGatherCost(FixedVectorType *Ty, 2158 const APInt &ShuffledIndices, 2159 bool NeedToShuffle) const; 2160 2161 /// Checks if the gathered \p VL can be represented as shuffle(s) of previous 2162 /// tree entries. 2163 /// \returns ShuffleKind, if gathered values can be represented as shuffles of 2164 /// previous tree entries. \p Mask is filled with the shuffle mask. 2165 Optional<TargetTransformInfo::ShuffleKind> 2166 isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 2167 SmallVectorImpl<const TreeEntry *> &Entries); 2168 2169 /// \returns the scalarization cost for this list of values. Assuming that 2170 /// this subtree gets vectorized, we may need to extract the values from the 2171 /// roots. This method calculates the cost of extracting the values. 2172 InstructionCost getGatherCost(ArrayRef<Value *> VL) const; 2173 2174 /// Set the Builder insert point to one after the last instruction in 2175 /// the bundle 2176 void setInsertPointAfterBundle(const TreeEntry *E); 2177 2178 /// \returns a vector from a collection of scalars in \p VL. 2179 Value *gather(ArrayRef<Value *> VL); 2180 2181 /// \returns whether the VectorizableTree is fully vectorizable and will 2182 /// be beneficial even the tree height is tiny. 2183 bool isFullyVectorizableTinyTree(bool ForReduction) const; 2184 2185 /// Reorder commutative or alt operands to get better probability of 2186 /// generating vectorized code. 2187 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 2188 SmallVectorImpl<Value *> &Left, 2189 SmallVectorImpl<Value *> &Right, 2190 const DataLayout &DL, 2191 ScalarEvolution &SE, 2192 const BoUpSLP &R); 2193 2194 /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the 2195 /// users of \p TE and collects the stores. It returns the map from the store 2196 /// pointers to the collected stores. 2197 DenseMap<Value *, SmallVector<StoreInst *, 4>> 2198 collectUserStores(const BoUpSLP::TreeEntry *TE) const; 2199 2200 /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the 2201 /// stores in \p StoresVec can for a vector instruction. If so it returns true 2202 /// and populates \p ReorderIndices with the shuffle indices of the the stores 2203 /// when compared to the sorted vector. 2204 bool CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec, 2205 OrdersType &ReorderIndices) const; 2206 2207 /// Iterates through the users of \p TE, looking for scalar stores that can be 2208 /// potentially vectorized in a future SLP-tree. If found, it keeps track of 2209 /// their order and builds an order index vector for each store bundle. It 2210 /// returns all these order vectors found. 2211 /// We run this after the tree has formed, otherwise we may come across user 2212 /// instructions that are not yet in the tree. 2213 SmallVector<OrdersType, 1> 2214 findExternalStoreUsersReorderIndices(TreeEntry *TE) const; 2215 2216 struct TreeEntry { 2217 using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>; 2218 TreeEntry(VecTreeTy &Container) : Container(Container) {} 2219 2220 /// \returns true if the scalars in VL are equal to this entry. 2221 bool isSame(ArrayRef<Value *> VL) const { 2222 auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) { 2223 if (Mask.size() != VL.size() && VL.size() == Scalars.size()) 2224 return std::equal(VL.begin(), VL.end(), Scalars.begin()); 2225 return VL.size() == Mask.size() && 2226 std::equal(VL.begin(), VL.end(), Mask.begin(), 2227 [Scalars](Value *V, int Idx) { 2228 return (isa<UndefValue>(V) && 2229 Idx == UndefMaskElem) || 2230 (Idx != UndefMaskElem && V == Scalars[Idx]); 2231 }); 2232 }; 2233 if (!ReorderIndices.empty()) { 2234 // TODO: implement matching if the nodes are just reordered, still can 2235 // treat the vector as the same if the list of scalars matches VL 2236 // directly, without reordering. 2237 SmallVector<int> Mask; 2238 inversePermutation(ReorderIndices, Mask); 2239 if (VL.size() == Scalars.size()) 2240 return IsSame(Scalars, Mask); 2241 if (VL.size() == ReuseShuffleIndices.size()) { 2242 ::addMask(Mask, ReuseShuffleIndices); 2243 return IsSame(Scalars, Mask); 2244 } 2245 return false; 2246 } 2247 return IsSame(Scalars, ReuseShuffleIndices); 2248 } 2249 2250 /// \returns true if current entry has same operands as \p TE. 2251 bool hasEqualOperands(const TreeEntry &TE) const { 2252 if (TE.getNumOperands() != getNumOperands()) 2253 return false; 2254 SmallBitVector Used(getNumOperands()); 2255 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) { 2256 unsigned PrevCount = Used.count(); 2257 for (unsigned K = 0; K < E; ++K) { 2258 if (Used.test(K)) 2259 continue; 2260 if (getOperand(K) == TE.getOperand(I)) { 2261 Used.set(K); 2262 break; 2263 } 2264 } 2265 // Check if we actually found the matching operand. 2266 if (PrevCount == Used.count()) 2267 return false; 2268 } 2269 return true; 2270 } 2271 2272 /// \return Final vectorization factor for the node. Defined by the total 2273 /// number of vectorized scalars, including those, used several times in the 2274 /// entry and counted in the \a ReuseShuffleIndices, if any. 2275 unsigned getVectorFactor() const { 2276 if (!ReuseShuffleIndices.empty()) 2277 return ReuseShuffleIndices.size(); 2278 return Scalars.size(); 2279 }; 2280 2281 /// A vector of scalars. 2282 ValueList Scalars; 2283 2284 /// The Scalars are vectorized into this value. It is initialized to Null. 2285 Value *VectorizedValue = nullptr; 2286 2287 /// Do we need to gather this sequence or vectorize it 2288 /// (either with vector instruction or with scatter/gather 2289 /// intrinsics for store/load)? 2290 enum EntryState { Vectorize, ScatterVectorize, NeedToGather }; 2291 EntryState State; 2292 2293 /// Does this sequence require some shuffling? 2294 SmallVector<int, 4> ReuseShuffleIndices; 2295 2296 /// Does this entry require reordering? 2297 SmallVector<unsigned, 4> ReorderIndices; 2298 2299 /// Points back to the VectorizableTree. 2300 /// 2301 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has 2302 /// to be a pointer and needs to be able to initialize the child iterator. 2303 /// Thus we need a reference back to the container to translate the indices 2304 /// to entries. 2305 VecTreeTy &Container; 2306 2307 /// The TreeEntry index containing the user of this entry. We can actually 2308 /// have multiple users so the data structure is not truly a tree. 2309 SmallVector<EdgeInfo, 1> UserTreeIndices; 2310 2311 /// The index of this treeEntry in VectorizableTree. 2312 int Idx = -1; 2313 2314 private: 2315 /// The operands of each instruction in each lane Operands[op_index][lane]. 2316 /// Note: This helps avoid the replication of the code that performs the 2317 /// reordering of operands during buildTree_rec() and vectorizeTree(). 2318 SmallVector<ValueList, 2> Operands; 2319 2320 /// The main/alternate instruction. 2321 Instruction *MainOp = nullptr; 2322 Instruction *AltOp = nullptr; 2323 2324 public: 2325 /// Set this bundle's \p OpIdx'th operand to \p OpVL. 2326 void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) { 2327 if (Operands.size() < OpIdx + 1) 2328 Operands.resize(OpIdx + 1); 2329 assert(Operands[OpIdx].empty() && "Already resized?"); 2330 assert(OpVL.size() <= Scalars.size() && 2331 "Number of operands is greater than the number of scalars."); 2332 Operands[OpIdx].resize(OpVL.size()); 2333 copy(OpVL, Operands[OpIdx].begin()); 2334 } 2335 2336 /// Set the operands of this bundle in their original order. 2337 void setOperandsInOrder() { 2338 assert(Operands.empty() && "Already initialized?"); 2339 auto *I0 = cast<Instruction>(Scalars[0]); 2340 Operands.resize(I0->getNumOperands()); 2341 unsigned NumLanes = Scalars.size(); 2342 for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands(); 2343 OpIdx != NumOperands; ++OpIdx) { 2344 Operands[OpIdx].resize(NumLanes); 2345 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 2346 auto *I = cast<Instruction>(Scalars[Lane]); 2347 assert(I->getNumOperands() == NumOperands && 2348 "Expected same number of operands"); 2349 Operands[OpIdx][Lane] = I->getOperand(OpIdx); 2350 } 2351 } 2352 } 2353 2354 /// Reorders operands of the node to the given mask \p Mask. 2355 void reorderOperands(ArrayRef<int> Mask) { 2356 for (ValueList &Operand : Operands) 2357 reorderScalars(Operand, Mask); 2358 } 2359 2360 /// \returns the \p OpIdx operand of this TreeEntry. 2361 ValueList &getOperand(unsigned OpIdx) { 2362 assert(OpIdx < Operands.size() && "Off bounds"); 2363 return Operands[OpIdx]; 2364 } 2365 2366 /// \returns the \p OpIdx operand of this TreeEntry. 2367 ArrayRef<Value *> getOperand(unsigned OpIdx) const { 2368 assert(OpIdx < Operands.size() && "Off bounds"); 2369 return Operands[OpIdx]; 2370 } 2371 2372 /// \returns the number of operands. 2373 unsigned getNumOperands() const { return Operands.size(); } 2374 2375 /// \return the single \p OpIdx operand. 2376 Value *getSingleOperand(unsigned OpIdx) const { 2377 assert(OpIdx < Operands.size() && "Off bounds"); 2378 assert(!Operands[OpIdx].empty() && "No operand available"); 2379 return Operands[OpIdx][0]; 2380 } 2381 2382 /// Some of the instructions in the list have alternate opcodes. 2383 bool isAltShuffle() const { return MainOp != AltOp; } 2384 2385 bool isOpcodeOrAlt(Instruction *I) const { 2386 unsigned CheckedOpcode = I->getOpcode(); 2387 return (getOpcode() == CheckedOpcode || 2388 getAltOpcode() == CheckedOpcode); 2389 } 2390 2391 /// Chooses the correct key for scheduling data. If \p Op has the same (or 2392 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is 2393 /// \p OpValue. 2394 Value *isOneOf(Value *Op) const { 2395 auto *I = dyn_cast<Instruction>(Op); 2396 if (I && isOpcodeOrAlt(I)) 2397 return Op; 2398 return MainOp; 2399 } 2400 2401 void setOperations(const InstructionsState &S) { 2402 MainOp = S.MainOp; 2403 AltOp = S.AltOp; 2404 } 2405 2406 Instruction *getMainOp() const { 2407 return MainOp; 2408 } 2409 2410 Instruction *getAltOp() const { 2411 return AltOp; 2412 } 2413 2414 /// The main/alternate opcodes for the list of instructions. 2415 unsigned getOpcode() const { 2416 return MainOp ? MainOp->getOpcode() : 0; 2417 } 2418 2419 unsigned getAltOpcode() const { 2420 return AltOp ? AltOp->getOpcode() : 0; 2421 } 2422 2423 /// When ReuseReorderShuffleIndices is empty it just returns position of \p 2424 /// V within vector of Scalars. Otherwise, try to remap on its reuse index. 2425 int findLaneForValue(Value *V) const { 2426 unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V)); 2427 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 2428 if (!ReorderIndices.empty()) 2429 FoundLane = ReorderIndices[FoundLane]; 2430 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 2431 if (!ReuseShuffleIndices.empty()) { 2432 FoundLane = std::distance(ReuseShuffleIndices.begin(), 2433 find(ReuseShuffleIndices, FoundLane)); 2434 } 2435 return FoundLane; 2436 } 2437 2438 #ifndef NDEBUG 2439 /// Debug printer. 2440 LLVM_DUMP_METHOD void dump() const { 2441 dbgs() << Idx << ".\n"; 2442 for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) { 2443 dbgs() << "Operand " << OpI << ":\n"; 2444 for (const Value *V : Operands[OpI]) 2445 dbgs().indent(2) << *V << "\n"; 2446 } 2447 dbgs() << "Scalars: \n"; 2448 for (Value *V : Scalars) 2449 dbgs().indent(2) << *V << "\n"; 2450 dbgs() << "State: "; 2451 switch (State) { 2452 case Vectorize: 2453 dbgs() << "Vectorize\n"; 2454 break; 2455 case ScatterVectorize: 2456 dbgs() << "ScatterVectorize\n"; 2457 break; 2458 case NeedToGather: 2459 dbgs() << "NeedToGather\n"; 2460 break; 2461 } 2462 dbgs() << "MainOp: "; 2463 if (MainOp) 2464 dbgs() << *MainOp << "\n"; 2465 else 2466 dbgs() << "NULL\n"; 2467 dbgs() << "AltOp: "; 2468 if (AltOp) 2469 dbgs() << *AltOp << "\n"; 2470 else 2471 dbgs() << "NULL\n"; 2472 dbgs() << "VectorizedValue: "; 2473 if (VectorizedValue) 2474 dbgs() << *VectorizedValue << "\n"; 2475 else 2476 dbgs() << "NULL\n"; 2477 dbgs() << "ReuseShuffleIndices: "; 2478 if (ReuseShuffleIndices.empty()) 2479 dbgs() << "Empty"; 2480 else 2481 for (int ReuseIdx : ReuseShuffleIndices) 2482 dbgs() << ReuseIdx << ", "; 2483 dbgs() << "\n"; 2484 dbgs() << "ReorderIndices: "; 2485 for (unsigned ReorderIdx : ReorderIndices) 2486 dbgs() << ReorderIdx << ", "; 2487 dbgs() << "\n"; 2488 dbgs() << "UserTreeIndices: "; 2489 for (const auto &EInfo : UserTreeIndices) 2490 dbgs() << EInfo << ", "; 2491 dbgs() << "\n"; 2492 } 2493 #endif 2494 }; 2495 2496 #ifndef NDEBUG 2497 void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost, 2498 InstructionCost VecCost, 2499 InstructionCost ScalarCost) const { 2500 dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump(); 2501 dbgs() << "SLP: Costs:\n"; 2502 dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n"; 2503 dbgs() << "SLP: VectorCost = " << VecCost << "\n"; 2504 dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n"; 2505 dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = " << 2506 ReuseShuffleCost + VecCost - ScalarCost << "\n"; 2507 } 2508 #endif 2509 2510 /// Create a new VectorizableTree entry. 2511 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle, 2512 const InstructionsState &S, 2513 const EdgeInfo &UserTreeIdx, 2514 ArrayRef<int> ReuseShuffleIndices = None, 2515 ArrayRef<unsigned> ReorderIndices = None) { 2516 TreeEntry::EntryState EntryState = 2517 Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather; 2518 return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx, 2519 ReuseShuffleIndices, ReorderIndices); 2520 } 2521 2522 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, 2523 TreeEntry::EntryState EntryState, 2524 Optional<ScheduleData *> Bundle, 2525 const InstructionsState &S, 2526 const EdgeInfo &UserTreeIdx, 2527 ArrayRef<int> ReuseShuffleIndices = None, 2528 ArrayRef<unsigned> ReorderIndices = None) { 2529 assert(((!Bundle && EntryState == TreeEntry::NeedToGather) || 2530 (Bundle && EntryState != TreeEntry::NeedToGather)) && 2531 "Need to vectorize gather entry?"); 2532 VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree)); 2533 TreeEntry *Last = VectorizableTree.back().get(); 2534 Last->Idx = VectorizableTree.size() - 1; 2535 Last->State = EntryState; 2536 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(), 2537 ReuseShuffleIndices.end()); 2538 if (ReorderIndices.empty()) { 2539 Last->Scalars.assign(VL.begin(), VL.end()); 2540 Last->setOperations(S); 2541 } else { 2542 // Reorder scalars and build final mask. 2543 Last->Scalars.assign(VL.size(), nullptr); 2544 transform(ReorderIndices, Last->Scalars.begin(), 2545 [VL](unsigned Idx) -> Value * { 2546 if (Idx >= VL.size()) 2547 return UndefValue::get(VL.front()->getType()); 2548 return VL[Idx]; 2549 }); 2550 InstructionsState S = getSameOpcode(Last->Scalars); 2551 Last->setOperations(S); 2552 Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end()); 2553 } 2554 if (Last->State != TreeEntry::NeedToGather) { 2555 for (Value *V : VL) { 2556 assert(!getTreeEntry(V) && "Scalar already in tree!"); 2557 ScalarToTreeEntry[V] = Last; 2558 } 2559 // Update the scheduler bundle to point to this TreeEntry. 2560 ScheduleData *BundleMember = *Bundle; 2561 assert((BundleMember || isa<PHINode>(S.MainOp) || 2562 isVectorLikeInstWithConstOps(S.MainOp) || 2563 doesNotNeedToSchedule(VL)) && 2564 "Bundle and VL out of sync"); 2565 if (BundleMember) { 2566 for (Value *V : VL) { 2567 if (doesNotNeedToBeScheduled(V)) 2568 continue; 2569 assert(BundleMember && "Unexpected end of bundle."); 2570 BundleMember->TE = Last; 2571 BundleMember = BundleMember->NextInBundle; 2572 } 2573 } 2574 assert(!BundleMember && "Bundle and VL out of sync"); 2575 } else { 2576 MustGather.insert(VL.begin(), VL.end()); 2577 } 2578 2579 if (UserTreeIdx.UserTE) 2580 Last->UserTreeIndices.push_back(UserTreeIdx); 2581 2582 return Last; 2583 } 2584 2585 /// -- Vectorization State -- 2586 /// Holds all of the tree entries. 2587 TreeEntry::VecTreeTy VectorizableTree; 2588 2589 #ifndef NDEBUG 2590 /// Debug printer. 2591 LLVM_DUMP_METHOD void dumpVectorizableTree() const { 2592 for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) { 2593 VectorizableTree[Id]->dump(); 2594 dbgs() << "\n"; 2595 } 2596 } 2597 #endif 2598 2599 TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); } 2600 2601 const TreeEntry *getTreeEntry(Value *V) const { 2602 return ScalarToTreeEntry.lookup(V); 2603 } 2604 2605 /// Maps a specific scalar to its tree entry. 2606 SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry; 2607 2608 /// Maps a value to the proposed vectorizable size. 2609 SmallDenseMap<Value *, unsigned> InstrElementSize; 2610 2611 /// A list of scalars that we found that we need to keep as scalars. 2612 ValueSet MustGather; 2613 2614 /// This POD struct describes one external user in the vectorized tree. 2615 struct ExternalUser { 2616 ExternalUser(Value *S, llvm::User *U, int L) 2617 : Scalar(S), User(U), Lane(L) {} 2618 2619 // Which scalar in our function. 2620 Value *Scalar; 2621 2622 // Which user that uses the scalar. 2623 llvm::User *User; 2624 2625 // Which lane does the scalar belong to. 2626 int Lane; 2627 }; 2628 using UserList = SmallVector<ExternalUser, 16>; 2629 2630 /// Checks if two instructions may access the same memory. 2631 /// 2632 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it 2633 /// is invariant in the calling loop. 2634 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1, 2635 Instruction *Inst2) { 2636 // First check if the result is already in the cache. 2637 AliasCacheKey key = std::make_pair(Inst1, Inst2); 2638 Optional<bool> &result = AliasCache[key]; 2639 if (result.hasValue()) { 2640 return result.getValue(); 2641 } 2642 bool aliased = true; 2643 if (Loc1.Ptr && isSimple(Inst1)) 2644 aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1)); 2645 // Store the result in the cache. 2646 result = aliased; 2647 return aliased; 2648 } 2649 2650 using AliasCacheKey = std::pair<Instruction *, Instruction *>; 2651 2652 /// Cache for alias results. 2653 /// TODO: consider moving this to the AliasAnalysis itself. 2654 DenseMap<AliasCacheKey, Optional<bool>> AliasCache; 2655 2656 // Cache for pointerMayBeCaptured calls inside AA. This is preserved 2657 // globally through SLP because we don't perform any action which 2658 // invalidates capture results. 2659 BatchAAResults BatchAA; 2660 2661 /// Temporary store for deleted instructions. Instructions will be deleted 2662 /// eventually when the BoUpSLP is destructed. The deferral is required to 2663 /// ensure that there are no incorrect collisions in the AliasCache, which 2664 /// can happen if a new instruction is allocated at the same address as a 2665 /// previously deleted instruction. 2666 DenseSet<Instruction *> DeletedInstructions; 2667 2668 /// Set of the instruction, being analyzed already for reductions. 2669 SmallPtrSet<Instruction *, 16> AnalyzedReductionsRoots; 2670 2671 /// Set of hashes for the list of reduction values already being analyzed. 2672 DenseSet<size_t> AnalyzedReductionVals; 2673 2674 /// A list of values that need to extracted out of the tree. 2675 /// This list holds pairs of (Internal Scalar : External User). External User 2676 /// can be nullptr, it means that this Internal Scalar will be used later, 2677 /// after vectorization. 2678 UserList ExternalUses; 2679 2680 /// Values used only by @llvm.assume calls. 2681 SmallPtrSet<const Value *, 32> EphValues; 2682 2683 /// Holds all of the instructions that we gathered. 2684 SetVector<Instruction *> GatherShuffleSeq; 2685 2686 /// A list of blocks that we are going to CSE. 2687 SetVector<BasicBlock *> CSEBlocks; 2688 2689 /// Contains all scheduling relevant data for an instruction. 2690 /// A ScheduleData either represents a single instruction or a member of an 2691 /// instruction bundle (= a group of instructions which is combined into a 2692 /// vector instruction). 2693 struct ScheduleData { 2694 // The initial value for the dependency counters. It means that the 2695 // dependencies are not calculated yet. 2696 enum { InvalidDeps = -1 }; 2697 2698 ScheduleData() = default; 2699 2700 void init(int BlockSchedulingRegionID, Value *OpVal) { 2701 FirstInBundle = this; 2702 NextInBundle = nullptr; 2703 NextLoadStore = nullptr; 2704 IsScheduled = false; 2705 SchedulingRegionID = BlockSchedulingRegionID; 2706 clearDependencies(); 2707 OpValue = OpVal; 2708 TE = nullptr; 2709 } 2710 2711 /// Verify basic self consistency properties 2712 void verify() { 2713 if (hasValidDependencies()) { 2714 assert(UnscheduledDeps <= Dependencies && "invariant"); 2715 } else { 2716 assert(UnscheduledDeps == Dependencies && "invariant"); 2717 } 2718 2719 if (IsScheduled) { 2720 assert(isSchedulingEntity() && 2721 "unexpected scheduled state"); 2722 for (const ScheduleData *BundleMember = this; BundleMember; 2723 BundleMember = BundleMember->NextInBundle) { 2724 assert(BundleMember->hasValidDependencies() && 2725 BundleMember->UnscheduledDeps == 0 && 2726 "unexpected scheduled state"); 2727 assert((BundleMember == this || !BundleMember->IsScheduled) && 2728 "only bundle is marked scheduled"); 2729 } 2730 } 2731 2732 assert(Inst->getParent() == FirstInBundle->Inst->getParent() && 2733 "all bundle members must be in same basic block"); 2734 } 2735 2736 /// Returns true if the dependency information has been calculated. 2737 /// Note that depenendency validity can vary between instructions within 2738 /// a single bundle. 2739 bool hasValidDependencies() const { return Dependencies != InvalidDeps; } 2740 2741 /// Returns true for single instructions and for bundle representatives 2742 /// (= the head of a bundle). 2743 bool isSchedulingEntity() const { return FirstInBundle == this; } 2744 2745 /// Returns true if it represents an instruction bundle and not only a 2746 /// single instruction. 2747 bool isPartOfBundle() const { 2748 return NextInBundle != nullptr || FirstInBundle != this || TE; 2749 } 2750 2751 /// Returns true if it is ready for scheduling, i.e. it has no more 2752 /// unscheduled depending instructions/bundles. 2753 bool isReady() const { 2754 assert(isSchedulingEntity() && 2755 "can't consider non-scheduling entity for ready list"); 2756 return unscheduledDepsInBundle() == 0 && !IsScheduled; 2757 } 2758 2759 /// Modifies the number of unscheduled dependencies for this instruction, 2760 /// and returns the number of remaining dependencies for the containing 2761 /// bundle. 2762 int incrementUnscheduledDeps(int Incr) { 2763 assert(hasValidDependencies() && 2764 "increment of unscheduled deps would be meaningless"); 2765 UnscheduledDeps += Incr; 2766 return FirstInBundle->unscheduledDepsInBundle(); 2767 } 2768 2769 /// Sets the number of unscheduled dependencies to the number of 2770 /// dependencies. 2771 void resetUnscheduledDeps() { 2772 UnscheduledDeps = Dependencies; 2773 } 2774 2775 /// Clears all dependency information. 2776 void clearDependencies() { 2777 Dependencies = InvalidDeps; 2778 resetUnscheduledDeps(); 2779 MemoryDependencies.clear(); 2780 ControlDependencies.clear(); 2781 } 2782 2783 int unscheduledDepsInBundle() const { 2784 assert(isSchedulingEntity() && "only meaningful on the bundle"); 2785 int Sum = 0; 2786 for (const ScheduleData *BundleMember = this; BundleMember; 2787 BundleMember = BundleMember->NextInBundle) { 2788 if (BundleMember->UnscheduledDeps == InvalidDeps) 2789 return InvalidDeps; 2790 Sum += BundleMember->UnscheduledDeps; 2791 } 2792 return Sum; 2793 } 2794 2795 void dump(raw_ostream &os) const { 2796 if (!isSchedulingEntity()) { 2797 os << "/ " << *Inst; 2798 } else if (NextInBundle) { 2799 os << '[' << *Inst; 2800 ScheduleData *SD = NextInBundle; 2801 while (SD) { 2802 os << ';' << *SD->Inst; 2803 SD = SD->NextInBundle; 2804 } 2805 os << ']'; 2806 } else { 2807 os << *Inst; 2808 } 2809 } 2810 2811 Instruction *Inst = nullptr; 2812 2813 /// Opcode of the current instruction in the schedule data. 2814 Value *OpValue = nullptr; 2815 2816 /// The TreeEntry that this instruction corresponds to. 2817 TreeEntry *TE = nullptr; 2818 2819 /// Points to the head in an instruction bundle (and always to this for 2820 /// single instructions). 2821 ScheduleData *FirstInBundle = nullptr; 2822 2823 /// Single linked list of all instructions in a bundle. Null if it is a 2824 /// single instruction. 2825 ScheduleData *NextInBundle = nullptr; 2826 2827 /// Single linked list of all memory instructions (e.g. load, store, call) 2828 /// in the block - until the end of the scheduling region. 2829 ScheduleData *NextLoadStore = nullptr; 2830 2831 /// The dependent memory instructions. 2832 /// This list is derived on demand in calculateDependencies(). 2833 SmallVector<ScheduleData *, 4> MemoryDependencies; 2834 2835 /// List of instructions which this instruction could be control dependent 2836 /// on. Allowing such nodes to be scheduled below this one could introduce 2837 /// a runtime fault which didn't exist in the original program. 2838 /// ex: this is a load or udiv following a readonly call which inf loops 2839 SmallVector<ScheduleData *, 4> ControlDependencies; 2840 2841 /// This ScheduleData is in the current scheduling region if this matches 2842 /// the current SchedulingRegionID of BlockScheduling. 2843 int SchedulingRegionID = 0; 2844 2845 /// Used for getting a "good" final ordering of instructions. 2846 int SchedulingPriority = 0; 2847 2848 /// The number of dependencies. Constitutes of the number of users of the 2849 /// instruction plus the number of dependent memory instructions (if any). 2850 /// This value is calculated on demand. 2851 /// If InvalidDeps, the number of dependencies is not calculated yet. 2852 int Dependencies = InvalidDeps; 2853 2854 /// The number of dependencies minus the number of dependencies of scheduled 2855 /// instructions. As soon as this is zero, the instruction/bundle gets ready 2856 /// for scheduling. 2857 /// Note that this is negative as long as Dependencies is not calculated. 2858 int UnscheduledDeps = InvalidDeps; 2859 2860 /// True if this instruction is scheduled (or considered as scheduled in the 2861 /// dry-run). 2862 bool IsScheduled = false; 2863 }; 2864 2865 #ifndef NDEBUG 2866 friend inline raw_ostream &operator<<(raw_ostream &os, 2867 const BoUpSLP::ScheduleData &SD) { 2868 SD.dump(os); 2869 return os; 2870 } 2871 #endif 2872 2873 friend struct GraphTraits<BoUpSLP *>; 2874 friend struct DOTGraphTraits<BoUpSLP *>; 2875 2876 /// Contains all scheduling data for a basic block. 2877 /// It does not schedules instructions, which are not memory read/write 2878 /// instructions and their operands are either constants, or arguments, or 2879 /// phis, or instructions from others blocks, or their users are phis or from 2880 /// the other blocks. The resulting vector instructions can be placed at the 2881 /// beginning of the basic block without scheduling (if operands does not need 2882 /// to be scheduled) or at the end of the block (if users are outside of the 2883 /// block). It allows to save some compile time and memory used by the 2884 /// compiler. 2885 /// ScheduleData is assigned for each instruction in between the boundaries of 2886 /// the tree entry, even for those, which are not part of the graph. It is 2887 /// required to correctly follow the dependencies between the instructions and 2888 /// their correct scheduling. The ScheduleData is not allocated for the 2889 /// instructions, which do not require scheduling, like phis, nodes with 2890 /// extractelements/insertelements only or nodes with instructions, with 2891 /// uses/operands outside of the block. 2892 struct BlockScheduling { 2893 BlockScheduling(BasicBlock *BB) 2894 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {} 2895 2896 void clear() { 2897 ReadyInsts.clear(); 2898 ScheduleStart = nullptr; 2899 ScheduleEnd = nullptr; 2900 FirstLoadStoreInRegion = nullptr; 2901 LastLoadStoreInRegion = nullptr; 2902 RegionHasStackSave = false; 2903 2904 // Reduce the maximum schedule region size by the size of the 2905 // previous scheduling run. 2906 ScheduleRegionSizeLimit -= ScheduleRegionSize; 2907 if (ScheduleRegionSizeLimit < MinScheduleRegionSize) 2908 ScheduleRegionSizeLimit = MinScheduleRegionSize; 2909 ScheduleRegionSize = 0; 2910 2911 // Make a new scheduling region, i.e. all existing ScheduleData is not 2912 // in the new region yet. 2913 ++SchedulingRegionID; 2914 } 2915 2916 ScheduleData *getScheduleData(Instruction *I) { 2917 if (BB != I->getParent()) 2918 // Avoid lookup if can't possibly be in map. 2919 return nullptr; 2920 ScheduleData *SD = ScheduleDataMap.lookup(I); 2921 if (SD && isInSchedulingRegion(SD)) 2922 return SD; 2923 return nullptr; 2924 } 2925 2926 ScheduleData *getScheduleData(Value *V) { 2927 if (auto *I = dyn_cast<Instruction>(V)) 2928 return getScheduleData(I); 2929 return nullptr; 2930 } 2931 2932 ScheduleData *getScheduleData(Value *V, Value *Key) { 2933 if (V == Key) 2934 return getScheduleData(V); 2935 auto I = ExtraScheduleDataMap.find(V); 2936 if (I != ExtraScheduleDataMap.end()) { 2937 ScheduleData *SD = I->second.lookup(Key); 2938 if (SD && isInSchedulingRegion(SD)) 2939 return SD; 2940 } 2941 return nullptr; 2942 } 2943 2944 bool isInSchedulingRegion(ScheduleData *SD) const { 2945 return SD->SchedulingRegionID == SchedulingRegionID; 2946 } 2947 2948 /// Marks an instruction as scheduled and puts all dependent ready 2949 /// instructions into the ready-list. 2950 template <typename ReadyListType> 2951 void schedule(ScheduleData *SD, ReadyListType &ReadyList) { 2952 SD->IsScheduled = true; 2953 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n"); 2954 2955 for (ScheduleData *BundleMember = SD; BundleMember; 2956 BundleMember = BundleMember->NextInBundle) { 2957 if (BundleMember->Inst != BundleMember->OpValue) 2958 continue; 2959 2960 // Handle the def-use chain dependencies. 2961 2962 // Decrement the unscheduled counter and insert to ready list if ready. 2963 auto &&DecrUnsched = [this, &ReadyList](Instruction *I) { 2964 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) { 2965 if (OpDef && OpDef->hasValidDependencies() && 2966 OpDef->incrementUnscheduledDeps(-1) == 0) { 2967 // There are no more unscheduled dependencies after 2968 // decrementing, so we can put the dependent instruction 2969 // into the ready list. 2970 ScheduleData *DepBundle = OpDef->FirstInBundle; 2971 assert(!DepBundle->IsScheduled && 2972 "already scheduled bundle gets ready"); 2973 ReadyList.insert(DepBundle); 2974 LLVM_DEBUG(dbgs() 2975 << "SLP: gets ready (def): " << *DepBundle << "\n"); 2976 } 2977 }); 2978 }; 2979 2980 // If BundleMember is a vector bundle, its operands may have been 2981 // reordered during buildTree(). We therefore need to get its operands 2982 // through the TreeEntry. 2983 if (TreeEntry *TE = BundleMember->TE) { 2984 // Need to search for the lane since the tree entry can be reordered. 2985 int Lane = std::distance(TE->Scalars.begin(), 2986 find(TE->Scalars, BundleMember->Inst)); 2987 assert(Lane >= 0 && "Lane not set"); 2988 2989 // Since vectorization tree is being built recursively this assertion 2990 // ensures that the tree entry has all operands set before reaching 2991 // this code. Couple of exceptions known at the moment are extracts 2992 // where their second (immediate) operand is not added. Since 2993 // immediates do not affect scheduler behavior this is considered 2994 // okay. 2995 auto *In = BundleMember->Inst; 2996 assert(In && 2997 (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) || 2998 In->getNumOperands() == TE->getNumOperands()) && 2999 "Missed TreeEntry operands?"); 3000 (void)In; // fake use to avoid build failure when assertions disabled 3001 3002 for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands(); 3003 OpIdx != NumOperands; ++OpIdx) 3004 if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane])) 3005 DecrUnsched(I); 3006 } else { 3007 // If BundleMember is a stand-alone instruction, no operand reordering 3008 // has taken place, so we directly access its operands. 3009 for (Use &U : BundleMember->Inst->operands()) 3010 if (auto *I = dyn_cast<Instruction>(U.get())) 3011 DecrUnsched(I); 3012 } 3013 // Handle the memory dependencies. 3014 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) { 3015 if (MemoryDepSD->hasValidDependencies() && 3016 MemoryDepSD->incrementUnscheduledDeps(-1) == 0) { 3017 // There are no more unscheduled dependencies after decrementing, 3018 // so we can put the dependent instruction into the ready list. 3019 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle; 3020 assert(!DepBundle->IsScheduled && 3021 "already scheduled bundle gets ready"); 3022 ReadyList.insert(DepBundle); 3023 LLVM_DEBUG(dbgs() 3024 << "SLP: gets ready (mem): " << *DepBundle << "\n"); 3025 } 3026 } 3027 // Handle the control dependencies. 3028 for (ScheduleData *DepSD : BundleMember->ControlDependencies) { 3029 if (DepSD->incrementUnscheduledDeps(-1) == 0) { 3030 // There are no more unscheduled dependencies after decrementing, 3031 // so we can put the dependent instruction into the ready list. 3032 ScheduleData *DepBundle = DepSD->FirstInBundle; 3033 assert(!DepBundle->IsScheduled && 3034 "already scheduled bundle gets ready"); 3035 ReadyList.insert(DepBundle); 3036 LLVM_DEBUG(dbgs() 3037 << "SLP: gets ready (ctl): " << *DepBundle << "\n"); 3038 } 3039 } 3040 3041 } 3042 } 3043 3044 /// Verify basic self consistency properties of the data structure. 3045 void verify() { 3046 if (!ScheduleStart) 3047 return; 3048 3049 assert(ScheduleStart->getParent() == ScheduleEnd->getParent() && 3050 ScheduleStart->comesBefore(ScheduleEnd) && 3051 "Not a valid scheduling region?"); 3052 3053 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 3054 auto *SD = getScheduleData(I); 3055 if (!SD) 3056 continue; 3057 assert(isInSchedulingRegion(SD) && 3058 "primary schedule data not in window?"); 3059 assert(isInSchedulingRegion(SD->FirstInBundle) && 3060 "entire bundle in window!"); 3061 (void)SD; 3062 doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); }); 3063 } 3064 3065 for (auto *SD : ReadyInsts) { 3066 assert(SD->isSchedulingEntity() && SD->isReady() && 3067 "item in ready list not ready?"); 3068 (void)SD; 3069 } 3070 } 3071 3072 void doForAllOpcodes(Value *V, 3073 function_ref<void(ScheduleData *SD)> Action) { 3074 if (ScheduleData *SD = getScheduleData(V)) 3075 Action(SD); 3076 auto I = ExtraScheduleDataMap.find(V); 3077 if (I != ExtraScheduleDataMap.end()) 3078 for (auto &P : I->second) 3079 if (isInSchedulingRegion(P.second)) 3080 Action(P.second); 3081 } 3082 3083 /// Put all instructions into the ReadyList which are ready for scheduling. 3084 template <typename ReadyListType> 3085 void initialFillReadyList(ReadyListType &ReadyList) { 3086 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 3087 doForAllOpcodes(I, [&](ScheduleData *SD) { 3088 if (SD->isSchedulingEntity() && SD->hasValidDependencies() && 3089 SD->isReady()) { 3090 ReadyList.insert(SD); 3091 LLVM_DEBUG(dbgs() 3092 << "SLP: initially in ready list: " << *SD << "\n"); 3093 } 3094 }); 3095 } 3096 } 3097 3098 /// Build a bundle from the ScheduleData nodes corresponding to the 3099 /// scalar instruction for each lane. 3100 ScheduleData *buildBundle(ArrayRef<Value *> VL); 3101 3102 /// Checks if a bundle of instructions can be scheduled, i.e. has no 3103 /// cyclic dependencies. This is only a dry-run, no instructions are 3104 /// actually moved at this stage. 3105 /// \returns the scheduling bundle. The returned Optional value is non-None 3106 /// if \p VL is allowed to be scheduled. 3107 Optional<ScheduleData *> 3108 tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 3109 const InstructionsState &S); 3110 3111 /// Un-bundles a group of instructions. 3112 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue); 3113 3114 /// Allocates schedule data chunk. 3115 ScheduleData *allocateScheduleDataChunks(); 3116 3117 /// Extends the scheduling region so that V is inside the region. 3118 /// \returns true if the region size is within the limit. 3119 bool extendSchedulingRegion(Value *V, const InstructionsState &S); 3120 3121 /// Initialize the ScheduleData structures for new instructions in the 3122 /// scheduling region. 3123 void initScheduleData(Instruction *FromI, Instruction *ToI, 3124 ScheduleData *PrevLoadStore, 3125 ScheduleData *NextLoadStore); 3126 3127 /// Updates the dependency information of a bundle and of all instructions/ 3128 /// bundles which depend on the original bundle. 3129 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList, 3130 BoUpSLP *SLP); 3131 3132 /// Sets all instruction in the scheduling region to un-scheduled. 3133 void resetSchedule(); 3134 3135 BasicBlock *BB; 3136 3137 /// Simple memory allocation for ScheduleData. 3138 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks; 3139 3140 /// The size of a ScheduleData array in ScheduleDataChunks. 3141 int ChunkSize; 3142 3143 /// The allocator position in the current chunk, which is the last entry 3144 /// of ScheduleDataChunks. 3145 int ChunkPos; 3146 3147 /// Attaches ScheduleData to Instruction. 3148 /// Note that the mapping survives during all vectorization iterations, i.e. 3149 /// ScheduleData structures are recycled. 3150 DenseMap<Instruction *, ScheduleData *> ScheduleDataMap; 3151 3152 /// Attaches ScheduleData to Instruction with the leading key. 3153 DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>> 3154 ExtraScheduleDataMap; 3155 3156 /// The ready-list for scheduling (only used for the dry-run). 3157 SetVector<ScheduleData *> ReadyInsts; 3158 3159 /// The first instruction of the scheduling region. 3160 Instruction *ScheduleStart = nullptr; 3161 3162 /// The first instruction _after_ the scheduling region. 3163 Instruction *ScheduleEnd = nullptr; 3164 3165 /// The first memory accessing instruction in the scheduling region 3166 /// (can be null). 3167 ScheduleData *FirstLoadStoreInRegion = nullptr; 3168 3169 /// The last memory accessing instruction in the scheduling region 3170 /// (can be null). 3171 ScheduleData *LastLoadStoreInRegion = nullptr; 3172 3173 /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling 3174 /// region? Used to optimize the dependence calculation for the 3175 /// common case where there isn't. 3176 bool RegionHasStackSave = false; 3177 3178 /// The current size of the scheduling region. 3179 int ScheduleRegionSize = 0; 3180 3181 /// The maximum size allowed for the scheduling region. 3182 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget; 3183 3184 /// The ID of the scheduling region. For a new vectorization iteration this 3185 /// is incremented which "removes" all ScheduleData from the region. 3186 /// Make sure that the initial SchedulingRegionID is greater than the 3187 /// initial SchedulingRegionID in ScheduleData (which is 0). 3188 int SchedulingRegionID = 1; 3189 }; 3190 3191 /// Attaches the BlockScheduling structures to basic blocks. 3192 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules; 3193 3194 /// Performs the "real" scheduling. Done before vectorization is actually 3195 /// performed in a basic block. 3196 void scheduleBlock(BlockScheduling *BS); 3197 3198 /// List of users to ignore during scheduling and that don't need extracting. 3199 const SmallDenseSet<Value *> *UserIgnoreList = nullptr; 3200 3201 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of 3202 /// sorted SmallVectors of unsigned. 3203 struct OrdersTypeDenseMapInfo { 3204 static OrdersType getEmptyKey() { 3205 OrdersType V; 3206 V.push_back(~1U); 3207 return V; 3208 } 3209 3210 static OrdersType getTombstoneKey() { 3211 OrdersType V; 3212 V.push_back(~2U); 3213 return V; 3214 } 3215 3216 static unsigned getHashValue(const OrdersType &V) { 3217 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 3218 } 3219 3220 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) { 3221 return LHS == RHS; 3222 } 3223 }; 3224 3225 // Analysis and block reference. 3226 Function *F; 3227 ScalarEvolution *SE; 3228 TargetTransformInfo *TTI; 3229 TargetLibraryInfo *TLI; 3230 LoopInfo *LI; 3231 DominatorTree *DT; 3232 AssumptionCache *AC; 3233 DemandedBits *DB; 3234 const DataLayout *DL; 3235 OptimizationRemarkEmitter *ORE; 3236 3237 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt. 3238 unsigned MinVecRegSize; // Set by cl::opt (default: 128). 3239 3240 /// Instruction builder to construct the vectorized tree. 3241 IRBuilder<> Builder; 3242 3243 /// A map of scalar integer values to the smallest bit width with which they 3244 /// can legally be represented. The values map to (width, signed) pairs, 3245 /// where "width" indicates the minimum bit width and "signed" is True if the 3246 /// value must be signed-extended, rather than zero-extended, back to its 3247 /// original width. 3248 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs; 3249 }; 3250 3251 } // end namespace slpvectorizer 3252 3253 template <> struct GraphTraits<BoUpSLP *> { 3254 using TreeEntry = BoUpSLP::TreeEntry; 3255 3256 /// NodeRef has to be a pointer per the GraphWriter. 3257 using NodeRef = TreeEntry *; 3258 3259 using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy; 3260 3261 /// Add the VectorizableTree to the index iterator to be able to return 3262 /// TreeEntry pointers. 3263 struct ChildIteratorType 3264 : public iterator_adaptor_base< 3265 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> { 3266 ContainerTy &VectorizableTree; 3267 3268 ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W, 3269 ContainerTy &VT) 3270 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {} 3271 3272 NodeRef operator*() { return I->UserTE; } 3273 }; 3274 3275 static NodeRef getEntryNode(BoUpSLP &R) { 3276 return R.VectorizableTree[0].get(); 3277 } 3278 3279 static ChildIteratorType child_begin(NodeRef N) { 3280 return {N->UserTreeIndices.begin(), N->Container}; 3281 } 3282 3283 static ChildIteratorType child_end(NodeRef N) { 3284 return {N->UserTreeIndices.end(), N->Container}; 3285 } 3286 3287 /// For the node iterator we just need to turn the TreeEntry iterator into a 3288 /// TreeEntry* iterator so that it dereferences to NodeRef. 3289 class nodes_iterator { 3290 using ItTy = ContainerTy::iterator; 3291 ItTy It; 3292 3293 public: 3294 nodes_iterator(const ItTy &It2) : It(It2) {} 3295 NodeRef operator*() { return It->get(); } 3296 nodes_iterator operator++() { 3297 ++It; 3298 return *this; 3299 } 3300 bool operator!=(const nodes_iterator &N2) const { return N2.It != It; } 3301 }; 3302 3303 static nodes_iterator nodes_begin(BoUpSLP *R) { 3304 return nodes_iterator(R->VectorizableTree.begin()); 3305 } 3306 3307 static nodes_iterator nodes_end(BoUpSLP *R) { 3308 return nodes_iterator(R->VectorizableTree.end()); 3309 } 3310 3311 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); } 3312 }; 3313 3314 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits { 3315 using TreeEntry = BoUpSLP::TreeEntry; 3316 3317 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 3318 3319 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) { 3320 std::string Str; 3321 raw_string_ostream OS(Str); 3322 if (isSplat(Entry->Scalars)) 3323 OS << "<splat> "; 3324 for (auto V : Entry->Scalars) { 3325 OS << *V; 3326 if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) { 3327 return EU.Scalar == V; 3328 })) 3329 OS << " <extract>"; 3330 OS << "\n"; 3331 } 3332 return Str; 3333 } 3334 3335 static std::string getNodeAttributes(const TreeEntry *Entry, 3336 const BoUpSLP *) { 3337 if (Entry->State == TreeEntry::NeedToGather) 3338 return "color=red"; 3339 return ""; 3340 } 3341 }; 3342 3343 } // end namespace llvm 3344 3345 BoUpSLP::~BoUpSLP() { 3346 SmallVector<WeakTrackingVH> DeadInsts; 3347 for (auto *I : DeletedInstructions) { 3348 for (Use &U : I->operands()) { 3349 auto *Op = dyn_cast<Instruction>(U.get()); 3350 if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() && 3351 wouldInstructionBeTriviallyDead(Op, TLI)) 3352 DeadInsts.emplace_back(Op); 3353 } 3354 I->dropAllReferences(); 3355 } 3356 for (auto *I : DeletedInstructions) { 3357 assert(I->use_empty() && 3358 "trying to erase instruction with users."); 3359 I->eraseFromParent(); 3360 } 3361 3362 // Cleanup any dead scalar code feeding the vectorized instructions 3363 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI); 3364 3365 #ifdef EXPENSIVE_CHECKS 3366 // If we could guarantee that this call is not extremely slow, we could 3367 // remove the ifdef limitation (see PR47712). 3368 assert(!verifyFunction(*F, &dbgs())); 3369 #endif 3370 } 3371 3372 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses 3373 /// contains original mask for the scalars reused in the node. Procedure 3374 /// transform this mask in accordance with the given \p Mask. 3375 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) { 3376 assert(!Mask.empty() && Reuses.size() == Mask.size() && 3377 "Expected non-empty mask."); 3378 SmallVector<int> Prev(Reuses.begin(), Reuses.end()); 3379 Prev.swap(Reuses); 3380 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 3381 if (Mask[I] != UndefMaskElem) 3382 Reuses[Mask[I]] = Prev[I]; 3383 } 3384 3385 /// Reorders the given \p Order according to the given \p Mask. \p Order - is 3386 /// the original order of the scalars. Procedure transforms the provided order 3387 /// in accordance with the given \p Mask. If the resulting \p Order is just an 3388 /// identity order, \p Order is cleared. 3389 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) { 3390 assert(!Mask.empty() && "Expected non-empty mask."); 3391 SmallVector<int> MaskOrder; 3392 if (Order.empty()) { 3393 MaskOrder.resize(Mask.size()); 3394 std::iota(MaskOrder.begin(), MaskOrder.end(), 0); 3395 } else { 3396 inversePermutation(Order, MaskOrder); 3397 } 3398 reorderReuses(MaskOrder, Mask); 3399 if (ShuffleVectorInst::isIdentityMask(MaskOrder)) { 3400 Order.clear(); 3401 return; 3402 } 3403 Order.assign(Mask.size(), Mask.size()); 3404 for (unsigned I = 0, E = Mask.size(); I < E; ++I) 3405 if (MaskOrder[I] != UndefMaskElem) 3406 Order[MaskOrder[I]] = I; 3407 fixupOrderingIndices(Order); 3408 } 3409 3410 Optional<BoUpSLP::OrdersType> 3411 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) { 3412 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only."); 3413 unsigned NumScalars = TE.Scalars.size(); 3414 OrdersType CurrentOrder(NumScalars, NumScalars); 3415 SmallVector<int> Positions; 3416 SmallBitVector UsedPositions(NumScalars); 3417 const TreeEntry *STE = nullptr; 3418 // Try to find all gathered scalars that are gets vectorized in other 3419 // vectorize node. Here we can have only one single tree vector node to 3420 // correctly identify order of the gathered scalars. 3421 for (unsigned I = 0; I < NumScalars; ++I) { 3422 Value *V = TE.Scalars[I]; 3423 if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V)) 3424 continue; 3425 if (const auto *LocalSTE = getTreeEntry(V)) { 3426 if (!STE) 3427 STE = LocalSTE; 3428 else if (STE != LocalSTE) 3429 // Take the order only from the single vector node. 3430 return None; 3431 unsigned Lane = 3432 std::distance(STE->Scalars.begin(), find(STE->Scalars, V)); 3433 if (Lane >= NumScalars) 3434 return None; 3435 if (CurrentOrder[Lane] != NumScalars) { 3436 if (Lane != I) 3437 continue; 3438 UsedPositions.reset(CurrentOrder[Lane]); 3439 } 3440 // The partial identity (where only some elements of the gather node are 3441 // in the identity order) is good. 3442 CurrentOrder[Lane] = I; 3443 UsedPositions.set(I); 3444 } 3445 } 3446 // Need to keep the order if we have a vector entry and at least 2 scalars or 3447 // the vectorized entry has just 2 scalars. 3448 if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) { 3449 auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) { 3450 for (unsigned I = 0; I < NumScalars; ++I) 3451 if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars) 3452 return false; 3453 return true; 3454 }; 3455 if (IsIdentityOrder(CurrentOrder)) { 3456 CurrentOrder.clear(); 3457 return CurrentOrder; 3458 } 3459 auto *It = CurrentOrder.begin(); 3460 for (unsigned I = 0; I < NumScalars;) { 3461 if (UsedPositions.test(I)) { 3462 ++I; 3463 continue; 3464 } 3465 if (*It == NumScalars) { 3466 *It = I; 3467 ++I; 3468 } 3469 ++It; 3470 } 3471 return CurrentOrder; 3472 } 3473 return None; 3474 } 3475 3476 namespace { 3477 /// Tracks the state we can represent the loads in the given sequence. 3478 enum class LoadsState { Gather, Vectorize, ScatterVectorize }; 3479 } // anonymous namespace 3480 3481 /// Checks if the given array of loads can be represented as a vectorized, 3482 /// scatter or just simple gather. 3483 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0, 3484 const TargetTransformInfo &TTI, 3485 const DataLayout &DL, ScalarEvolution &SE, 3486 LoopInfo &LI, 3487 SmallVectorImpl<unsigned> &Order, 3488 SmallVectorImpl<Value *> &PointerOps) { 3489 // Check that a vectorized load would load the same memory as a scalar 3490 // load. For example, we don't want to vectorize loads that are smaller 3491 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 3492 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 3493 // from such a struct, we read/write packed bits disagreeing with the 3494 // unvectorized version. 3495 Type *ScalarTy = VL0->getType(); 3496 3497 if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy)) 3498 return LoadsState::Gather; 3499 3500 // Make sure all loads in the bundle are simple - we can't vectorize 3501 // atomic or volatile loads. 3502 PointerOps.clear(); 3503 PointerOps.resize(VL.size()); 3504 auto *POIter = PointerOps.begin(); 3505 for (Value *V : VL) { 3506 auto *L = cast<LoadInst>(V); 3507 if (!L->isSimple()) 3508 return LoadsState::Gather; 3509 *POIter = L->getPointerOperand(); 3510 ++POIter; 3511 } 3512 3513 Order.clear(); 3514 // Check the order of pointer operands or that all pointers are the same. 3515 bool IsSorted = sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order); 3516 if (IsSorted || all_of(PointerOps, [&PointerOps](Value *P) { 3517 if (getUnderlyingObject(P) != getUnderlyingObject(PointerOps.front())) 3518 return false; 3519 auto *GEP = dyn_cast<GetElementPtrInst>(P); 3520 if (!GEP) 3521 return false; 3522 auto *GEP0 = cast<GetElementPtrInst>(PointerOps.front()); 3523 return GEP->getNumOperands() == 2 && 3524 ((isConstant(GEP->getOperand(1)) && 3525 isConstant(GEP0->getOperand(1))) || 3526 getSameOpcode({GEP->getOperand(1), GEP0->getOperand(1)}) 3527 .getOpcode()); 3528 })) { 3529 if (IsSorted) { 3530 Value *Ptr0; 3531 Value *PtrN; 3532 if (Order.empty()) { 3533 Ptr0 = PointerOps.front(); 3534 PtrN = PointerOps.back(); 3535 } else { 3536 Ptr0 = PointerOps[Order.front()]; 3537 PtrN = PointerOps[Order.back()]; 3538 } 3539 Optional<int> Diff = 3540 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE); 3541 // Check that the sorted loads are consecutive. 3542 if (static_cast<unsigned>(*Diff) == VL.size() - 1) 3543 return LoadsState::Vectorize; 3544 } 3545 // TODO: need to improve analysis of the pointers, if not all of them are 3546 // GEPs or have > 2 operands, we end up with a gather node, which just 3547 // increases the cost. 3548 Loop *L = LI.getLoopFor(cast<LoadInst>(VL0)->getParent()); 3549 bool ProfitableGatherPointers = 3550 static_cast<unsigned>(count_if(PointerOps, [L](Value *V) { 3551 return L && L->isLoopInvariant(V); 3552 })) <= VL.size() / 2 && VL.size() > 2; 3553 if (ProfitableGatherPointers || all_of(PointerOps, [IsSorted](Value *P) { 3554 auto *GEP = dyn_cast<GetElementPtrInst>(P); 3555 return (IsSorted && !GEP && doesNotNeedToBeScheduled(P)) || 3556 (GEP && GEP->getNumOperands() == 2); 3557 })) { 3558 Align CommonAlignment = cast<LoadInst>(VL0)->getAlign(); 3559 for (Value *V : VL) 3560 CommonAlignment = 3561 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 3562 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 3563 if (TTI.isLegalMaskedGather(VecTy, CommonAlignment) && 3564 !TTI.forceScalarizeMaskedGather(VecTy, CommonAlignment)) 3565 return LoadsState::ScatterVectorize; 3566 } 3567 } 3568 3569 return LoadsState::Gather; 3570 } 3571 3572 bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy, 3573 const DataLayout &DL, ScalarEvolution &SE, 3574 SmallVectorImpl<unsigned> &SortedIndices) { 3575 assert(llvm::all_of( 3576 VL, [](const Value *V) { return V->getType()->isPointerTy(); }) && 3577 "Expected list of pointer operands."); 3578 // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each 3579 // Ptr into, sort and return the sorted indices with values next to one 3580 // another. 3581 MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases; 3582 Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U)); 3583 3584 unsigned Cnt = 1; 3585 for (Value *Ptr : VL.drop_front()) { 3586 bool Found = any_of(Bases, [&](auto &Base) { 3587 Optional<int> Diff = 3588 getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE, 3589 /*StrictCheck=*/true); 3590 if (!Diff) 3591 return false; 3592 3593 Base.second.emplace_back(Ptr, *Diff, Cnt++); 3594 return true; 3595 }); 3596 3597 if (!Found) { 3598 // If we haven't found enough to usefully cluster, return early. 3599 if (Bases.size() > VL.size() / 2 - 1) 3600 return false; 3601 3602 // Not found already - add a new Base 3603 Bases[Ptr].emplace_back(Ptr, 0, Cnt++); 3604 } 3605 } 3606 3607 // For each of the bases sort the pointers by Offset and check if any of the 3608 // base become consecutively allocated. 3609 bool AnyConsecutive = false; 3610 for (auto &Base : Bases) { 3611 auto &Vec = Base.second; 3612 if (Vec.size() > 1) { 3613 llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X, 3614 const std::tuple<Value *, int, unsigned> &Y) { 3615 return std::get<1>(X) < std::get<1>(Y); 3616 }); 3617 int InitialOffset = std::get<1>(Vec[0]); 3618 AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) { 3619 return std::get<1>(P.value()) == int(P.index()) + InitialOffset; 3620 }); 3621 } 3622 } 3623 3624 // Fill SortedIndices array only if it looks worth-while to sort the ptrs. 3625 SortedIndices.clear(); 3626 if (!AnyConsecutive) 3627 return false; 3628 3629 for (auto &Base : Bases) { 3630 for (auto &T : Base.second) 3631 SortedIndices.push_back(std::get<2>(T)); 3632 } 3633 3634 assert(SortedIndices.size() == VL.size() && 3635 "Expected SortedIndices to be the size of VL"); 3636 return true; 3637 } 3638 3639 Optional<BoUpSLP::OrdersType> 3640 BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) { 3641 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only."); 3642 Type *ScalarTy = TE.Scalars[0]->getType(); 3643 3644 SmallVector<Value *> Ptrs; 3645 Ptrs.reserve(TE.Scalars.size()); 3646 for (Value *V : TE.Scalars) { 3647 auto *L = dyn_cast<LoadInst>(V); 3648 if (!L || !L->isSimple()) 3649 return None; 3650 Ptrs.push_back(L->getPointerOperand()); 3651 } 3652 3653 BoUpSLP::OrdersType Order; 3654 if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order)) 3655 return Order; 3656 return None; 3657 } 3658 3659 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE, 3660 bool TopToBottom) { 3661 // No need to reorder if need to shuffle reuses, still need to shuffle the 3662 // node. 3663 if (!TE.ReuseShuffleIndices.empty()) 3664 return None; 3665 if (TE.State == TreeEntry::Vectorize && 3666 (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) || 3667 (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) && 3668 !TE.isAltShuffle()) 3669 return TE.ReorderIndices; 3670 if (TE.State == TreeEntry::NeedToGather) { 3671 // TODO: add analysis of other gather nodes with extractelement 3672 // instructions and other values/instructions, not only undefs. 3673 if (((TE.getOpcode() == Instruction::ExtractElement && 3674 !TE.isAltShuffle()) || 3675 (all_of(TE.Scalars, 3676 [](Value *V) { 3677 return isa<UndefValue, ExtractElementInst>(V); 3678 }) && 3679 any_of(TE.Scalars, 3680 [](Value *V) { return isa<ExtractElementInst>(V); }))) && 3681 all_of(TE.Scalars, 3682 [](Value *V) { 3683 auto *EE = dyn_cast<ExtractElementInst>(V); 3684 return !EE || isa<FixedVectorType>(EE->getVectorOperandType()); 3685 }) && 3686 allSameType(TE.Scalars)) { 3687 // Check that gather of extractelements can be represented as 3688 // just a shuffle of a single vector. 3689 OrdersType CurrentOrder; 3690 bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder); 3691 if (Reuse || !CurrentOrder.empty()) { 3692 if (!CurrentOrder.empty()) 3693 fixupOrderingIndices(CurrentOrder); 3694 return CurrentOrder; 3695 } 3696 } 3697 if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE)) 3698 return CurrentOrder; 3699 if (TE.Scalars.size() >= 4) 3700 if (Optional<OrdersType> Order = findPartiallyOrderedLoads(TE)) 3701 return Order; 3702 } 3703 return None; 3704 } 3705 3706 void BoUpSLP::reorderTopToBottom() { 3707 // Maps VF to the graph nodes. 3708 DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries; 3709 // ExtractElement gather nodes which can be vectorized and need to handle 3710 // their ordering. 3711 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3712 3713 // AltShuffles can also have a preferred ordering that leads to fewer 3714 // instructions, e.g., the addsub instruction in x86. 3715 DenseMap<const TreeEntry *, OrdersType> AltShufflesToOrders; 3716 3717 // Maps a TreeEntry to the reorder indices of external users. 3718 DenseMap<const TreeEntry *, SmallVector<OrdersType, 1>> 3719 ExternalUserReorderMap; 3720 // Find all reorderable nodes with the given VF. 3721 // Currently the are vectorized stores,loads,extracts + some gathering of 3722 // extracts. 3723 for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders, 3724 &ExternalUserReorderMap, &AltShufflesToOrders]( 3725 const std::unique_ptr<TreeEntry> &TE) { 3726 // Look for external users that will probably be vectorized. 3727 SmallVector<OrdersType, 1> ExternalUserReorderIndices = 3728 findExternalStoreUsersReorderIndices(TE.get()); 3729 if (!ExternalUserReorderIndices.empty()) { 3730 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 3731 ExternalUserReorderMap.try_emplace(TE.get(), 3732 std::move(ExternalUserReorderIndices)); 3733 } 3734 3735 // Patterns like [fadd,fsub] can be combined into a single instruction in 3736 // x86. Reordering them into [fsub,fadd] blocks this pattern. So we need 3737 // to take into account their order when looking for the most used order. 3738 if (TE->isAltShuffle()) { 3739 VectorType *VecTy = 3740 FixedVectorType::get(TE->Scalars[0]->getType(), TE->Scalars.size()); 3741 unsigned Opcode0 = TE->getOpcode(); 3742 unsigned Opcode1 = TE->getAltOpcode(); 3743 // The opcode mask selects between the two opcodes. 3744 SmallBitVector OpcodeMask(TE->Scalars.size(), 0); 3745 for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) 3746 if (cast<Instruction>(TE->Scalars[Lane])->getOpcode() == Opcode1) 3747 OpcodeMask.set(Lane); 3748 // If this pattern is supported by the target then we consider the order. 3749 if (TTI->isLegalAltInstr(VecTy, Opcode0, Opcode1, OpcodeMask)) { 3750 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 3751 AltShufflesToOrders.try_emplace(TE.get(), OrdersType()); 3752 } 3753 // TODO: Check the reverse order too. 3754 } 3755 3756 if (Optional<OrdersType> CurrentOrder = 3757 getReorderingData(*TE, /*TopToBottom=*/true)) { 3758 // Do not include ordering for nodes used in the alt opcode vectorization, 3759 // better to reorder them during bottom-to-top stage. If follow the order 3760 // here, it causes reordering of the whole graph though actually it is 3761 // profitable just to reorder the subgraph that starts from the alternate 3762 // opcode vectorization node. Such nodes already end-up with the shuffle 3763 // instruction and it is just enough to change this shuffle rather than 3764 // rotate the scalars for the whole graph. 3765 unsigned Cnt = 0; 3766 const TreeEntry *UserTE = TE.get(); 3767 while (UserTE && Cnt < RecursionMaxDepth) { 3768 if (UserTE->UserTreeIndices.size() != 1) 3769 break; 3770 if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) { 3771 return EI.UserTE->State == TreeEntry::Vectorize && 3772 EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0; 3773 })) 3774 return; 3775 UserTE = UserTE->UserTreeIndices.back().UserTE; 3776 ++Cnt; 3777 } 3778 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 3779 if (TE->State != TreeEntry::Vectorize) 3780 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3781 } 3782 }); 3783 3784 // Reorder the graph nodes according to their vectorization factor. 3785 for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1; 3786 VF /= 2) { 3787 auto It = VFToOrderedEntries.find(VF); 3788 if (It == VFToOrderedEntries.end()) 3789 continue; 3790 // Try to find the most profitable order. We just are looking for the most 3791 // used order and reorder scalar elements in the nodes according to this 3792 // mostly used order. 3793 ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef(); 3794 // All operands are reordered and used only in this node - propagate the 3795 // most used order to the user node. 3796 MapVector<OrdersType, unsigned, 3797 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3798 OrdersUses; 3799 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3800 for (const TreeEntry *OpTE : OrderedEntries) { 3801 // No need to reorder this nodes, still need to extend and to use shuffle, 3802 // just need to merge reordering shuffle and the reuse shuffle. 3803 if (!OpTE->ReuseShuffleIndices.empty()) 3804 continue; 3805 // Count number of orders uses. 3806 const auto &Order = [OpTE, &GathersToOrders, 3807 &AltShufflesToOrders]() -> const OrdersType & { 3808 if (OpTE->State == TreeEntry::NeedToGather) { 3809 auto It = GathersToOrders.find(OpTE); 3810 if (It != GathersToOrders.end()) 3811 return It->second; 3812 } 3813 if (OpTE->isAltShuffle()) { 3814 auto It = AltShufflesToOrders.find(OpTE); 3815 if (It != AltShufflesToOrders.end()) 3816 return It->second; 3817 } 3818 return OpTE->ReorderIndices; 3819 }(); 3820 // First consider the order of the external scalar users. 3821 auto It = ExternalUserReorderMap.find(OpTE); 3822 if (It != ExternalUserReorderMap.end()) { 3823 const auto &ExternalUserReorderIndices = It->second; 3824 for (const OrdersType &ExtOrder : ExternalUserReorderIndices) 3825 ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second; 3826 // No other useful reorder data in this entry. 3827 if (Order.empty()) 3828 continue; 3829 } 3830 // Stores actually store the mask, not the order, need to invert. 3831 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3832 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3833 SmallVector<int> Mask; 3834 inversePermutation(Order, Mask); 3835 unsigned E = Order.size(); 3836 OrdersType CurrentOrder(E, E); 3837 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3838 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3839 }); 3840 fixupOrderingIndices(CurrentOrder); 3841 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 3842 } else { 3843 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 3844 } 3845 } 3846 // Set order of the user node. 3847 if (OrdersUses.empty()) 3848 continue; 3849 // Choose the most used order. 3850 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3851 unsigned Cnt = OrdersUses.front().second; 3852 for (const auto &Pair : drop_begin(OrdersUses)) { 3853 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3854 BestOrder = Pair.first; 3855 Cnt = Pair.second; 3856 } 3857 } 3858 // Set order of the user node. 3859 if (BestOrder.empty()) 3860 continue; 3861 SmallVector<int> Mask; 3862 inversePermutation(BestOrder, Mask); 3863 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3864 unsigned E = BestOrder.size(); 3865 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3866 return I < E ? static_cast<int>(I) : UndefMaskElem; 3867 }); 3868 // Do an actual reordering, if profitable. 3869 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 3870 // Just do the reordering for the nodes with the given VF. 3871 if (TE->Scalars.size() != VF) { 3872 if (TE->ReuseShuffleIndices.size() == VF) { 3873 // Need to reorder the reuses masks of the operands with smaller VF to 3874 // be able to find the match between the graph nodes and scalar 3875 // operands of the given node during vectorization/cost estimation. 3876 assert(all_of(TE->UserTreeIndices, 3877 [VF, &TE](const EdgeInfo &EI) { 3878 return EI.UserTE->Scalars.size() == VF || 3879 EI.UserTE->Scalars.size() == 3880 TE->Scalars.size(); 3881 }) && 3882 "All users must be of VF size."); 3883 // Update ordering of the operands with the smaller VF than the given 3884 // one. 3885 reorderReuses(TE->ReuseShuffleIndices, Mask); 3886 } 3887 continue; 3888 } 3889 if (TE->State == TreeEntry::Vectorize && 3890 isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst, 3891 InsertElementInst>(TE->getMainOp()) && 3892 !TE->isAltShuffle()) { 3893 // Build correct orders for extract{element,value}, loads and 3894 // stores. 3895 reorderOrder(TE->ReorderIndices, Mask); 3896 if (isa<InsertElementInst, StoreInst>(TE->getMainOp())) 3897 TE->reorderOperands(Mask); 3898 } else { 3899 // Reorder the node and its operands. 3900 TE->reorderOperands(Mask); 3901 assert(TE->ReorderIndices.empty() && 3902 "Expected empty reorder sequence."); 3903 reorderScalars(TE->Scalars, Mask); 3904 } 3905 if (!TE->ReuseShuffleIndices.empty()) { 3906 // Apply reversed order to keep the original ordering of the reused 3907 // elements to avoid extra reorder indices shuffling. 3908 OrdersType CurrentOrder; 3909 reorderOrder(CurrentOrder, MaskOrder); 3910 SmallVector<int> NewReuses; 3911 inversePermutation(CurrentOrder, NewReuses); 3912 addMask(NewReuses, TE->ReuseShuffleIndices); 3913 TE->ReuseShuffleIndices.swap(NewReuses); 3914 } 3915 } 3916 } 3917 } 3918 3919 bool BoUpSLP::canReorderOperands( 3920 TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges, 3921 ArrayRef<TreeEntry *> ReorderableGathers, 3922 SmallVectorImpl<TreeEntry *> &GatherOps) { 3923 for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) { 3924 if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) { 3925 return OpData.first == I && 3926 OpData.second->State == TreeEntry::Vectorize; 3927 })) 3928 continue; 3929 if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) { 3930 // Do not reorder if operand node is used by many user nodes. 3931 if (any_of(TE->UserTreeIndices, 3932 [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; })) 3933 return false; 3934 // Add the node to the list of the ordered nodes with the identity 3935 // order. 3936 Edges.emplace_back(I, TE); 3937 // Add ScatterVectorize nodes to the list of operands, where just 3938 // reordering of the scalars is required. Similar to the gathers, so 3939 // simply add to the list of gathered ops. 3940 if (TE->State != TreeEntry::Vectorize) 3941 GatherOps.push_back(TE); 3942 continue; 3943 } 3944 ArrayRef<Value *> VL = UserTE->getOperand(I); 3945 TreeEntry *Gather = nullptr; 3946 if (count_if(ReorderableGathers, 3947 [VL, &Gather](TreeEntry *TE) { 3948 assert(TE->State != TreeEntry::Vectorize && 3949 "Only non-vectorized nodes are expected."); 3950 if (TE->isSame(VL)) { 3951 Gather = TE; 3952 return true; 3953 } 3954 return false; 3955 }) > 1 && 3956 !all_of(VL, isConstant)) 3957 return false; 3958 if (Gather) 3959 GatherOps.push_back(Gather); 3960 } 3961 return true; 3962 } 3963 3964 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) { 3965 SetVector<TreeEntry *> OrderedEntries; 3966 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3967 // Find all reorderable leaf nodes with the given VF. 3968 // Currently the are vectorized loads,extracts without alternate operands + 3969 // some gathering of extracts. 3970 SmallVector<TreeEntry *> NonVectorized; 3971 for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders, 3972 &NonVectorized]( 3973 const std::unique_ptr<TreeEntry> &TE) { 3974 if (TE->State != TreeEntry::Vectorize) 3975 NonVectorized.push_back(TE.get()); 3976 if (Optional<OrdersType> CurrentOrder = 3977 getReorderingData(*TE, /*TopToBottom=*/false)) { 3978 OrderedEntries.insert(TE.get()); 3979 if (TE->State != TreeEntry::Vectorize) 3980 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3981 } 3982 }); 3983 3984 // 1. Propagate order to the graph nodes, which use only reordered nodes. 3985 // I.e., if the node has operands, that are reordered, try to make at least 3986 // one operand order in the natural order and reorder others + reorder the 3987 // user node itself. 3988 SmallPtrSet<const TreeEntry *, 4> Visited; 3989 while (!OrderedEntries.empty()) { 3990 // 1. Filter out only reordered nodes. 3991 // 2. If the entry has multiple uses - skip it and jump to the next node. 3992 DenseMap<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users; 3993 SmallVector<TreeEntry *> Filtered; 3994 for (TreeEntry *TE : OrderedEntries) { 3995 if (!(TE->State == TreeEntry::Vectorize || 3996 (TE->State == TreeEntry::NeedToGather && 3997 GathersToOrders.count(TE))) || 3998 TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() || 3999 !all_of(drop_begin(TE->UserTreeIndices), 4000 [TE](const EdgeInfo &EI) { 4001 return EI.UserTE == TE->UserTreeIndices.front().UserTE; 4002 }) || 4003 !Visited.insert(TE).second) { 4004 Filtered.push_back(TE); 4005 continue; 4006 } 4007 // Build a map between user nodes and their operands order to speedup 4008 // search. The graph currently does not provide this dependency directly. 4009 for (EdgeInfo &EI : TE->UserTreeIndices) { 4010 TreeEntry *UserTE = EI.UserTE; 4011 auto It = Users.find(UserTE); 4012 if (It == Users.end()) 4013 It = Users.insert({UserTE, {}}).first; 4014 It->second.emplace_back(EI.EdgeIdx, TE); 4015 } 4016 } 4017 // Erase filtered entries. 4018 for_each(Filtered, 4019 [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); }); 4020 SmallVector< 4021 std::pair<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>>> 4022 UsersVec(Users.begin(), Users.end()); 4023 sort(UsersVec, [](const auto &Data1, const auto &Data2) { 4024 return Data1.first->Idx > Data2.first->Idx; 4025 }); 4026 for (auto &Data : UsersVec) { 4027 // Check that operands are used only in the User node. 4028 SmallVector<TreeEntry *> GatherOps; 4029 if (!canReorderOperands(Data.first, Data.second, NonVectorized, 4030 GatherOps)) { 4031 for_each(Data.second, 4032 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 4033 OrderedEntries.remove(Op.second); 4034 }); 4035 continue; 4036 } 4037 // All operands are reordered and used only in this node - propagate the 4038 // most used order to the user node. 4039 MapVector<OrdersType, unsigned, 4040 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 4041 OrdersUses; 4042 // Do the analysis for each tree entry only once, otherwise the order of 4043 // the same node my be considered several times, though might be not 4044 // profitable. 4045 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 4046 SmallPtrSet<const TreeEntry *, 4> VisitedUsers; 4047 for (const auto &Op : Data.second) { 4048 TreeEntry *OpTE = Op.second; 4049 if (!VisitedOps.insert(OpTE).second) 4050 continue; 4051 if (!OpTE->ReuseShuffleIndices.empty() || 4052 (IgnoreReorder && OpTE == VectorizableTree.front().get())) 4053 continue; 4054 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 4055 if (OpTE->State == TreeEntry::NeedToGather) 4056 return GathersToOrders.find(OpTE)->second; 4057 return OpTE->ReorderIndices; 4058 }(); 4059 unsigned NumOps = count_if( 4060 Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) { 4061 return P.second == OpTE; 4062 }); 4063 // Stores actually store the mask, not the order, need to invert. 4064 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 4065 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 4066 SmallVector<int> Mask; 4067 inversePermutation(Order, Mask); 4068 unsigned E = Order.size(); 4069 OrdersType CurrentOrder(E, E); 4070 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 4071 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 4072 }); 4073 fixupOrderingIndices(CurrentOrder); 4074 OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second += 4075 NumOps; 4076 } else { 4077 OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps; 4078 } 4079 auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0)); 4080 const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders]( 4081 const TreeEntry *TE) { 4082 if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() || 4083 (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) || 4084 (IgnoreReorder && TE->Idx == 0)) 4085 return true; 4086 if (TE->State == TreeEntry::NeedToGather) { 4087 auto It = GathersToOrders.find(TE); 4088 if (It != GathersToOrders.end()) 4089 return !It->second.empty(); 4090 return true; 4091 } 4092 return false; 4093 }; 4094 for (const EdgeInfo &EI : OpTE->UserTreeIndices) { 4095 TreeEntry *UserTE = EI.UserTE; 4096 if (!VisitedUsers.insert(UserTE).second) 4097 continue; 4098 // May reorder user node if it requires reordering, has reused 4099 // scalars, is an alternate op vectorize node or its op nodes require 4100 // reordering. 4101 if (AllowsReordering(UserTE)) 4102 continue; 4103 // Check if users allow reordering. 4104 // Currently look up just 1 level of operands to avoid increase of 4105 // the compile time. 4106 // Profitable to reorder if definitely more operands allow 4107 // reordering rather than those with natural order. 4108 ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE]; 4109 if (static_cast<unsigned>(count_if( 4110 Ops, [UserTE, &AllowsReordering]( 4111 const std::pair<unsigned, TreeEntry *> &Op) { 4112 return AllowsReordering(Op.second) && 4113 all_of(Op.second->UserTreeIndices, 4114 [UserTE](const EdgeInfo &EI) { 4115 return EI.UserTE == UserTE; 4116 }); 4117 })) <= Ops.size() / 2) 4118 ++Res.first->second; 4119 } 4120 } 4121 // If no orders - skip current nodes and jump to the next one, if any. 4122 if (OrdersUses.empty()) { 4123 for_each(Data.second, 4124 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 4125 OrderedEntries.remove(Op.second); 4126 }); 4127 continue; 4128 } 4129 // Choose the best order. 4130 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 4131 unsigned Cnt = OrdersUses.front().second; 4132 for (const auto &Pair : drop_begin(OrdersUses)) { 4133 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 4134 BestOrder = Pair.first; 4135 Cnt = Pair.second; 4136 } 4137 } 4138 // Set order of the user node (reordering of operands and user nodes). 4139 if (BestOrder.empty()) { 4140 for_each(Data.second, 4141 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 4142 OrderedEntries.remove(Op.second); 4143 }); 4144 continue; 4145 } 4146 // Erase operands from OrderedEntries list and adjust their orders. 4147 VisitedOps.clear(); 4148 SmallVector<int> Mask; 4149 inversePermutation(BestOrder, Mask); 4150 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 4151 unsigned E = BestOrder.size(); 4152 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 4153 return I < E ? static_cast<int>(I) : UndefMaskElem; 4154 }); 4155 for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) { 4156 TreeEntry *TE = Op.second; 4157 OrderedEntries.remove(TE); 4158 if (!VisitedOps.insert(TE).second) 4159 continue; 4160 if (TE->ReuseShuffleIndices.size() == BestOrder.size()) { 4161 // Just reorder reuses indices. 4162 reorderReuses(TE->ReuseShuffleIndices, Mask); 4163 continue; 4164 } 4165 // Gathers are processed separately. 4166 if (TE->State != TreeEntry::Vectorize) 4167 continue; 4168 assert((BestOrder.size() == TE->ReorderIndices.size() || 4169 TE->ReorderIndices.empty()) && 4170 "Non-matching sizes of user/operand entries."); 4171 reorderOrder(TE->ReorderIndices, Mask); 4172 } 4173 // For gathers just need to reorder its scalars. 4174 for (TreeEntry *Gather : GatherOps) { 4175 assert(Gather->ReorderIndices.empty() && 4176 "Unexpected reordering of gathers."); 4177 if (!Gather->ReuseShuffleIndices.empty()) { 4178 // Just reorder reuses indices. 4179 reorderReuses(Gather->ReuseShuffleIndices, Mask); 4180 continue; 4181 } 4182 reorderScalars(Gather->Scalars, Mask); 4183 OrderedEntries.remove(Gather); 4184 } 4185 // Reorder operands of the user node and set the ordering for the user 4186 // node itself. 4187 if (Data.first->State != TreeEntry::Vectorize || 4188 !isa<ExtractElementInst, ExtractValueInst, LoadInst>( 4189 Data.first->getMainOp()) || 4190 Data.first->isAltShuffle()) 4191 Data.first->reorderOperands(Mask); 4192 if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) || 4193 Data.first->isAltShuffle()) { 4194 reorderScalars(Data.first->Scalars, Mask); 4195 reorderOrder(Data.first->ReorderIndices, MaskOrder); 4196 if (Data.first->ReuseShuffleIndices.empty() && 4197 !Data.first->ReorderIndices.empty() && 4198 !Data.first->isAltShuffle()) { 4199 // Insert user node to the list to try to sink reordering deeper in 4200 // the graph. 4201 OrderedEntries.insert(Data.first); 4202 } 4203 } else { 4204 reorderOrder(Data.first->ReorderIndices, Mask); 4205 } 4206 } 4207 } 4208 // If the reordering is unnecessary, just remove the reorder. 4209 if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() && 4210 VectorizableTree.front()->ReuseShuffleIndices.empty()) 4211 VectorizableTree.front()->ReorderIndices.clear(); 4212 } 4213 4214 void BoUpSLP::buildExternalUses( 4215 const ExtraValueToDebugLocsMap &ExternallyUsedValues) { 4216 // Collect the values that we need to extract from the tree. 4217 for (auto &TEPtr : VectorizableTree) { 4218 TreeEntry *Entry = TEPtr.get(); 4219 4220 // No need to handle users of gathered values. 4221 if (Entry->State == TreeEntry::NeedToGather) 4222 continue; 4223 4224 // For each lane: 4225 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 4226 Value *Scalar = Entry->Scalars[Lane]; 4227 int FoundLane = Entry->findLaneForValue(Scalar); 4228 4229 // Check if the scalar is externally used as an extra arg. 4230 auto ExtI = ExternallyUsedValues.find(Scalar); 4231 if (ExtI != ExternallyUsedValues.end()) { 4232 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " 4233 << Lane << " from " << *Scalar << ".\n"); 4234 ExternalUses.emplace_back(Scalar, nullptr, FoundLane); 4235 } 4236 for (User *U : Scalar->users()) { 4237 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n"); 4238 4239 Instruction *UserInst = dyn_cast<Instruction>(U); 4240 if (!UserInst) 4241 continue; 4242 4243 if (isDeleted(UserInst)) 4244 continue; 4245 4246 // Skip in-tree scalars that become vectors 4247 if (TreeEntry *UseEntry = getTreeEntry(U)) { 4248 Value *UseScalar = UseEntry->Scalars[0]; 4249 // Some in-tree scalars will remain as scalar in vectorized 4250 // instructions. If that is the case, the one in Lane 0 will 4251 // be used. 4252 if (UseScalar != U || 4253 UseEntry->State == TreeEntry::ScatterVectorize || 4254 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) { 4255 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U 4256 << ".\n"); 4257 assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state"); 4258 continue; 4259 } 4260 } 4261 4262 // Ignore users in the user ignore list. 4263 if (UserIgnoreList && UserIgnoreList->contains(UserInst)) 4264 continue; 4265 4266 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " 4267 << Lane << " from " << *Scalar << ".\n"); 4268 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane)); 4269 } 4270 } 4271 } 4272 } 4273 4274 DenseMap<Value *, SmallVector<StoreInst *, 4>> 4275 BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const { 4276 DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap; 4277 for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) { 4278 Value *V = TE->Scalars[Lane]; 4279 // To save compilation time we don't visit if we have too many users. 4280 static constexpr unsigned UsersLimit = 4; 4281 if (V->hasNUsesOrMore(UsersLimit)) 4282 break; 4283 4284 // Collect stores per pointer object. 4285 for (User *U : V->users()) { 4286 auto *SI = dyn_cast<StoreInst>(U); 4287 if (SI == nullptr || !SI->isSimple() || 4288 !isValidElementType(SI->getValueOperand()->getType())) 4289 continue; 4290 // Skip entry if already 4291 if (getTreeEntry(U)) 4292 continue; 4293 4294 Value *Ptr = getUnderlyingObject(SI->getPointerOperand()); 4295 auto &StoresVec = PtrToStoresMap[Ptr]; 4296 // For now just keep one store per pointer object per lane. 4297 // TODO: Extend this to support multiple stores per pointer per lane 4298 if (StoresVec.size() > Lane) 4299 continue; 4300 // Skip if in different BBs. 4301 if (!StoresVec.empty() && 4302 SI->getParent() != StoresVec.back()->getParent()) 4303 continue; 4304 // Make sure that the stores are of the same type. 4305 if (!StoresVec.empty() && 4306 SI->getValueOperand()->getType() != 4307 StoresVec.back()->getValueOperand()->getType()) 4308 continue; 4309 StoresVec.push_back(SI); 4310 } 4311 } 4312 return PtrToStoresMap; 4313 } 4314 4315 bool BoUpSLP::CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec, 4316 OrdersType &ReorderIndices) const { 4317 // We check whether the stores in StoreVec can form a vector by sorting them 4318 // and checking whether they are consecutive. 4319 4320 // To avoid calling getPointersDiff() while sorting we create a vector of 4321 // pairs {store, offset from first} and sort this instead. 4322 SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size()); 4323 StoreInst *S0 = StoresVec[0]; 4324 StoreOffsetVec[0] = {S0, 0}; 4325 Type *S0Ty = S0->getValueOperand()->getType(); 4326 Value *S0Ptr = S0->getPointerOperand(); 4327 for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) { 4328 StoreInst *SI = StoresVec[Idx]; 4329 Optional<int> Diff = 4330 getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(), 4331 SI->getPointerOperand(), *DL, *SE, 4332 /*StrictCheck=*/true); 4333 // We failed to compare the pointers so just abandon this StoresVec. 4334 if (!Diff) 4335 return false; 4336 StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff}; 4337 } 4338 4339 // Sort the vector based on the pointers. We create a copy because we may 4340 // need the original later for calculating the reorder (shuffle) indices. 4341 stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1, 4342 const std::pair<StoreInst *, int> &Pair2) { 4343 int Offset1 = Pair1.second; 4344 int Offset2 = Pair2.second; 4345 return Offset1 < Offset2; 4346 }); 4347 4348 // Check if the stores are consecutive by checking if their difference is 1. 4349 for (unsigned Idx : seq<unsigned>(1, StoreOffsetVec.size())) 4350 if (StoreOffsetVec[Idx].second != StoreOffsetVec[Idx-1].second + 1) 4351 return false; 4352 4353 // Calculate the shuffle indices according to their offset against the sorted 4354 // StoreOffsetVec. 4355 ReorderIndices.reserve(StoresVec.size()); 4356 for (StoreInst *SI : StoresVec) { 4357 unsigned Idx = find_if(StoreOffsetVec, 4358 [SI](const std::pair<StoreInst *, int> &Pair) { 4359 return Pair.first == SI; 4360 }) - 4361 StoreOffsetVec.begin(); 4362 ReorderIndices.push_back(Idx); 4363 } 4364 // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in 4365 // reorderTopToBottom() and reorderBottomToTop(), so we are following the 4366 // same convention here. 4367 auto IsIdentityOrder = [](const OrdersType &Order) { 4368 for (unsigned Idx : seq<unsigned>(0, Order.size())) 4369 if (Idx != Order[Idx]) 4370 return false; 4371 return true; 4372 }; 4373 if (IsIdentityOrder(ReorderIndices)) 4374 ReorderIndices.clear(); 4375 4376 return true; 4377 } 4378 4379 #ifndef NDEBUG 4380 LLVM_DUMP_METHOD static void dumpOrder(const BoUpSLP::OrdersType &Order) { 4381 for (unsigned Idx : Order) 4382 dbgs() << Idx << ", "; 4383 dbgs() << "\n"; 4384 } 4385 #endif 4386 4387 SmallVector<BoUpSLP::OrdersType, 1> 4388 BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const { 4389 unsigned NumLanes = TE->Scalars.size(); 4390 4391 DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap = 4392 collectUserStores(TE); 4393 4394 // Holds the reorder indices for each candidate store vector that is a user of 4395 // the current TreeEntry. 4396 SmallVector<OrdersType, 1> ExternalReorderIndices; 4397 4398 // Now inspect the stores collected per pointer and look for vectorization 4399 // candidates. For each candidate calculate the reorder index vector and push 4400 // it into `ExternalReorderIndices` 4401 for (const auto &Pair : PtrToStoresMap) { 4402 auto &StoresVec = Pair.second; 4403 // If we have fewer than NumLanes stores, then we can't form a vector. 4404 if (StoresVec.size() != NumLanes) 4405 continue; 4406 4407 // If the stores are not consecutive then abandon this StoresVec. 4408 OrdersType ReorderIndices; 4409 if (!CanFormVector(StoresVec, ReorderIndices)) 4410 continue; 4411 4412 // We now know that the scalars in StoresVec can form a vector instruction, 4413 // so set the reorder indices. 4414 ExternalReorderIndices.push_back(ReorderIndices); 4415 } 4416 return ExternalReorderIndices; 4417 } 4418 4419 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, 4420 const SmallDenseSet<Value *> &UserIgnoreLst) { 4421 deleteTree(); 4422 UserIgnoreList = &UserIgnoreLst; 4423 if (!allSameType(Roots)) 4424 return; 4425 buildTree_rec(Roots, 0, EdgeInfo()); 4426 } 4427 4428 void BoUpSLP::buildTree(ArrayRef<Value *> Roots) { 4429 deleteTree(); 4430 if (!allSameType(Roots)) 4431 return; 4432 buildTree_rec(Roots, 0, EdgeInfo()); 4433 } 4434 4435 /// \return true if the specified list of values has only one instruction that 4436 /// requires scheduling, false otherwise. 4437 #ifndef NDEBUG 4438 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) { 4439 Value *NeedsScheduling = nullptr; 4440 for (Value *V : VL) { 4441 if (doesNotNeedToBeScheduled(V)) 4442 continue; 4443 if (!NeedsScheduling) { 4444 NeedsScheduling = V; 4445 continue; 4446 } 4447 return false; 4448 } 4449 return NeedsScheduling; 4450 } 4451 #endif 4452 4453 /// Generates key/subkey pair for the given value to provide effective sorting 4454 /// of the values and better detection of the vectorizable values sequences. The 4455 /// keys/subkeys can be used for better sorting of the values themselves (keys) 4456 /// and in values subgroups (subkeys). 4457 static std::pair<size_t, size_t> generateKeySubkey( 4458 Value *V, const TargetLibraryInfo *TLI, 4459 function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator, 4460 bool AllowAlternate) { 4461 hash_code Key = hash_value(V->getValueID() + 2); 4462 hash_code SubKey = hash_value(0); 4463 // Sort the loads by the distance between the pointers. 4464 if (auto *LI = dyn_cast<LoadInst>(V)) { 4465 Key = hash_combine(hash_value(Instruction::Load), Key); 4466 if (LI->isSimple()) 4467 SubKey = hash_value(LoadsSubkeyGenerator(Key, LI)); 4468 else 4469 SubKey = hash_value(LI); 4470 } else if (isVectorLikeInstWithConstOps(V)) { 4471 // Sort extracts by the vector operands. 4472 if (isa<ExtractElementInst, UndefValue>(V)) 4473 Key = hash_value(Value::UndefValueVal + 1); 4474 if (auto *EI = dyn_cast<ExtractElementInst>(V)) { 4475 if (!isUndefVector(EI->getVectorOperand()) && 4476 !isa<UndefValue>(EI->getIndexOperand())) 4477 SubKey = hash_value(EI->getVectorOperand()); 4478 } 4479 } else if (auto *I = dyn_cast<Instruction>(V)) { 4480 // Sort other instructions just by the opcodes except for CMPInst. 4481 // For CMP also sort by the predicate kind. 4482 if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) && 4483 isValidForAlternation(I->getOpcode())) { 4484 if (AllowAlternate) 4485 Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0); 4486 else 4487 Key = hash_combine(hash_value(I->getOpcode()), Key); 4488 SubKey = hash_combine( 4489 hash_value(I->getOpcode()), hash_value(I->getType()), 4490 hash_value(isa<BinaryOperator>(I) 4491 ? I->getType() 4492 : cast<CastInst>(I)->getOperand(0)->getType())); 4493 // For casts, look through the only operand to improve compile time. 4494 if (isa<CastInst>(I)) { 4495 std::pair<size_t, size_t> OpVals = 4496 generateKeySubkey(I->getOperand(0), TLI, LoadsSubkeyGenerator, 4497 /*=AllowAlternate*/ true); 4498 Key = hash_combine(OpVals.first, Key); 4499 SubKey = hash_combine(OpVals.first, SubKey); 4500 } 4501 } else if (auto *CI = dyn_cast<CmpInst>(I)) { 4502 CmpInst::Predicate Pred = CI->getPredicate(); 4503 if (CI->isCommutative()) 4504 Pred = std::min(Pred, CmpInst::getInversePredicate(Pred)); 4505 CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred); 4506 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred), 4507 hash_value(SwapPred), 4508 hash_value(CI->getOperand(0)->getType())); 4509 } else if (auto *Call = dyn_cast<CallInst>(I)) { 4510 Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI); 4511 if (isTriviallyVectorizable(ID)) { 4512 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID)); 4513 } else if (!VFDatabase(*Call).getMappings(*Call).empty()) { 4514 SubKey = hash_combine(hash_value(I->getOpcode()), 4515 hash_value(Call->getCalledFunction())); 4516 } else { 4517 Key = hash_combine(hash_value(Call), Key); 4518 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call)); 4519 } 4520 for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos()) 4521 SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End), 4522 hash_value(Op.Tag), SubKey); 4523 } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) { 4524 if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1))) 4525 SubKey = hash_value(Gep->getPointerOperand()); 4526 else 4527 SubKey = hash_value(Gep); 4528 } else if (BinaryOperator::isIntDivRem(I->getOpcode()) && 4529 !isa<ConstantInt>(I->getOperand(1))) { 4530 // Do not try to vectorize instructions with potentially high cost. 4531 SubKey = hash_value(I); 4532 } else { 4533 SubKey = hash_value(I->getOpcode()); 4534 } 4535 Key = hash_combine(hash_value(I->getParent()), Key); 4536 } 4537 return std::make_pair(Key, SubKey); 4538 } 4539 4540 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth, 4541 const EdgeInfo &UserTreeIdx) { 4542 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!"); 4543 4544 SmallVector<int> ReuseShuffleIndicies; 4545 SmallVector<Value *> UniqueValues; 4546 auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues, 4547 &UserTreeIdx, 4548 this](const InstructionsState &S) { 4549 // Check that every instruction appears once in this bundle. 4550 DenseMap<Value *, unsigned> UniquePositions; 4551 for (Value *V : VL) { 4552 if (isConstant(V)) { 4553 ReuseShuffleIndicies.emplace_back( 4554 isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size()); 4555 UniqueValues.emplace_back(V); 4556 continue; 4557 } 4558 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 4559 ReuseShuffleIndicies.emplace_back(Res.first->second); 4560 if (Res.second) 4561 UniqueValues.emplace_back(V); 4562 } 4563 size_t NumUniqueScalarValues = UniqueValues.size(); 4564 if (NumUniqueScalarValues == VL.size()) { 4565 ReuseShuffleIndicies.clear(); 4566 } else { 4567 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n"); 4568 if (NumUniqueScalarValues <= 1 || 4569 (UniquePositions.size() == 1 && all_of(UniqueValues, 4570 [](Value *V) { 4571 return isa<UndefValue>(V) || 4572 !isConstant(V); 4573 })) || 4574 !llvm::isPowerOf2_32(NumUniqueScalarValues)) { 4575 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); 4576 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4577 return false; 4578 } 4579 VL = UniqueValues; 4580 } 4581 return true; 4582 }; 4583 4584 InstructionsState S = getSameOpcode(VL); 4585 if (Depth == RecursionMaxDepth) { 4586 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); 4587 if (TryToFindDuplicates(S)) 4588 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4589 ReuseShuffleIndicies); 4590 return; 4591 } 4592 4593 // Don't handle scalable vectors 4594 if (S.getOpcode() == Instruction::ExtractElement && 4595 isa<ScalableVectorType>( 4596 cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) { 4597 LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n"); 4598 if (TryToFindDuplicates(S)) 4599 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4600 ReuseShuffleIndicies); 4601 return; 4602 } 4603 4604 // Don't handle vectors. 4605 if (S.OpValue->getType()->isVectorTy() && 4606 !isa<InsertElementInst>(S.OpValue)) { 4607 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); 4608 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4609 return; 4610 } 4611 4612 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue)) 4613 if (SI->getValueOperand()->getType()->isVectorTy()) { 4614 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); 4615 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4616 return; 4617 } 4618 4619 // If all of the operands are identical or constant we have a simple solution. 4620 // If we deal with insert/extract instructions, they all must have constant 4621 // indices, otherwise we should gather them, not try to vectorize. 4622 // If alternate op node with 2 elements with gathered operands - do not 4623 // vectorize. 4624 auto &&NotProfitableForVectorization = [&S, this, 4625 Depth](ArrayRef<Value *> VL) { 4626 if (!S.getOpcode() || !S.isAltShuffle() || VL.size() > 2) 4627 return false; 4628 if (VectorizableTree.size() < MinTreeSize) 4629 return false; 4630 if (Depth >= RecursionMaxDepth - 1) 4631 return true; 4632 // Check if all operands are extracts, part of vector node or can build a 4633 // regular vectorize node. 4634 SmallVector<unsigned, 2> InstsCount(VL.size(), 0); 4635 for (Value *V : VL) { 4636 auto *I = cast<Instruction>(V); 4637 InstsCount.push_back(count_if(I->operand_values(), [](Value *Op) { 4638 return isa<Instruction>(Op) || isVectorLikeInstWithConstOps(Op); 4639 })); 4640 } 4641 bool IsCommutative = isCommutative(S.MainOp) || isCommutative(S.AltOp); 4642 if ((IsCommutative && 4643 std::accumulate(InstsCount.begin(), InstsCount.end(), 0) < 2) || 4644 (!IsCommutative && 4645 all_of(InstsCount, [](unsigned ICnt) { return ICnt < 2; }))) 4646 return true; 4647 assert(VL.size() == 2 && "Expected only 2 alternate op instructions."); 4648 SmallVector<SmallVector<std::pair<Value *, Value *>>> Candidates; 4649 auto *I1 = cast<Instruction>(VL.front()); 4650 auto *I2 = cast<Instruction>(VL.back()); 4651 for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op) 4652 Candidates.emplace_back().emplace_back(I1->getOperand(Op), 4653 I2->getOperand(Op)); 4654 if (static_cast<unsigned>(count_if( 4655 Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) { 4656 return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat); 4657 })) >= S.MainOp->getNumOperands() / 2) 4658 return false; 4659 if (S.MainOp->getNumOperands() > 2) 4660 return true; 4661 if (IsCommutative) { 4662 // Check permuted operands. 4663 Candidates.clear(); 4664 for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op) 4665 Candidates.emplace_back().emplace_back(I1->getOperand(Op), 4666 I2->getOperand((Op + 1) % E)); 4667 if (any_of( 4668 Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) { 4669 return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat); 4670 })) 4671 return false; 4672 } 4673 return true; 4674 }; 4675 SmallVector<unsigned> SortedIndices; 4676 BasicBlock *BB = nullptr; 4677 bool AreAllSameInsts = 4678 (S.getOpcode() && allSameBlock(VL)) || 4679 (S.OpValue->getType()->isPointerTy() && UserTreeIdx.UserTE && 4680 UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize && 4681 VL.size() > 2 && 4682 all_of(VL, 4683 [&BB](Value *V) { 4684 auto *I = dyn_cast<GetElementPtrInst>(V); 4685 if (!I) 4686 return doesNotNeedToBeScheduled(V); 4687 if (!BB) 4688 BB = I->getParent(); 4689 return BB == I->getParent() && I->getNumOperands() == 2; 4690 }) && 4691 BB && 4692 sortPtrAccesses(VL, UserTreeIdx.UserTE->getMainOp()->getType(), *DL, *SE, 4693 SortedIndices)); 4694 if (allConstant(VL) || isSplat(VL) || !AreAllSameInsts || 4695 (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>( 4696 S.OpValue) && 4697 !all_of(VL, isVectorLikeInstWithConstOps)) || 4698 NotProfitableForVectorization(VL)) { 4699 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O, small shuffle. \n"); 4700 if (TryToFindDuplicates(S)) 4701 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4702 ReuseShuffleIndicies); 4703 return; 4704 } 4705 4706 // We now know that this is a vector of instructions of the same type from 4707 // the same block. 4708 4709 // Don't vectorize ephemeral values. 4710 if (!EphValues.empty()) { 4711 for (Value *V : VL) { 4712 if (EphValues.count(V)) { 4713 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 4714 << ") is ephemeral.\n"); 4715 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4716 return; 4717 } 4718 } 4719 } 4720 4721 // Check if this is a duplicate of another entry. 4722 if (TreeEntry *E = getTreeEntry(S.OpValue)) { 4723 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n"); 4724 if (!E->isSame(VL)) { 4725 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); 4726 if (TryToFindDuplicates(S)) 4727 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4728 ReuseShuffleIndicies); 4729 return; 4730 } 4731 // Record the reuse of the tree node. FIXME, currently this is only used to 4732 // properly draw the graph rather than for the actual vectorization. 4733 E->UserTreeIndices.push_back(UserTreeIdx); 4734 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue 4735 << ".\n"); 4736 return; 4737 } 4738 4739 // Check that none of the instructions in the bundle are already in the tree. 4740 for (Value *V : VL) { 4741 auto *I = dyn_cast<Instruction>(V); 4742 if (!I) 4743 continue; 4744 if (getTreeEntry(I)) { 4745 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 4746 << ") is already in tree.\n"); 4747 if (TryToFindDuplicates(S)) 4748 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4749 ReuseShuffleIndicies); 4750 return; 4751 } 4752 } 4753 4754 // The reduction nodes (stored in UserIgnoreList) also should stay scalar. 4755 if (UserIgnoreList && !UserIgnoreList->empty()) { 4756 for (Value *V : VL) { 4757 if (UserIgnoreList && UserIgnoreList->contains(V)) { 4758 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n"); 4759 if (TryToFindDuplicates(S)) 4760 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4761 ReuseShuffleIndicies); 4762 return; 4763 } 4764 } 4765 } 4766 4767 // Special processing for sorted pointers for ScatterVectorize node with 4768 // constant indeces only. 4769 if (AreAllSameInsts && !(S.getOpcode() && allSameBlock(VL)) && 4770 UserTreeIdx.UserTE && 4771 UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize) { 4772 assert(S.OpValue->getType()->isPointerTy() && 4773 count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >= 4774 2 && 4775 "Expected pointers only."); 4776 // Reset S to make it GetElementPtr kind of node. 4777 const auto *It = find_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }); 4778 assert(It != VL.end() && "Expected at least one GEP."); 4779 S = getSameOpcode(*It); 4780 } 4781 4782 // Check that all of the users of the scalars that we want to vectorize are 4783 // schedulable. 4784 auto *VL0 = cast<Instruction>(S.OpValue); 4785 BB = VL0->getParent(); 4786 4787 if (!DT->isReachableFromEntry(BB)) { 4788 // Don't go into unreachable blocks. They may contain instructions with 4789 // dependency cycles which confuse the final scheduling. 4790 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n"); 4791 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4792 return; 4793 } 4794 4795 // Check that every instruction appears once in this bundle. 4796 if (!TryToFindDuplicates(S)) 4797 return; 4798 4799 auto &BSRef = BlocksSchedules[BB]; 4800 if (!BSRef) 4801 BSRef = std::make_unique<BlockScheduling>(BB); 4802 4803 BlockScheduling &BS = *BSRef; 4804 4805 Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S); 4806 #ifdef EXPENSIVE_CHECKS 4807 // Make sure we didn't break any internal invariants 4808 BS.verify(); 4809 #endif 4810 if (!Bundle) { 4811 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n"); 4812 assert((!BS.getScheduleData(VL0) || 4813 !BS.getScheduleData(VL0)->isPartOfBundle()) && 4814 "tryScheduleBundle should cancelScheduling on failure"); 4815 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4816 ReuseShuffleIndicies); 4817 return; 4818 } 4819 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); 4820 4821 unsigned ShuffleOrOp = S.isAltShuffle() ? 4822 (unsigned) Instruction::ShuffleVector : S.getOpcode(); 4823 switch (ShuffleOrOp) { 4824 case Instruction::PHI: { 4825 auto *PH = cast<PHINode>(VL0); 4826 4827 // Check for terminator values (e.g. invoke). 4828 for (Value *V : VL) 4829 for (Value *Incoming : cast<PHINode>(V)->incoming_values()) { 4830 Instruction *Term = dyn_cast<Instruction>(Incoming); 4831 if (Term && Term->isTerminator()) { 4832 LLVM_DEBUG(dbgs() 4833 << "SLP: Need to swizzle PHINodes (terminator use).\n"); 4834 BS.cancelScheduling(VL, VL0); 4835 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4836 ReuseShuffleIndicies); 4837 return; 4838 } 4839 } 4840 4841 TreeEntry *TE = 4842 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies); 4843 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); 4844 4845 // Keeps the reordered operands to avoid code duplication. 4846 SmallVector<ValueList, 2> OperandsVec; 4847 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 4848 if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) { 4849 ValueList Operands(VL.size(), PoisonValue::get(PH->getType())); 4850 TE->setOperand(I, Operands); 4851 OperandsVec.push_back(Operands); 4852 continue; 4853 } 4854 ValueList Operands; 4855 // Prepare the operand vector. 4856 for (Value *V : VL) 4857 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock( 4858 PH->getIncomingBlock(I))); 4859 TE->setOperand(I, Operands); 4860 OperandsVec.push_back(Operands); 4861 } 4862 for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx) 4863 buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx}); 4864 return; 4865 } 4866 case Instruction::ExtractValue: 4867 case Instruction::ExtractElement: { 4868 OrdersType CurrentOrder; 4869 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder); 4870 if (Reuse) { 4871 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n"); 4872 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4873 ReuseShuffleIndicies); 4874 // This is a special case, as it does not gather, but at the same time 4875 // we are not extending buildTree_rec() towards the operands. 4876 ValueList Op0; 4877 Op0.assign(VL.size(), VL0->getOperand(0)); 4878 VectorizableTree.back()->setOperand(0, Op0); 4879 return; 4880 } 4881 if (!CurrentOrder.empty()) { 4882 LLVM_DEBUG({ 4883 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " 4884 "with order"; 4885 for (unsigned Idx : CurrentOrder) 4886 dbgs() << " " << Idx; 4887 dbgs() << "\n"; 4888 }); 4889 fixupOrderingIndices(CurrentOrder); 4890 // Insert new order with initial value 0, if it does not exist, 4891 // otherwise return the iterator to the existing one. 4892 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4893 ReuseShuffleIndicies, CurrentOrder); 4894 // This is a special case, as it does not gather, but at the same time 4895 // we are not extending buildTree_rec() towards the operands. 4896 ValueList Op0; 4897 Op0.assign(VL.size(), VL0->getOperand(0)); 4898 VectorizableTree.back()->setOperand(0, Op0); 4899 return; 4900 } 4901 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n"); 4902 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4903 ReuseShuffleIndicies); 4904 BS.cancelScheduling(VL, VL0); 4905 return; 4906 } 4907 case Instruction::InsertElement: { 4908 assert(ReuseShuffleIndicies.empty() && "All inserts should be unique"); 4909 4910 // Check that we have a buildvector and not a shuffle of 2 or more 4911 // different vectors. 4912 ValueSet SourceVectors; 4913 for (Value *V : VL) { 4914 SourceVectors.insert(cast<Instruction>(V)->getOperand(0)); 4915 assert(getInsertIndex(V) != None && "Non-constant or undef index?"); 4916 } 4917 4918 if (count_if(VL, [&SourceVectors](Value *V) { 4919 return !SourceVectors.contains(V); 4920 }) >= 2) { 4921 // Found 2nd source vector - cancel. 4922 LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with " 4923 "different source vectors.\n"); 4924 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4925 BS.cancelScheduling(VL, VL0); 4926 return; 4927 } 4928 4929 auto OrdCompare = [](const std::pair<int, int> &P1, 4930 const std::pair<int, int> &P2) { 4931 return P1.first > P2.first; 4932 }; 4933 PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>, 4934 decltype(OrdCompare)> 4935 Indices(OrdCompare); 4936 for (int I = 0, E = VL.size(); I < E; ++I) { 4937 unsigned Idx = *getInsertIndex(VL[I]); 4938 Indices.emplace(Idx, I); 4939 } 4940 OrdersType CurrentOrder(VL.size(), VL.size()); 4941 bool IsIdentity = true; 4942 for (int I = 0, E = VL.size(); I < E; ++I) { 4943 CurrentOrder[Indices.top().second] = I; 4944 IsIdentity &= Indices.top().second == I; 4945 Indices.pop(); 4946 } 4947 if (IsIdentity) 4948 CurrentOrder.clear(); 4949 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4950 None, CurrentOrder); 4951 LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n"); 4952 4953 constexpr int NumOps = 2; 4954 ValueList VectorOperands[NumOps]; 4955 for (int I = 0; I < NumOps; ++I) { 4956 for (Value *V : VL) 4957 VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I)); 4958 4959 TE->setOperand(I, VectorOperands[I]); 4960 } 4961 buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1}); 4962 return; 4963 } 4964 case Instruction::Load: { 4965 // Check that a vectorized load would load the same memory as a scalar 4966 // load. For example, we don't want to vectorize loads that are smaller 4967 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 4968 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 4969 // from such a struct, we read/write packed bits disagreeing with the 4970 // unvectorized version. 4971 SmallVector<Value *> PointerOps; 4972 OrdersType CurrentOrder; 4973 TreeEntry *TE = nullptr; 4974 switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, *LI, CurrentOrder, 4975 PointerOps)) { 4976 case LoadsState::Vectorize: 4977 if (CurrentOrder.empty()) { 4978 // Original loads are consecutive and does not require reordering. 4979 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4980 ReuseShuffleIndicies); 4981 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n"); 4982 } else { 4983 fixupOrderingIndices(CurrentOrder); 4984 // Need to reorder. 4985 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4986 ReuseShuffleIndicies, CurrentOrder); 4987 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n"); 4988 } 4989 TE->setOperandsInOrder(); 4990 break; 4991 case LoadsState::ScatterVectorize: 4992 // Vectorizing non-consecutive loads with `llvm.masked.gather`. 4993 TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S, 4994 UserTreeIdx, ReuseShuffleIndicies); 4995 TE->setOperandsInOrder(); 4996 buildTree_rec(PointerOps, Depth + 1, {TE, 0}); 4997 LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n"); 4998 break; 4999 case LoadsState::Gather: 5000 BS.cancelScheduling(VL, VL0); 5001 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5002 ReuseShuffleIndicies); 5003 #ifndef NDEBUG 5004 Type *ScalarTy = VL0->getType(); 5005 if (DL->getTypeSizeInBits(ScalarTy) != 5006 DL->getTypeAllocSizeInBits(ScalarTy)) 5007 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n"); 5008 else if (any_of(VL, [](Value *V) { 5009 return !cast<LoadInst>(V)->isSimple(); 5010 })) 5011 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n"); 5012 else 5013 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n"); 5014 #endif // NDEBUG 5015 break; 5016 } 5017 return; 5018 } 5019 case Instruction::ZExt: 5020 case Instruction::SExt: 5021 case Instruction::FPToUI: 5022 case Instruction::FPToSI: 5023 case Instruction::FPExt: 5024 case Instruction::PtrToInt: 5025 case Instruction::IntToPtr: 5026 case Instruction::SIToFP: 5027 case Instruction::UIToFP: 5028 case Instruction::Trunc: 5029 case Instruction::FPTrunc: 5030 case Instruction::BitCast: { 5031 Type *SrcTy = VL0->getOperand(0)->getType(); 5032 for (Value *V : VL) { 5033 Type *Ty = cast<Instruction>(V)->getOperand(0)->getType(); 5034 if (Ty != SrcTy || !isValidElementType(Ty)) { 5035 BS.cancelScheduling(VL, VL0); 5036 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5037 ReuseShuffleIndicies); 5038 LLVM_DEBUG(dbgs() 5039 << "SLP: Gathering casts with different src types.\n"); 5040 return; 5041 } 5042 } 5043 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5044 ReuseShuffleIndicies); 5045 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n"); 5046 5047 TE->setOperandsInOrder(); 5048 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 5049 ValueList Operands; 5050 // Prepare the operand vector. 5051 for (Value *V : VL) 5052 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 5053 5054 buildTree_rec(Operands, Depth + 1, {TE, i}); 5055 } 5056 return; 5057 } 5058 case Instruction::ICmp: 5059 case Instruction::FCmp: { 5060 // Check that all of the compares have the same predicate. 5061 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 5062 CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0); 5063 Type *ComparedTy = VL0->getOperand(0)->getType(); 5064 for (Value *V : VL) { 5065 CmpInst *Cmp = cast<CmpInst>(V); 5066 if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) || 5067 Cmp->getOperand(0)->getType() != ComparedTy) { 5068 BS.cancelScheduling(VL, VL0); 5069 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5070 ReuseShuffleIndicies); 5071 LLVM_DEBUG(dbgs() 5072 << "SLP: Gathering cmp with different predicate.\n"); 5073 return; 5074 } 5075 } 5076 5077 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5078 ReuseShuffleIndicies); 5079 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n"); 5080 5081 ValueList Left, Right; 5082 if (cast<CmpInst>(VL0)->isCommutative()) { 5083 // Commutative predicate - collect + sort operands of the instructions 5084 // so that each side is more likely to have the same opcode. 5085 assert(P0 == SwapP0 && "Commutative Predicate mismatch"); 5086 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 5087 } else { 5088 // Collect operands - commute if it uses the swapped predicate. 5089 for (Value *V : VL) { 5090 auto *Cmp = cast<CmpInst>(V); 5091 Value *LHS = Cmp->getOperand(0); 5092 Value *RHS = Cmp->getOperand(1); 5093 if (Cmp->getPredicate() != P0) 5094 std::swap(LHS, RHS); 5095 Left.push_back(LHS); 5096 Right.push_back(RHS); 5097 } 5098 } 5099 TE->setOperand(0, Left); 5100 TE->setOperand(1, Right); 5101 buildTree_rec(Left, Depth + 1, {TE, 0}); 5102 buildTree_rec(Right, Depth + 1, {TE, 1}); 5103 return; 5104 } 5105 case Instruction::Select: 5106 case Instruction::FNeg: 5107 case Instruction::Add: 5108 case Instruction::FAdd: 5109 case Instruction::Sub: 5110 case Instruction::FSub: 5111 case Instruction::Mul: 5112 case Instruction::FMul: 5113 case Instruction::UDiv: 5114 case Instruction::SDiv: 5115 case Instruction::FDiv: 5116 case Instruction::URem: 5117 case Instruction::SRem: 5118 case Instruction::FRem: 5119 case Instruction::Shl: 5120 case Instruction::LShr: 5121 case Instruction::AShr: 5122 case Instruction::And: 5123 case Instruction::Or: 5124 case Instruction::Xor: { 5125 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5126 ReuseShuffleIndicies); 5127 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n"); 5128 5129 // Sort operands of the instructions so that each side is more likely to 5130 // have the same opcode. 5131 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) { 5132 ValueList Left, Right; 5133 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 5134 TE->setOperand(0, Left); 5135 TE->setOperand(1, Right); 5136 buildTree_rec(Left, Depth + 1, {TE, 0}); 5137 buildTree_rec(Right, Depth + 1, {TE, 1}); 5138 return; 5139 } 5140 5141 TE->setOperandsInOrder(); 5142 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 5143 ValueList Operands; 5144 // Prepare the operand vector. 5145 for (Value *V : VL) 5146 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 5147 5148 buildTree_rec(Operands, Depth + 1, {TE, i}); 5149 } 5150 return; 5151 } 5152 case Instruction::GetElementPtr: { 5153 // We don't combine GEPs with complicated (nested) indexing. 5154 for (Value *V : VL) { 5155 auto *I = dyn_cast<GetElementPtrInst>(V); 5156 if (!I) 5157 continue; 5158 if (I->getNumOperands() != 2) { 5159 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"); 5160 BS.cancelScheduling(VL, VL0); 5161 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5162 ReuseShuffleIndicies); 5163 return; 5164 } 5165 } 5166 5167 // We can't combine several GEPs into one vector if they operate on 5168 // different types. 5169 Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType(); 5170 for (Value *V : VL) { 5171 auto *GEP = dyn_cast<GEPOperator>(V); 5172 if (!GEP) 5173 continue; 5174 Type *CurTy = GEP->getSourceElementType(); 5175 if (Ty0 != CurTy) { 5176 LLVM_DEBUG(dbgs() 5177 << "SLP: not-vectorizable GEP (different types).\n"); 5178 BS.cancelScheduling(VL, VL0); 5179 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5180 ReuseShuffleIndicies); 5181 return; 5182 } 5183 } 5184 5185 bool IsScatterUser = 5186 UserTreeIdx.UserTE && 5187 UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize; 5188 // We don't combine GEPs with non-constant indexes. 5189 Type *Ty1 = VL0->getOperand(1)->getType(); 5190 for (Value *V : VL) { 5191 auto *I = dyn_cast<GetElementPtrInst>(V); 5192 if (!I) 5193 continue; 5194 auto *Op = I->getOperand(1); 5195 if ((!IsScatterUser && !isa<ConstantInt>(Op)) || 5196 (Op->getType() != Ty1 && 5197 ((IsScatterUser && !isa<ConstantInt>(Op)) || 5198 Op->getType()->getScalarSizeInBits() > 5199 DL->getIndexSizeInBits( 5200 V->getType()->getPointerAddressSpace())))) { 5201 LLVM_DEBUG(dbgs() 5202 << "SLP: not-vectorizable GEP (non-constant indexes).\n"); 5203 BS.cancelScheduling(VL, VL0); 5204 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5205 ReuseShuffleIndicies); 5206 return; 5207 } 5208 } 5209 5210 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5211 ReuseShuffleIndicies); 5212 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n"); 5213 SmallVector<ValueList, 2> Operands(2); 5214 // Prepare the operand vector for pointer operands. 5215 for (Value *V : VL) { 5216 auto *GEP = dyn_cast<GetElementPtrInst>(V); 5217 if (!GEP) { 5218 Operands.front().push_back(V); 5219 continue; 5220 } 5221 Operands.front().push_back(GEP->getPointerOperand()); 5222 } 5223 TE->setOperand(0, Operands.front()); 5224 // Need to cast all indices to the same type before vectorization to 5225 // avoid crash. 5226 // Required to be able to find correct matches between different gather 5227 // nodes and reuse the vectorized values rather than trying to gather them 5228 // again. 5229 int IndexIdx = 1; 5230 Type *VL0Ty = VL0->getOperand(IndexIdx)->getType(); 5231 Type *Ty = all_of(VL, 5232 [VL0Ty, IndexIdx](Value *V) { 5233 auto *GEP = dyn_cast<GetElementPtrInst>(V); 5234 if (!GEP) 5235 return true; 5236 return VL0Ty == GEP->getOperand(IndexIdx)->getType(); 5237 }) 5238 ? VL0Ty 5239 : DL->getIndexType(cast<GetElementPtrInst>(VL0) 5240 ->getPointerOperandType() 5241 ->getScalarType()); 5242 // Prepare the operand vector. 5243 for (Value *V : VL) { 5244 auto *I = dyn_cast<GetElementPtrInst>(V); 5245 if (!I) { 5246 Operands.back().push_back( 5247 ConstantInt::get(Ty, 0, /*isSigned=*/false)); 5248 continue; 5249 } 5250 auto *Op = I->getOperand(IndexIdx); 5251 auto *CI = dyn_cast<ConstantInt>(Op); 5252 if (!CI) 5253 Operands.back().push_back(Op); 5254 else 5255 Operands.back().push_back(ConstantExpr::getIntegerCast( 5256 CI, Ty, CI->getValue().isSignBitSet())); 5257 } 5258 TE->setOperand(IndexIdx, Operands.back()); 5259 5260 for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I) 5261 buildTree_rec(Operands[I], Depth + 1, {TE, I}); 5262 return; 5263 } 5264 case Instruction::Store: { 5265 // Check if the stores are consecutive or if we need to swizzle them. 5266 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType(); 5267 // Avoid types that are padded when being allocated as scalars, while 5268 // being packed together in a vector (such as i1). 5269 if (DL->getTypeSizeInBits(ScalarTy) != 5270 DL->getTypeAllocSizeInBits(ScalarTy)) { 5271 BS.cancelScheduling(VL, VL0); 5272 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5273 ReuseShuffleIndicies); 5274 LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n"); 5275 return; 5276 } 5277 // Make sure all stores in the bundle are simple - we can't vectorize 5278 // atomic or volatile stores. 5279 SmallVector<Value *, 4> PointerOps(VL.size()); 5280 ValueList Operands(VL.size()); 5281 auto POIter = PointerOps.begin(); 5282 auto OIter = Operands.begin(); 5283 for (Value *V : VL) { 5284 auto *SI = cast<StoreInst>(V); 5285 if (!SI->isSimple()) { 5286 BS.cancelScheduling(VL, VL0); 5287 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5288 ReuseShuffleIndicies); 5289 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n"); 5290 return; 5291 } 5292 *POIter = SI->getPointerOperand(); 5293 *OIter = SI->getValueOperand(); 5294 ++POIter; 5295 ++OIter; 5296 } 5297 5298 OrdersType CurrentOrder; 5299 // Check the order of pointer operands. 5300 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) { 5301 Value *Ptr0; 5302 Value *PtrN; 5303 if (CurrentOrder.empty()) { 5304 Ptr0 = PointerOps.front(); 5305 PtrN = PointerOps.back(); 5306 } else { 5307 Ptr0 = PointerOps[CurrentOrder.front()]; 5308 PtrN = PointerOps[CurrentOrder.back()]; 5309 } 5310 Optional<int> Dist = 5311 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE); 5312 // Check that the sorted pointer operands are consecutive. 5313 if (static_cast<unsigned>(*Dist) == VL.size() - 1) { 5314 if (CurrentOrder.empty()) { 5315 // Original stores are consecutive and does not require reordering. 5316 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, 5317 UserTreeIdx, ReuseShuffleIndicies); 5318 TE->setOperandsInOrder(); 5319 buildTree_rec(Operands, Depth + 1, {TE, 0}); 5320 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n"); 5321 } else { 5322 fixupOrderingIndices(CurrentOrder); 5323 TreeEntry *TE = 5324 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5325 ReuseShuffleIndicies, CurrentOrder); 5326 TE->setOperandsInOrder(); 5327 buildTree_rec(Operands, Depth + 1, {TE, 0}); 5328 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n"); 5329 } 5330 return; 5331 } 5332 } 5333 5334 BS.cancelScheduling(VL, VL0); 5335 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5336 ReuseShuffleIndicies); 5337 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n"); 5338 return; 5339 } 5340 case Instruction::Call: { 5341 // Check if the calls are all to the same vectorizable intrinsic or 5342 // library function. 5343 CallInst *CI = cast<CallInst>(VL0); 5344 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 5345 5346 VFShape Shape = VFShape::get( 5347 *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())), 5348 false /*HasGlobalPred*/); 5349 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 5350 5351 if (!VecFunc && !isTriviallyVectorizable(ID)) { 5352 BS.cancelScheduling(VL, VL0); 5353 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5354 ReuseShuffleIndicies); 5355 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n"); 5356 return; 5357 } 5358 Function *F = CI->getCalledFunction(); 5359 unsigned NumArgs = CI->arg_size(); 5360 SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr); 5361 for (unsigned j = 0; j != NumArgs; ++j) 5362 if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) 5363 ScalarArgs[j] = CI->getArgOperand(j); 5364 for (Value *V : VL) { 5365 CallInst *CI2 = dyn_cast<CallInst>(V); 5366 if (!CI2 || CI2->getCalledFunction() != F || 5367 getVectorIntrinsicIDForCall(CI2, TLI) != ID || 5368 (VecFunc && 5369 VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) || 5370 !CI->hasIdenticalOperandBundleSchema(*CI2)) { 5371 BS.cancelScheduling(VL, VL0); 5372 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5373 ReuseShuffleIndicies); 5374 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V 5375 << "\n"); 5376 return; 5377 } 5378 // Some intrinsics have scalar arguments and should be same in order for 5379 // them to be vectorized. 5380 for (unsigned j = 0; j != NumArgs; ++j) { 5381 if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) { 5382 Value *A1J = CI2->getArgOperand(j); 5383 if (ScalarArgs[j] != A1J) { 5384 BS.cancelScheduling(VL, VL0); 5385 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5386 ReuseShuffleIndicies); 5387 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI 5388 << " argument " << ScalarArgs[j] << "!=" << A1J 5389 << "\n"); 5390 return; 5391 } 5392 } 5393 } 5394 // Verify that the bundle operands are identical between the two calls. 5395 if (CI->hasOperandBundles() && 5396 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(), 5397 CI->op_begin() + CI->getBundleOperandsEndIndex(), 5398 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) { 5399 BS.cancelScheduling(VL, VL0); 5400 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5401 ReuseShuffleIndicies); 5402 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" 5403 << *CI << "!=" << *V << '\n'); 5404 return; 5405 } 5406 } 5407 5408 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5409 ReuseShuffleIndicies); 5410 TE->setOperandsInOrder(); 5411 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 5412 // For scalar operands no need to to create an entry since no need to 5413 // vectorize it. 5414 if (isVectorIntrinsicWithScalarOpAtArg(ID, i)) 5415 continue; 5416 ValueList Operands; 5417 // Prepare the operand vector. 5418 for (Value *V : VL) { 5419 auto *CI2 = cast<CallInst>(V); 5420 Operands.push_back(CI2->getArgOperand(i)); 5421 } 5422 buildTree_rec(Operands, Depth + 1, {TE, i}); 5423 } 5424 return; 5425 } 5426 case Instruction::ShuffleVector: { 5427 // If this is not an alternate sequence of opcode like add-sub 5428 // then do not vectorize this instruction. 5429 if (!S.isAltShuffle()) { 5430 BS.cancelScheduling(VL, VL0); 5431 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5432 ReuseShuffleIndicies); 5433 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n"); 5434 return; 5435 } 5436 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5437 ReuseShuffleIndicies); 5438 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n"); 5439 5440 // Reorder operands if reordering would enable vectorization. 5441 auto *CI = dyn_cast<CmpInst>(VL0); 5442 if (isa<BinaryOperator>(VL0) || CI) { 5443 ValueList Left, Right; 5444 if (!CI || all_of(VL, [](Value *V) { 5445 return cast<CmpInst>(V)->isCommutative(); 5446 })) { 5447 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 5448 } else { 5449 CmpInst::Predicate P0 = CI->getPredicate(); 5450 CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate(); 5451 assert(P0 != AltP0 && 5452 "Expected different main/alternate predicates."); 5453 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 5454 Value *BaseOp0 = VL0->getOperand(0); 5455 Value *BaseOp1 = VL0->getOperand(1); 5456 // Collect operands - commute if it uses the swapped predicate or 5457 // alternate operation. 5458 for (Value *V : VL) { 5459 auto *Cmp = cast<CmpInst>(V); 5460 Value *LHS = Cmp->getOperand(0); 5461 Value *RHS = Cmp->getOperand(1); 5462 CmpInst::Predicate CurrentPred = Cmp->getPredicate(); 5463 if (P0 == AltP0Swapped) { 5464 if (CI != Cmp && S.AltOp != Cmp && 5465 ((P0 == CurrentPred && 5466 !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) || 5467 (AltP0 == CurrentPred && 5468 areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)))) 5469 std::swap(LHS, RHS); 5470 } else if (P0 != CurrentPred && AltP0 != CurrentPred) { 5471 std::swap(LHS, RHS); 5472 } 5473 Left.push_back(LHS); 5474 Right.push_back(RHS); 5475 } 5476 } 5477 TE->setOperand(0, Left); 5478 TE->setOperand(1, Right); 5479 buildTree_rec(Left, Depth + 1, {TE, 0}); 5480 buildTree_rec(Right, Depth + 1, {TE, 1}); 5481 return; 5482 } 5483 5484 TE->setOperandsInOrder(); 5485 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 5486 ValueList Operands; 5487 // Prepare the operand vector. 5488 for (Value *V : VL) 5489 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 5490 5491 buildTree_rec(Operands, Depth + 1, {TE, i}); 5492 } 5493 return; 5494 } 5495 default: 5496 BS.cancelScheduling(VL, VL0); 5497 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5498 ReuseShuffleIndicies); 5499 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); 5500 return; 5501 } 5502 } 5503 5504 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const { 5505 unsigned N = 1; 5506 Type *EltTy = T; 5507 5508 while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) || 5509 isa<VectorType>(EltTy)) { 5510 if (auto *ST = dyn_cast<StructType>(EltTy)) { 5511 // Check that struct is homogeneous. 5512 for (const auto *Ty : ST->elements()) 5513 if (Ty != *ST->element_begin()) 5514 return 0; 5515 N *= ST->getNumElements(); 5516 EltTy = *ST->element_begin(); 5517 } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) { 5518 N *= AT->getNumElements(); 5519 EltTy = AT->getElementType(); 5520 } else { 5521 auto *VT = cast<FixedVectorType>(EltTy); 5522 N *= VT->getNumElements(); 5523 EltTy = VT->getElementType(); 5524 } 5525 } 5526 5527 if (!isValidElementType(EltTy)) 5528 return 0; 5529 uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N)); 5530 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T)) 5531 return 0; 5532 return N; 5533 } 5534 5535 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 5536 SmallVectorImpl<unsigned> &CurrentOrder) const { 5537 const auto *It = find_if(VL, [](Value *V) { 5538 return isa<ExtractElementInst, ExtractValueInst>(V); 5539 }); 5540 assert(It != VL.end() && "Expected at least one extract instruction."); 5541 auto *E0 = cast<Instruction>(*It); 5542 assert(all_of(VL, 5543 [](Value *V) { 5544 return isa<UndefValue, ExtractElementInst, ExtractValueInst>( 5545 V); 5546 }) && 5547 "Invalid opcode"); 5548 // Check if all of the extracts come from the same vector and from the 5549 // correct offset. 5550 Value *Vec = E0->getOperand(0); 5551 5552 CurrentOrder.clear(); 5553 5554 // We have to extract from a vector/aggregate with the same number of elements. 5555 unsigned NElts; 5556 if (E0->getOpcode() == Instruction::ExtractValue) { 5557 const DataLayout &DL = E0->getModule()->getDataLayout(); 5558 NElts = canMapToVector(Vec->getType(), DL); 5559 if (!NElts) 5560 return false; 5561 // Check if load can be rewritten as load of vector. 5562 LoadInst *LI = dyn_cast<LoadInst>(Vec); 5563 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size())) 5564 return false; 5565 } else { 5566 NElts = cast<FixedVectorType>(Vec->getType())->getNumElements(); 5567 } 5568 5569 if (NElts != VL.size()) 5570 return false; 5571 5572 // Check that all of the indices extract from the correct offset. 5573 bool ShouldKeepOrder = true; 5574 unsigned E = VL.size(); 5575 // Assign to all items the initial value E + 1 so we can check if the extract 5576 // instruction index was used already. 5577 // Also, later we can check that all the indices are used and we have a 5578 // consecutive access in the extract instructions, by checking that no 5579 // element of CurrentOrder still has value E + 1. 5580 CurrentOrder.assign(E, E); 5581 unsigned I = 0; 5582 for (; I < E; ++I) { 5583 auto *Inst = dyn_cast<Instruction>(VL[I]); 5584 if (!Inst) 5585 continue; 5586 if (Inst->getOperand(0) != Vec) 5587 break; 5588 if (auto *EE = dyn_cast<ExtractElementInst>(Inst)) 5589 if (isa<UndefValue>(EE->getIndexOperand())) 5590 continue; 5591 Optional<unsigned> Idx = getExtractIndex(Inst); 5592 if (!Idx) 5593 break; 5594 const unsigned ExtIdx = *Idx; 5595 if (ExtIdx != I) { 5596 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E) 5597 break; 5598 ShouldKeepOrder = false; 5599 CurrentOrder[ExtIdx] = I; 5600 } else { 5601 if (CurrentOrder[I] != E) 5602 break; 5603 CurrentOrder[I] = I; 5604 } 5605 } 5606 if (I < E) { 5607 CurrentOrder.clear(); 5608 return false; 5609 } 5610 if (ShouldKeepOrder) 5611 CurrentOrder.clear(); 5612 5613 return ShouldKeepOrder; 5614 } 5615 5616 bool BoUpSLP::areAllUsersVectorized(Instruction *I, 5617 ArrayRef<Value *> VectorizedVals) const { 5618 return (I->hasOneUse() && is_contained(VectorizedVals, I)) || 5619 all_of(I->users(), [this](User *U) { 5620 return ScalarToTreeEntry.count(U) > 0 || 5621 isVectorLikeInstWithConstOps(U) || 5622 (isa<ExtractElementInst>(U) && MustGather.contains(U)); 5623 }); 5624 } 5625 5626 static std::pair<InstructionCost, InstructionCost> 5627 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy, 5628 TargetTransformInfo *TTI, TargetLibraryInfo *TLI) { 5629 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 5630 5631 // Calculate the cost of the scalar and vector calls. 5632 SmallVector<Type *, 4> VecTys; 5633 for (Use &Arg : CI->args()) 5634 VecTys.push_back( 5635 FixedVectorType::get(Arg->getType(), VecTy->getNumElements())); 5636 FastMathFlags FMF; 5637 if (auto *FPCI = dyn_cast<FPMathOperator>(CI)) 5638 FMF = FPCI->getFastMathFlags(); 5639 SmallVector<const Value *> Arguments(CI->args()); 5640 IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF, 5641 dyn_cast<IntrinsicInst>(CI)); 5642 auto IntrinsicCost = 5643 TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput); 5644 5645 auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 5646 VecTy->getNumElements())), 5647 false /*HasGlobalPred*/); 5648 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 5649 auto LibCost = IntrinsicCost; 5650 if (!CI->isNoBuiltin() && VecFunc) { 5651 // Calculate the cost of the vector library call. 5652 // If the corresponding vector call is cheaper, return its cost. 5653 LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys, 5654 TTI::TCK_RecipThroughput); 5655 } 5656 return {IntrinsicCost, LibCost}; 5657 } 5658 5659 /// Compute the cost of creating a vector of type \p VecTy containing the 5660 /// extracted values from \p VL. 5661 static InstructionCost 5662 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy, 5663 TargetTransformInfo::ShuffleKind ShuffleKind, 5664 ArrayRef<int> Mask, TargetTransformInfo &TTI) { 5665 unsigned NumOfParts = TTI.getNumberOfParts(VecTy); 5666 5667 if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts || 5668 VecTy->getNumElements() < NumOfParts) 5669 return TTI.getShuffleCost(ShuffleKind, VecTy, Mask); 5670 5671 bool AllConsecutive = true; 5672 unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts; 5673 unsigned Idx = -1; 5674 InstructionCost Cost = 0; 5675 5676 // Process extracts in blocks of EltsPerVector to check if the source vector 5677 // operand can be re-used directly. If not, add the cost of creating a shuffle 5678 // to extract the values into a vector register. 5679 SmallVector<int> RegMask(EltsPerVector, UndefMaskElem); 5680 for (auto *V : VL) { 5681 ++Idx; 5682 5683 // Reached the start of a new vector registers. 5684 if (Idx % EltsPerVector == 0) { 5685 RegMask.assign(EltsPerVector, UndefMaskElem); 5686 AllConsecutive = true; 5687 continue; 5688 } 5689 5690 // Need to exclude undefs from analysis. 5691 if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem) 5692 continue; 5693 5694 // Check all extracts for a vector register on the target directly 5695 // extract values in order. 5696 unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V)); 5697 if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) { 5698 unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1])); 5699 AllConsecutive &= PrevIdx + 1 == CurrentIdx && 5700 CurrentIdx % EltsPerVector == Idx % EltsPerVector; 5701 RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector; 5702 } 5703 5704 if (AllConsecutive) 5705 continue; 5706 5707 // Skip all indices, except for the last index per vector block. 5708 if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size()) 5709 continue; 5710 5711 // If we have a series of extracts which are not consecutive and hence 5712 // cannot re-use the source vector register directly, compute the shuffle 5713 // cost to extract the vector with EltsPerVector elements. 5714 Cost += TTI.getShuffleCost( 5715 TargetTransformInfo::SK_PermuteSingleSrc, 5716 FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask); 5717 } 5718 return Cost; 5719 } 5720 5721 /// Build shuffle mask for shuffle graph entries and lists of main and alternate 5722 /// operations operands. 5723 static void 5724 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices, 5725 ArrayRef<int> ReusesIndices, 5726 const function_ref<bool(Instruction *)> IsAltOp, 5727 SmallVectorImpl<int> &Mask, 5728 SmallVectorImpl<Value *> *OpScalars = nullptr, 5729 SmallVectorImpl<Value *> *AltScalars = nullptr) { 5730 unsigned Sz = VL.size(); 5731 Mask.assign(Sz, UndefMaskElem); 5732 SmallVector<int> OrderMask; 5733 if (!ReorderIndices.empty()) 5734 inversePermutation(ReorderIndices, OrderMask); 5735 for (unsigned I = 0; I < Sz; ++I) { 5736 unsigned Idx = I; 5737 if (!ReorderIndices.empty()) 5738 Idx = OrderMask[I]; 5739 auto *OpInst = cast<Instruction>(VL[Idx]); 5740 if (IsAltOp(OpInst)) { 5741 Mask[I] = Sz + Idx; 5742 if (AltScalars) 5743 AltScalars->push_back(OpInst); 5744 } else { 5745 Mask[I] = Idx; 5746 if (OpScalars) 5747 OpScalars->push_back(OpInst); 5748 } 5749 } 5750 if (!ReusesIndices.empty()) { 5751 SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem); 5752 transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) { 5753 return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem; 5754 }); 5755 Mask.swap(NewMask); 5756 } 5757 } 5758 5759 /// Checks if the specified instruction \p I is an alternate operation for the 5760 /// given \p MainOp and \p AltOp instructions. 5761 static bool isAlternateInstruction(const Instruction *I, 5762 const Instruction *MainOp, 5763 const Instruction *AltOp) { 5764 if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) { 5765 auto *AltCI0 = cast<CmpInst>(AltOp); 5766 auto *CI = cast<CmpInst>(I); 5767 CmpInst::Predicate P0 = CI0->getPredicate(); 5768 CmpInst::Predicate AltP0 = AltCI0->getPredicate(); 5769 assert(P0 != AltP0 && "Expected different main/alternate predicates."); 5770 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 5771 CmpInst::Predicate CurrentPred = CI->getPredicate(); 5772 if (P0 == AltP0Swapped) 5773 return I == AltCI0 || 5774 (I != MainOp && 5775 !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1), 5776 CI->getOperand(0), CI->getOperand(1))); 5777 return AltP0 == CurrentPred || AltP0Swapped == CurrentPred; 5778 } 5779 return I->getOpcode() == AltOp->getOpcode(); 5780 } 5781 5782 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E, 5783 ArrayRef<Value *> VectorizedVals) { 5784 ArrayRef<Value*> VL = E->Scalars; 5785 5786 Type *ScalarTy = VL[0]->getType(); 5787 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 5788 ScalarTy = SI->getValueOperand()->getType(); 5789 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0])) 5790 ScalarTy = CI->getOperand(0)->getType(); 5791 else if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 5792 ScalarTy = IE->getOperand(1)->getType(); 5793 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 5794 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 5795 5796 // If we have computed a smaller type for the expression, update VecTy so 5797 // that the costs will be accurate. 5798 if (MinBWs.count(VL[0])) 5799 VecTy = FixedVectorType::get( 5800 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size()); 5801 unsigned EntryVF = E->getVectorFactor(); 5802 auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF); 5803 5804 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 5805 // FIXME: it tries to fix a problem with MSVC buildbots. 5806 TargetTransformInfo &TTIRef = *TTI; 5807 auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy, 5808 VectorizedVals, E](InstructionCost &Cost) { 5809 DenseMap<Value *, int> ExtractVectorsTys; 5810 SmallPtrSet<Value *, 4> CheckedExtracts; 5811 for (auto *V : VL) { 5812 if (isa<UndefValue>(V)) 5813 continue; 5814 // If all users of instruction are going to be vectorized and this 5815 // instruction itself is not going to be vectorized, consider this 5816 // instruction as dead and remove its cost from the final cost of the 5817 // vectorized tree. 5818 // Also, avoid adjusting the cost for extractelements with multiple uses 5819 // in different graph entries. 5820 const TreeEntry *VE = getTreeEntry(V); 5821 if (!CheckedExtracts.insert(V).second || 5822 !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) || 5823 (VE && VE != E)) 5824 continue; 5825 auto *EE = cast<ExtractElementInst>(V); 5826 Optional<unsigned> EEIdx = getExtractIndex(EE); 5827 if (!EEIdx) 5828 continue; 5829 unsigned Idx = *EEIdx; 5830 if (TTIRef.getNumberOfParts(VecTy) != 5831 TTIRef.getNumberOfParts(EE->getVectorOperandType())) { 5832 auto It = 5833 ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first; 5834 It->getSecond() = std::min<int>(It->second, Idx); 5835 } 5836 // Take credit for instruction that will become dead. 5837 if (EE->hasOneUse()) { 5838 Instruction *Ext = EE->user_back(); 5839 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 5840 all_of(Ext->users(), 5841 [](User *U) { return isa<GetElementPtrInst>(U); })) { 5842 // Use getExtractWithExtendCost() to calculate the cost of 5843 // extractelement/ext pair. 5844 Cost -= 5845 TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(), 5846 EE->getVectorOperandType(), Idx); 5847 // Add back the cost of s|zext which is subtracted separately. 5848 Cost += TTIRef.getCastInstrCost( 5849 Ext->getOpcode(), Ext->getType(), EE->getType(), 5850 TTI::getCastContextHint(Ext), CostKind, Ext); 5851 continue; 5852 } 5853 } 5854 Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement, 5855 EE->getVectorOperandType(), Idx); 5856 } 5857 // Add a cost for subvector extracts/inserts if required. 5858 for (const auto &Data : ExtractVectorsTys) { 5859 auto *EEVTy = cast<FixedVectorType>(Data.first->getType()); 5860 unsigned NumElts = VecTy->getNumElements(); 5861 if (Data.second % NumElts == 0) 5862 continue; 5863 if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) { 5864 unsigned Idx = (Data.second / NumElts) * NumElts; 5865 unsigned EENumElts = EEVTy->getNumElements(); 5866 if (Idx + NumElts <= EENumElts) { 5867 Cost += 5868 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 5869 EEVTy, None, Idx, VecTy); 5870 } else { 5871 // Need to round up the subvector type vectorization factor to avoid a 5872 // crash in cost model functions. Make SubVT so that Idx + VF of SubVT 5873 // <= EENumElts. 5874 auto *SubVT = 5875 FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx); 5876 Cost += 5877 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 5878 EEVTy, None, Idx, SubVT); 5879 } 5880 } else { 5881 Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector, 5882 VecTy, None, 0, EEVTy); 5883 } 5884 } 5885 }; 5886 if (E->State == TreeEntry::NeedToGather) { 5887 if (allConstant(VL)) 5888 return 0; 5889 if (isa<InsertElementInst>(VL[0])) 5890 return InstructionCost::getInvalid(); 5891 SmallVector<int> Mask; 5892 SmallVector<const TreeEntry *> Entries; 5893 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 5894 isGatherShuffledEntry(E, Mask, Entries); 5895 if (Shuffle) { 5896 InstructionCost GatherCost = 0; 5897 if (ShuffleVectorInst::isIdentityMask(Mask)) { 5898 // Perfect match in the graph, will reuse the previously vectorized 5899 // node. Cost is 0. 5900 LLVM_DEBUG( 5901 dbgs() 5902 << "SLP: perfect diamond match for gather bundle that starts with " 5903 << *VL.front() << ".\n"); 5904 if (NeedToShuffleReuses) 5905 GatherCost = 5906 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 5907 FinalVecTy, E->ReuseShuffleIndices); 5908 } else { 5909 LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size() 5910 << " entries for bundle that starts with " 5911 << *VL.front() << ".\n"); 5912 // Detected that instead of gather we can emit a shuffle of single/two 5913 // previously vectorized nodes. Add the cost of the permutation rather 5914 // than gather. 5915 ::addMask(Mask, E->ReuseShuffleIndices); 5916 GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask); 5917 } 5918 return GatherCost; 5919 } 5920 if ((E->getOpcode() == Instruction::ExtractElement || 5921 all_of(E->Scalars, 5922 [](Value *V) { 5923 return isa<ExtractElementInst, UndefValue>(V); 5924 })) && 5925 allSameType(VL)) { 5926 // Check that gather of extractelements can be represented as just a 5927 // shuffle of a single/two vectors the scalars are extracted from. 5928 SmallVector<int> Mask; 5929 Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = 5930 isFixedVectorShuffle(VL, Mask); 5931 if (ShuffleKind) { 5932 // Found the bunch of extractelement instructions that must be gathered 5933 // into a vector and can be represented as a permutation elements in a 5934 // single input vector or of 2 input vectors. 5935 InstructionCost Cost = 5936 computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI); 5937 AdjustExtractsCost(Cost); 5938 if (NeedToShuffleReuses) 5939 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 5940 FinalVecTy, E->ReuseShuffleIndices); 5941 return Cost; 5942 } 5943 } 5944 if (isSplat(VL)) { 5945 // Found the broadcasting of the single scalar, calculate the cost as the 5946 // broadcast. 5947 assert(VecTy == FinalVecTy && 5948 "No reused scalars expected for broadcast."); 5949 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 5950 /*Mask=*/None, /*Index=*/0, 5951 /*SubTp=*/nullptr, /*Args=*/VL[0]); 5952 } 5953 InstructionCost ReuseShuffleCost = 0; 5954 if (NeedToShuffleReuses) 5955 ReuseShuffleCost = TTI->getShuffleCost( 5956 TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices); 5957 // Improve gather cost for gather of loads, if we can group some of the 5958 // loads into vector loads. 5959 if (VL.size() > 2 && E->getOpcode() == Instruction::Load && 5960 !E->isAltShuffle()) { 5961 BoUpSLP::ValueSet VectorizedLoads; 5962 unsigned StartIdx = 0; 5963 unsigned VF = VL.size() / 2; 5964 unsigned VectorizedCnt = 0; 5965 unsigned ScatterVectorizeCnt = 0; 5966 const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType()); 5967 for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) { 5968 for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End; 5969 Cnt += VF) { 5970 ArrayRef<Value *> Slice = VL.slice(Cnt, VF); 5971 if (!VectorizedLoads.count(Slice.front()) && 5972 !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) { 5973 SmallVector<Value *> PointerOps; 5974 OrdersType CurrentOrder; 5975 LoadsState LS = 5976 canVectorizeLoads(Slice, Slice.front(), *TTI, *DL, *SE, *LI, 5977 CurrentOrder, PointerOps); 5978 switch (LS) { 5979 case LoadsState::Vectorize: 5980 case LoadsState::ScatterVectorize: 5981 // Mark the vectorized loads so that we don't vectorize them 5982 // again. 5983 if (LS == LoadsState::Vectorize) 5984 ++VectorizedCnt; 5985 else 5986 ++ScatterVectorizeCnt; 5987 VectorizedLoads.insert(Slice.begin(), Slice.end()); 5988 // If we vectorized initial block, no need to try to vectorize it 5989 // again. 5990 if (Cnt == StartIdx) 5991 StartIdx += VF; 5992 break; 5993 case LoadsState::Gather: 5994 break; 5995 } 5996 } 5997 } 5998 // Check if the whole array was vectorized already - exit. 5999 if (StartIdx >= VL.size()) 6000 break; 6001 // Found vectorizable parts - exit. 6002 if (!VectorizedLoads.empty()) 6003 break; 6004 } 6005 if (!VectorizedLoads.empty()) { 6006 InstructionCost GatherCost = 0; 6007 unsigned NumParts = TTI->getNumberOfParts(VecTy); 6008 bool NeedInsertSubvectorAnalysis = 6009 !NumParts || (VL.size() / VF) > NumParts; 6010 // Get the cost for gathered loads. 6011 for (unsigned I = 0, End = VL.size(); I < End; I += VF) { 6012 if (VectorizedLoads.contains(VL[I])) 6013 continue; 6014 GatherCost += getGatherCost(VL.slice(I, VF)); 6015 } 6016 // The cost for vectorized loads. 6017 InstructionCost ScalarsCost = 0; 6018 for (Value *V : VectorizedLoads) { 6019 auto *LI = cast<LoadInst>(V); 6020 ScalarsCost += TTI->getMemoryOpCost( 6021 Instruction::Load, LI->getType(), LI->getAlign(), 6022 LI->getPointerAddressSpace(), CostKind, LI); 6023 } 6024 auto *LI = cast<LoadInst>(E->getMainOp()); 6025 auto *LoadTy = FixedVectorType::get(LI->getType(), VF); 6026 Align Alignment = LI->getAlign(); 6027 GatherCost += 6028 VectorizedCnt * 6029 TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment, 6030 LI->getPointerAddressSpace(), CostKind, LI); 6031 GatherCost += ScatterVectorizeCnt * 6032 TTI->getGatherScatterOpCost( 6033 Instruction::Load, LoadTy, LI->getPointerOperand(), 6034 /*VariableMask=*/false, Alignment, CostKind, LI); 6035 if (NeedInsertSubvectorAnalysis) { 6036 // Add the cost for the subvectors insert. 6037 for (int I = VF, E = VL.size(); I < E; I += VF) 6038 GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy, 6039 None, I, LoadTy); 6040 } 6041 return ReuseShuffleCost + GatherCost - ScalarsCost; 6042 } 6043 } 6044 return ReuseShuffleCost + getGatherCost(VL); 6045 } 6046 InstructionCost CommonCost = 0; 6047 SmallVector<int> Mask; 6048 if (!E->ReorderIndices.empty()) { 6049 SmallVector<int> NewMask; 6050 if (E->getOpcode() == Instruction::Store) { 6051 // For stores the order is actually a mask. 6052 NewMask.resize(E->ReorderIndices.size()); 6053 copy(E->ReorderIndices, NewMask.begin()); 6054 } else { 6055 inversePermutation(E->ReorderIndices, NewMask); 6056 } 6057 ::addMask(Mask, NewMask); 6058 } 6059 if (NeedToShuffleReuses) 6060 ::addMask(Mask, E->ReuseShuffleIndices); 6061 if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask)) 6062 CommonCost = 6063 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask); 6064 assert((E->State == TreeEntry::Vectorize || 6065 E->State == TreeEntry::ScatterVectorize) && 6066 "Unhandled state"); 6067 assert(E->getOpcode() && 6068 ((allSameType(VL) && allSameBlock(VL)) || 6069 (E->getOpcode() == Instruction::GetElementPtr && 6070 E->getMainOp()->getType()->isPointerTy())) && 6071 "Invalid VL"); 6072 Instruction *VL0 = E->getMainOp(); 6073 unsigned ShuffleOrOp = 6074 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 6075 switch (ShuffleOrOp) { 6076 case Instruction::PHI: 6077 return 0; 6078 6079 case Instruction::ExtractValue: 6080 case Instruction::ExtractElement: { 6081 // The common cost of removal ExtractElement/ExtractValue instructions + 6082 // the cost of shuffles, if required to resuffle the original vector. 6083 if (NeedToShuffleReuses) { 6084 unsigned Idx = 0; 6085 for (unsigned I : E->ReuseShuffleIndices) { 6086 if (ShuffleOrOp == Instruction::ExtractElement) { 6087 auto *EE = cast<ExtractElementInst>(VL[I]); 6088 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 6089 EE->getVectorOperandType(), 6090 *getExtractIndex(EE)); 6091 } else { 6092 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 6093 VecTy, Idx); 6094 ++Idx; 6095 } 6096 } 6097 Idx = EntryVF; 6098 for (Value *V : VL) { 6099 if (ShuffleOrOp == Instruction::ExtractElement) { 6100 auto *EE = cast<ExtractElementInst>(V); 6101 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 6102 EE->getVectorOperandType(), 6103 *getExtractIndex(EE)); 6104 } else { 6105 --Idx; 6106 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 6107 VecTy, Idx); 6108 } 6109 } 6110 } 6111 if (ShuffleOrOp == Instruction::ExtractValue) { 6112 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 6113 auto *EI = cast<Instruction>(VL[I]); 6114 // Take credit for instruction that will become dead. 6115 if (EI->hasOneUse()) { 6116 Instruction *Ext = EI->user_back(); 6117 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 6118 all_of(Ext->users(), 6119 [](User *U) { return isa<GetElementPtrInst>(U); })) { 6120 // Use getExtractWithExtendCost() to calculate the cost of 6121 // extractelement/ext pair. 6122 CommonCost -= TTI->getExtractWithExtendCost( 6123 Ext->getOpcode(), Ext->getType(), VecTy, I); 6124 // Add back the cost of s|zext which is subtracted separately. 6125 CommonCost += TTI->getCastInstrCost( 6126 Ext->getOpcode(), Ext->getType(), EI->getType(), 6127 TTI::getCastContextHint(Ext), CostKind, Ext); 6128 continue; 6129 } 6130 } 6131 CommonCost -= 6132 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I); 6133 } 6134 } else { 6135 AdjustExtractsCost(CommonCost); 6136 } 6137 return CommonCost; 6138 } 6139 case Instruction::InsertElement: { 6140 assert(E->ReuseShuffleIndices.empty() && 6141 "Unique insertelements only are expected."); 6142 auto *SrcVecTy = cast<FixedVectorType>(VL0->getType()); 6143 unsigned const NumElts = SrcVecTy->getNumElements(); 6144 unsigned const NumScalars = VL.size(); 6145 6146 unsigned NumOfParts = TTI->getNumberOfParts(SrcVecTy); 6147 6148 unsigned OffsetBeg = *getInsertIndex(VL.front()); 6149 unsigned OffsetEnd = OffsetBeg; 6150 for (Value *V : VL.drop_front()) { 6151 unsigned Idx = *getInsertIndex(V); 6152 if (OffsetBeg > Idx) 6153 OffsetBeg = Idx; 6154 else if (OffsetEnd < Idx) 6155 OffsetEnd = Idx; 6156 } 6157 unsigned VecScalarsSz = PowerOf2Ceil(NumElts); 6158 if (NumOfParts > 0) 6159 VecScalarsSz = PowerOf2Ceil((NumElts + NumOfParts - 1) / NumOfParts); 6160 unsigned VecSz = 6161 (1 + OffsetEnd / VecScalarsSz - OffsetBeg / VecScalarsSz) * 6162 VecScalarsSz; 6163 unsigned Offset = VecScalarsSz * (OffsetBeg / VecScalarsSz); 6164 unsigned InsertVecSz = std::min<unsigned>( 6165 PowerOf2Ceil(OffsetEnd - OffsetBeg + 1), 6166 ((OffsetEnd - OffsetBeg + VecScalarsSz) / VecScalarsSz) * 6167 VecScalarsSz); 6168 bool IsWholeSubvector = 6169 OffsetBeg == Offset && ((OffsetEnd + 1) % VecScalarsSz == 0); 6170 // Check if we can safely insert a subvector. If it is not possible, just 6171 // generate a whole-sized vector and shuffle the source vector and the new 6172 // subvector. 6173 if (OffsetBeg + InsertVecSz > VecSz) { 6174 // Align OffsetBeg to generate correct mask. 6175 OffsetBeg = alignDown(OffsetBeg, VecSz, Offset); 6176 InsertVecSz = VecSz; 6177 } 6178 6179 APInt DemandedElts = APInt::getZero(NumElts); 6180 // TODO: Add support for Instruction::InsertValue. 6181 SmallVector<int> Mask; 6182 if (!E->ReorderIndices.empty()) { 6183 inversePermutation(E->ReorderIndices, Mask); 6184 Mask.append(InsertVecSz - Mask.size(), UndefMaskElem); 6185 } else { 6186 Mask.assign(VecSz, UndefMaskElem); 6187 std::iota(Mask.begin(), std::next(Mask.begin(), InsertVecSz), 0); 6188 } 6189 bool IsIdentity = true; 6190 SmallVector<int> PrevMask(InsertVecSz, UndefMaskElem); 6191 Mask.swap(PrevMask); 6192 for (unsigned I = 0; I < NumScalars; ++I) { 6193 unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]); 6194 DemandedElts.setBit(InsertIdx); 6195 IsIdentity &= InsertIdx - OffsetBeg == I; 6196 Mask[InsertIdx - OffsetBeg] = I; 6197 } 6198 assert(Offset < NumElts && "Failed to find vector index offset"); 6199 6200 InstructionCost Cost = 0; 6201 Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts, 6202 /*Insert*/ true, /*Extract*/ false); 6203 6204 // First cost - resize to actual vector size if not identity shuffle or 6205 // need to shift the vector. 6206 // Do not calculate the cost if the actual size is the register size and 6207 // we can merge this shuffle with the following SK_Select. 6208 auto *InsertVecTy = 6209 FixedVectorType::get(SrcVecTy->getElementType(), InsertVecSz); 6210 if (!IsIdentity) 6211 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 6212 InsertVecTy, Mask); 6213 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 6214 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); 6215 })); 6216 // Second cost - permutation with subvector, if some elements are from the 6217 // initial vector or inserting a subvector. 6218 // TODO: Implement the analysis of the FirstInsert->getOperand(0) 6219 // subvector of ActualVecTy. 6220 if (!isUndefVector(FirstInsert->getOperand(0)) && NumScalars != NumElts && 6221 !IsWholeSubvector) { 6222 if (InsertVecSz != VecSz) { 6223 auto *ActualVecTy = 6224 FixedVectorType::get(SrcVecTy->getElementType(), VecSz); 6225 Cost += TTI->getShuffleCost(TTI::SK_InsertSubvector, ActualVecTy, 6226 None, OffsetBeg - Offset, InsertVecTy); 6227 } else { 6228 for (unsigned I = 0, End = OffsetBeg - Offset; I < End; ++I) 6229 Mask[I] = I; 6230 for (unsigned I = OffsetBeg - Offset, End = OffsetEnd - Offset; 6231 I <= End; ++I) 6232 if (Mask[I] != UndefMaskElem) 6233 Mask[I] = I + VecSz; 6234 for (unsigned I = OffsetEnd + 1 - Offset; I < VecSz; ++I) 6235 Mask[I] = I; 6236 Cost += TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, InsertVecTy, Mask); 6237 } 6238 } 6239 return Cost; 6240 } 6241 case Instruction::ZExt: 6242 case Instruction::SExt: 6243 case Instruction::FPToUI: 6244 case Instruction::FPToSI: 6245 case Instruction::FPExt: 6246 case Instruction::PtrToInt: 6247 case Instruction::IntToPtr: 6248 case Instruction::SIToFP: 6249 case Instruction::UIToFP: 6250 case Instruction::Trunc: 6251 case Instruction::FPTrunc: 6252 case Instruction::BitCast: { 6253 Type *SrcTy = VL0->getOperand(0)->getType(); 6254 InstructionCost ScalarEltCost = 6255 TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy, 6256 TTI::getCastContextHint(VL0), CostKind, VL0); 6257 if (NeedToShuffleReuses) { 6258 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6259 } 6260 6261 // Calculate the cost of this instruction. 6262 InstructionCost ScalarCost = VL.size() * ScalarEltCost; 6263 6264 auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size()); 6265 InstructionCost VecCost = 0; 6266 // Check if the values are candidates to demote. 6267 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) { 6268 VecCost = CommonCost + TTI->getCastInstrCost( 6269 E->getOpcode(), VecTy, SrcVecTy, 6270 TTI::getCastContextHint(VL0), CostKind, VL0); 6271 } 6272 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6273 return VecCost - ScalarCost; 6274 } 6275 case Instruction::FCmp: 6276 case Instruction::ICmp: 6277 case Instruction::Select: { 6278 // Calculate the cost of this instruction. 6279 InstructionCost ScalarEltCost = 6280 TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 6281 CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0); 6282 if (NeedToShuffleReuses) { 6283 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6284 } 6285 auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size()); 6286 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 6287 6288 // Check if all entries in VL are either compares or selects with compares 6289 // as condition that have the same predicates. 6290 CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE; 6291 bool First = true; 6292 for (auto *V : VL) { 6293 CmpInst::Predicate CurrentPred; 6294 auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value()); 6295 if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) && 6296 !match(V, MatchCmp)) || 6297 (!First && VecPred != CurrentPred)) { 6298 VecPred = CmpInst::BAD_ICMP_PREDICATE; 6299 break; 6300 } 6301 First = false; 6302 VecPred = CurrentPred; 6303 } 6304 6305 InstructionCost VecCost = TTI->getCmpSelInstrCost( 6306 E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0); 6307 // Check if it is possible and profitable to use min/max for selects in 6308 // VL. 6309 // 6310 auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL); 6311 if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) { 6312 IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy, 6313 {VecTy, VecTy}); 6314 InstructionCost IntrinsicCost = 6315 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 6316 // If the selects are the only uses of the compares, they will be dead 6317 // and we can adjust the cost by removing their cost. 6318 if (IntrinsicAndUse.second) 6319 IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, 6320 MaskTy, VecPred, CostKind); 6321 VecCost = std::min(VecCost, IntrinsicCost); 6322 } 6323 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6324 return CommonCost + VecCost - ScalarCost; 6325 } 6326 case Instruction::FNeg: 6327 case Instruction::Add: 6328 case Instruction::FAdd: 6329 case Instruction::Sub: 6330 case Instruction::FSub: 6331 case Instruction::Mul: 6332 case Instruction::FMul: 6333 case Instruction::UDiv: 6334 case Instruction::SDiv: 6335 case Instruction::FDiv: 6336 case Instruction::URem: 6337 case Instruction::SRem: 6338 case Instruction::FRem: 6339 case Instruction::Shl: 6340 case Instruction::LShr: 6341 case Instruction::AShr: 6342 case Instruction::And: 6343 case Instruction::Or: 6344 case Instruction::Xor: { 6345 // Certain instructions can be cheaper to vectorize if they have a 6346 // constant second vector operand. 6347 TargetTransformInfo::OperandValueKind Op1VK = 6348 TargetTransformInfo::OK_AnyValue; 6349 TargetTransformInfo::OperandValueKind Op2VK = 6350 TargetTransformInfo::OK_UniformConstantValue; 6351 TargetTransformInfo::OperandValueProperties Op1VP = 6352 TargetTransformInfo::OP_None; 6353 TargetTransformInfo::OperandValueProperties Op2VP = 6354 TargetTransformInfo::OP_PowerOf2; 6355 6356 // If all operands are exactly the same ConstantInt then set the 6357 // operand kind to OK_UniformConstantValue. 6358 // If instead not all operands are constants, then set the operand kind 6359 // to OK_AnyValue. If all operands are constants but not the same, 6360 // then set the operand kind to OK_NonUniformConstantValue. 6361 ConstantInt *CInt0 = nullptr; 6362 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 6363 const Instruction *I = cast<Instruction>(VL[i]); 6364 unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0; 6365 ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx)); 6366 if (!CInt) { 6367 Op2VK = TargetTransformInfo::OK_AnyValue; 6368 Op2VP = TargetTransformInfo::OP_None; 6369 break; 6370 } 6371 if (Op2VP == TargetTransformInfo::OP_PowerOf2 && 6372 !CInt->getValue().isPowerOf2()) 6373 Op2VP = TargetTransformInfo::OP_None; 6374 if (i == 0) { 6375 CInt0 = CInt; 6376 continue; 6377 } 6378 if (CInt0 != CInt) 6379 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 6380 } 6381 6382 SmallVector<const Value *, 4> Operands(VL0->operand_values()); 6383 InstructionCost ScalarEltCost = 6384 TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK, 6385 Op2VK, Op1VP, Op2VP, Operands, VL0); 6386 if (NeedToShuffleReuses) { 6387 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6388 } 6389 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 6390 InstructionCost VecCost = 6391 TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK, 6392 Op2VK, Op1VP, Op2VP, Operands, VL0); 6393 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6394 return CommonCost + VecCost - ScalarCost; 6395 } 6396 case Instruction::GetElementPtr: { 6397 TargetTransformInfo::OperandValueKind Op1VK = 6398 TargetTransformInfo::OK_AnyValue; 6399 TargetTransformInfo::OperandValueKind Op2VK = 6400 any_of(VL, 6401 [](Value *V) { 6402 return isa<GetElementPtrInst>(V) && 6403 !isConstant( 6404 cast<GetElementPtrInst>(V)->getOperand(1)); 6405 }) 6406 ? TargetTransformInfo::OK_AnyValue 6407 : TargetTransformInfo::OK_UniformConstantValue; 6408 6409 InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost( 6410 Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK); 6411 if (NeedToShuffleReuses) { 6412 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6413 } 6414 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 6415 InstructionCost VecCost = TTI->getArithmeticInstrCost( 6416 Instruction::Add, VecTy, CostKind, Op1VK, Op2VK); 6417 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6418 return CommonCost + VecCost - ScalarCost; 6419 } 6420 case Instruction::Load: { 6421 // Cost of wide load - cost of scalar loads. 6422 Align Alignment = cast<LoadInst>(VL0)->getAlign(); 6423 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 6424 Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0); 6425 if (NeedToShuffleReuses) { 6426 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6427 } 6428 InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost; 6429 InstructionCost VecLdCost; 6430 if (E->State == TreeEntry::Vectorize) { 6431 VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0, 6432 CostKind, VL0); 6433 } else { 6434 assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState"); 6435 Align CommonAlignment = Alignment; 6436 for (Value *V : VL) 6437 CommonAlignment = 6438 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 6439 VecLdCost = TTI->getGatherScatterOpCost( 6440 Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(), 6441 /*VariableMask=*/false, CommonAlignment, CostKind, VL0); 6442 } 6443 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost)); 6444 return CommonCost + VecLdCost - ScalarLdCost; 6445 } 6446 case Instruction::Store: { 6447 // We know that we can merge the stores. Calculate the cost. 6448 bool IsReorder = !E->ReorderIndices.empty(); 6449 auto *SI = 6450 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0); 6451 Align Alignment = SI->getAlign(); 6452 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 6453 Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0); 6454 InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost; 6455 InstructionCost VecStCost = TTI->getMemoryOpCost( 6456 Instruction::Store, VecTy, Alignment, 0, CostKind, VL0); 6457 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost)); 6458 return CommonCost + VecStCost - ScalarStCost; 6459 } 6460 case Instruction::Call: { 6461 CallInst *CI = cast<CallInst>(VL0); 6462 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 6463 6464 // Calculate the cost of the scalar and vector calls. 6465 IntrinsicCostAttributes CostAttrs(ID, *CI, 1); 6466 InstructionCost ScalarEltCost = 6467 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 6468 if (NeedToShuffleReuses) { 6469 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6470 } 6471 InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost; 6472 6473 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 6474 InstructionCost VecCallCost = 6475 std::min(VecCallCosts.first, VecCallCosts.second); 6476 6477 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost 6478 << " (" << VecCallCost << "-" << ScalarCallCost << ")" 6479 << " for " << *CI << "\n"); 6480 6481 return CommonCost + VecCallCost - ScalarCallCost; 6482 } 6483 case Instruction::ShuffleVector: { 6484 assert(E->isAltShuffle() && 6485 ((Instruction::isBinaryOp(E->getOpcode()) && 6486 Instruction::isBinaryOp(E->getAltOpcode())) || 6487 (Instruction::isCast(E->getOpcode()) && 6488 Instruction::isCast(E->getAltOpcode())) || 6489 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 6490 "Invalid Shuffle Vector Operand"); 6491 InstructionCost ScalarCost = 0; 6492 if (NeedToShuffleReuses) { 6493 for (unsigned Idx : E->ReuseShuffleIndices) { 6494 Instruction *I = cast<Instruction>(VL[Idx]); 6495 CommonCost -= TTI->getInstructionCost(I, CostKind); 6496 } 6497 for (Value *V : VL) { 6498 Instruction *I = cast<Instruction>(V); 6499 CommonCost += TTI->getInstructionCost(I, CostKind); 6500 } 6501 } 6502 for (Value *V : VL) { 6503 Instruction *I = cast<Instruction>(V); 6504 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 6505 ScalarCost += TTI->getInstructionCost(I, CostKind); 6506 } 6507 // VecCost is equal to sum of the cost of creating 2 vectors 6508 // and the cost of creating shuffle. 6509 InstructionCost VecCost = 0; 6510 // Try to find the previous shuffle node with the same operands and same 6511 // main/alternate ops. 6512 auto &&TryFindNodeWithEqualOperands = [this, E]() { 6513 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 6514 if (TE.get() == E) 6515 break; 6516 if (TE->isAltShuffle() && 6517 ((TE->getOpcode() == E->getOpcode() && 6518 TE->getAltOpcode() == E->getAltOpcode()) || 6519 (TE->getOpcode() == E->getAltOpcode() && 6520 TE->getAltOpcode() == E->getOpcode())) && 6521 TE->hasEqualOperands(*E)) 6522 return true; 6523 } 6524 return false; 6525 }; 6526 if (TryFindNodeWithEqualOperands()) { 6527 LLVM_DEBUG({ 6528 dbgs() << "SLP: diamond match for alternate node found.\n"; 6529 E->dump(); 6530 }); 6531 // No need to add new vector costs here since we're going to reuse 6532 // same main/alternate vector ops, just do different shuffling. 6533 } else if (Instruction::isBinaryOp(E->getOpcode())) { 6534 VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind); 6535 VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy, 6536 CostKind); 6537 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 6538 VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, 6539 Builder.getInt1Ty(), 6540 CI0->getPredicate(), CostKind, VL0); 6541 VecCost += TTI->getCmpSelInstrCost( 6542 E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 6543 cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind, 6544 E->getAltOp()); 6545 } else { 6546 Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType(); 6547 Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType(); 6548 auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size()); 6549 auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size()); 6550 VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty, 6551 TTI::CastContextHint::None, CostKind); 6552 VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty, 6553 TTI::CastContextHint::None, CostKind); 6554 } 6555 6556 if (E->ReuseShuffleIndices.empty()) { 6557 CommonCost = 6558 TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy); 6559 } else { 6560 SmallVector<int> Mask; 6561 buildShuffleEntryMask( 6562 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 6563 [E](Instruction *I) { 6564 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 6565 return I->getOpcode() == E->getAltOpcode(); 6566 }, 6567 Mask); 6568 CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, 6569 FinalVecTy, Mask); 6570 } 6571 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6572 return CommonCost + VecCost - ScalarCost; 6573 } 6574 default: 6575 llvm_unreachable("Unknown instruction"); 6576 } 6577 } 6578 6579 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const { 6580 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height " 6581 << VectorizableTree.size() << " is fully vectorizable .\n"); 6582 6583 auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) { 6584 SmallVector<int> Mask; 6585 return TE->State == TreeEntry::NeedToGather && 6586 !any_of(TE->Scalars, 6587 [this](Value *V) { return EphValues.contains(V); }) && 6588 (allConstant(TE->Scalars) || isSplat(TE->Scalars) || 6589 TE->Scalars.size() < Limit || 6590 ((TE->getOpcode() == Instruction::ExtractElement || 6591 all_of(TE->Scalars, 6592 [](Value *V) { 6593 return isa<ExtractElementInst, UndefValue>(V); 6594 })) && 6595 isFixedVectorShuffle(TE->Scalars, Mask)) || 6596 (TE->State == TreeEntry::NeedToGather && 6597 TE->getOpcode() == Instruction::Load && !TE->isAltShuffle())); 6598 }; 6599 6600 // We only handle trees of heights 1 and 2. 6601 if (VectorizableTree.size() == 1 && 6602 (VectorizableTree[0]->State == TreeEntry::Vectorize || 6603 (ForReduction && 6604 AreVectorizableGathers(VectorizableTree[0].get(), 6605 VectorizableTree[0]->Scalars.size()) && 6606 VectorizableTree[0]->getVectorFactor() > 2))) 6607 return true; 6608 6609 if (VectorizableTree.size() != 2) 6610 return false; 6611 6612 // Handle splat and all-constants stores. Also try to vectorize tiny trees 6613 // with the second gather nodes if they have less scalar operands rather than 6614 // the initial tree element (may be profitable to shuffle the second gather) 6615 // or they are extractelements, which form shuffle. 6616 SmallVector<int> Mask; 6617 if (VectorizableTree[0]->State == TreeEntry::Vectorize && 6618 AreVectorizableGathers(VectorizableTree[1].get(), 6619 VectorizableTree[0]->Scalars.size())) 6620 return true; 6621 6622 // Gathering cost would be too much for tiny trees. 6623 if (VectorizableTree[0]->State == TreeEntry::NeedToGather || 6624 (VectorizableTree[1]->State == TreeEntry::NeedToGather && 6625 VectorizableTree[0]->State != TreeEntry::ScatterVectorize)) 6626 return false; 6627 6628 return true; 6629 } 6630 6631 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts, 6632 TargetTransformInfo *TTI, 6633 bool MustMatchOrInst) { 6634 // Look past the root to find a source value. Arbitrarily follow the 6635 // path through operand 0 of any 'or'. Also, peek through optional 6636 // shift-left-by-multiple-of-8-bits. 6637 Value *ZextLoad = Root; 6638 const APInt *ShAmtC; 6639 bool FoundOr = false; 6640 while (!isa<ConstantExpr>(ZextLoad) && 6641 (match(ZextLoad, m_Or(m_Value(), m_Value())) || 6642 (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) && 6643 ShAmtC->urem(8) == 0))) { 6644 auto *BinOp = cast<BinaryOperator>(ZextLoad); 6645 ZextLoad = BinOp->getOperand(0); 6646 if (BinOp->getOpcode() == Instruction::Or) 6647 FoundOr = true; 6648 } 6649 // Check if the input is an extended load of the required or/shift expression. 6650 Value *Load; 6651 if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root || 6652 !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load)) 6653 return false; 6654 6655 // Require that the total load bit width is a legal integer type. 6656 // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target. 6657 // But <16 x i8> --> i128 is not, so the backend probably can't reduce it. 6658 Type *SrcTy = Load->getType(); 6659 unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts; 6660 if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth))) 6661 return false; 6662 6663 // Everything matched - assume that we can fold the whole sequence using 6664 // load combining. 6665 LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at " 6666 << *(cast<Instruction>(Root)) << "\n"); 6667 6668 return true; 6669 } 6670 6671 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const { 6672 if (RdxKind != RecurKind::Or) 6673 return false; 6674 6675 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 6676 Value *FirstReduced = VectorizableTree[0]->Scalars[0]; 6677 return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI, 6678 /* MatchOr */ false); 6679 } 6680 6681 bool BoUpSLP::isLoadCombineCandidate() const { 6682 // Peek through a final sequence of stores and check if all operations are 6683 // likely to be load-combined. 6684 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 6685 for (Value *Scalar : VectorizableTree[0]->Scalars) { 6686 Value *X; 6687 if (!match(Scalar, m_Store(m_Value(X), m_Value())) || 6688 !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true)) 6689 return false; 6690 } 6691 return true; 6692 } 6693 6694 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const { 6695 // No need to vectorize inserts of gathered values. 6696 if (VectorizableTree.size() == 2 && 6697 isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) && 6698 VectorizableTree[1]->State == TreeEntry::NeedToGather && 6699 (VectorizableTree[1]->getVectorFactor() <= 2 || 6700 !(isSplat(VectorizableTree[1]->Scalars) || 6701 allConstant(VectorizableTree[1]->Scalars)))) 6702 return true; 6703 6704 // We can vectorize the tree if its size is greater than or equal to the 6705 // minimum size specified by the MinTreeSize command line option. 6706 if (VectorizableTree.size() >= MinTreeSize) 6707 return false; 6708 6709 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we 6710 // can vectorize it if we can prove it fully vectorizable. 6711 if (isFullyVectorizableTinyTree(ForReduction)) 6712 return false; 6713 6714 assert(VectorizableTree.empty() 6715 ? ExternalUses.empty() 6716 : true && "We shouldn't have any external users"); 6717 6718 // Otherwise, we can't vectorize the tree. It is both tiny and not fully 6719 // vectorizable. 6720 return true; 6721 } 6722 6723 InstructionCost BoUpSLP::getSpillCost() const { 6724 // Walk from the bottom of the tree to the top, tracking which values are 6725 // live. When we see a call instruction that is not part of our tree, 6726 // query TTI to see if there is a cost to keeping values live over it 6727 // (for example, if spills and fills are required). 6728 unsigned BundleWidth = VectorizableTree.front()->Scalars.size(); 6729 InstructionCost Cost = 0; 6730 6731 SmallPtrSet<Instruction*, 4> LiveValues; 6732 Instruction *PrevInst = nullptr; 6733 6734 // The entries in VectorizableTree are not necessarily ordered by their 6735 // position in basic blocks. Collect them and order them by dominance so later 6736 // instructions are guaranteed to be visited first. For instructions in 6737 // different basic blocks, we only scan to the beginning of the block, so 6738 // their order does not matter, as long as all instructions in a basic block 6739 // are grouped together. Using dominance ensures a deterministic order. 6740 SmallVector<Instruction *, 16> OrderedScalars; 6741 for (const auto &TEPtr : VectorizableTree) { 6742 Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]); 6743 if (!Inst) 6744 continue; 6745 OrderedScalars.push_back(Inst); 6746 } 6747 llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) { 6748 auto *NodeA = DT->getNode(A->getParent()); 6749 auto *NodeB = DT->getNode(B->getParent()); 6750 assert(NodeA && "Should only process reachable instructions"); 6751 assert(NodeB && "Should only process reachable instructions"); 6752 assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && 6753 "Different nodes should have different DFS numbers"); 6754 if (NodeA != NodeB) 6755 return NodeA->getDFSNumIn() < NodeB->getDFSNumIn(); 6756 return B->comesBefore(A); 6757 }); 6758 6759 for (Instruction *Inst : OrderedScalars) { 6760 if (!PrevInst) { 6761 PrevInst = Inst; 6762 continue; 6763 } 6764 6765 // Update LiveValues. 6766 LiveValues.erase(PrevInst); 6767 for (auto &J : PrevInst->operands()) { 6768 if (isa<Instruction>(&*J) && getTreeEntry(&*J)) 6769 LiveValues.insert(cast<Instruction>(&*J)); 6770 } 6771 6772 LLVM_DEBUG({ 6773 dbgs() << "SLP: #LV: " << LiveValues.size(); 6774 for (auto *X : LiveValues) 6775 dbgs() << " " << X->getName(); 6776 dbgs() << ", Looking at "; 6777 Inst->dump(); 6778 }); 6779 6780 // Now find the sequence of instructions between PrevInst and Inst. 6781 unsigned NumCalls = 0; 6782 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(), 6783 PrevInstIt = 6784 PrevInst->getIterator().getReverse(); 6785 while (InstIt != PrevInstIt) { 6786 if (PrevInstIt == PrevInst->getParent()->rend()) { 6787 PrevInstIt = Inst->getParent()->rbegin(); 6788 continue; 6789 } 6790 6791 // Debug information does not impact spill cost. 6792 if ((isa<CallInst>(&*PrevInstIt) && 6793 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) && 6794 &*PrevInstIt != PrevInst) 6795 NumCalls++; 6796 6797 ++PrevInstIt; 6798 } 6799 6800 if (NumCalls) { 6801 SmallVector<Type*, 4> V; 6802 for (auto *II : LiveValues) { 6803 auto *ScalarTy = II->getType(); 6804 if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy)) 6805 ScalarTy = VectorTy->getElementType(); 6806 V.push_back(FixedVectorType::get(ScalarTy, BundleWidth)); 6807 } 6808 Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V); 6809 } 6810 6811 PrevInst = Inst; 6812 } 6813 6814 return Cost; 6815 } 6816 6817 /// Check if two insertelement instructions are from the same buildvector. 6818 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU, 6819 InsertElementInst *V) { 6820 // Instructions must be from the same basic blocks. 6821 if (VU->getParent() != V->getParent()) 6822 return false; 6823 // Checks if 2 insertelements are from the same buildvector. 6824 if (VU->getType() != V->getType()) 6825 return false; 6826 // Multiple used inserts are separate nodes. 6827 if (!VU->hasOneUse() && !V->hasOneUse()) 6828 return false; 6829 auto *IE1 = VU; 6830 auto *IE2 = V; 6831 unsigned Idx1 = *getInsertIndex(IE1); 6832 unsigned Idx2 = *getInsertIndex(IE2); 6833 // Go through the vector operand of insertelement instructions trying to find 6834 // either VU as the original vector for IE2 or V as the original vector for 6835 // IE1. 6836 do { 6837 if (IE2 == VU) 6838 return VU->hasOneUse(); 6839 if (IE1 == V) 6840 return V->hasOneUse(); 6841 if (IE1) { 6842 if ((IE1 != VU && !IE1->hasOneUse()) || 6843 getInsertIndex(IE1).value_or(Idx2) == Idx2) 6844 IE1 = nullptr; 6845 else 6846 IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0)); 6847 } 6848 if (IE2) { 6849 if ((IE2 != V && !IE2->hasOneUse()) || 6850 getInsertIndex(IE2).value_or(Idx1) == Idx1) 6851 IE2 = nullptr; 6852 else 6853 IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0)); 6854 } 6855 } while (IE1 || IE2); 6856 return false; 6857 } 6858 6859 /// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the 6860 /// buildvector sequence. 6861 static bool isFirstInsertElement(const InsertElementInst *IE1, 6862 const InsertElementInst *IE2) { 6863 if (IE1 == IE2) 6864 return false; 6865 const auto *I1 = IE1; 6866 const auto *I2 = IE2; 6867 const InsertElementInst *PrevI1; 6868 const InsertElementInst *PrevI2; 6869 unsigned Idx1 = *getInsertIndex(IE1); 6870 unsigned Idx2 = *getInsertIndex(IE2); 6871 do { 6872 if (I2 == IE1) 6873 return true; 6874 if (I1 == IE2) 6875 return false; 6876 PrevI1 = I1; 6877 PrevI2 = I2; 6878 if (I1 && (I1 == IE1 || I1->hasOneUse()) && 6879 getInsertIndex(I1).value_or(Idx2) != Idx2) 6880 I1 = dyn_cast<InsertElementInst>(I1->getOperand(0)); 6881 if (I2 && ((I2 == IE2 || I2->hasOneUse())) && 6882 getInsertIndex(I2).value_or(Idx1) != Idx1) 6883 I2 = dyn_cast<InsertElementInst>(I2->getOperand(0)); 6884 } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2)); 6885 llvm_unreachable("Two different buildvectors not expected."); 6886 } 6887 6888 namespace { 6889 /// Returns incoming Value *, if the requested type is Value * too, or a default 6890 /// value, otherwise. 6891 struct ValueSelect { 6892 template <typename U> 6893 static typename std::enable_if<std::is_same<Value *, U>::value, Value *>::type 6894 get(Value *V) { 6895 return V; 6896 } 6897 template <typename U> 6898 static typename std::enable_if<!std::is_same<Value *, U>::value, U>::type 6899 get(Value *) { 6900 return U(); 6901 } 6902 }; 6903 } // namespace 6904 6905 /// Does the analysis of the provided shuffle masks and performs the requested 6906 /// actions on the vectors with the given shuffle masks. It tries to do it in 6907 /// several steps. 6908 /// 1. If the Base vector is not undef vector, resizing the very first mask to 6909 /// have common VF and perform action for 2 input vectors (including non-undef 6910 /// Base). Other shuffle masks are combined with the resulting after the 1 stage 6911 /// and processed as a shuffle of 2 elements. 6912 /// 2. If the Base is undef vector and have only 1 shuffle mask, perform the 6913 /// action only for 1 vector with the given mask, if it is not the identity 6914 /// mask. 6915 /// 3. If > 2 masks are used, perform the remaining shuffle actions for 2 6916 /// vectors, combing the masks properly between the steps. 6917 template <typename T> 6918 static T *performExtractsShuffleAction( 6919 MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base, 6920 function_ref<unsigned(T *)> GetVF, 6921 function_ref<std::pair<T *, bool>(T *, ArrayRef<int>)> ResizeAction, 6922 function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) { 6923 assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts."); 6924 SmallVector<int> Mask(ShuffleMask.begin()->second); 6925 auto VMIt = std::next(ShuffleMask.begin()); 6926 T *Prev = nullptr; 6927 bool IsBaseNotUndef = !isUndefVector(Base); 6928 if (IsBaseNotUndef) { 6929 // Base is not undef, need to combine it with the next subvectors. 6930 std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask); 6931 for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) { 6932 if (Mask[Idx] == UndefMaskElem) 6933 Mask[Idx] = Idx; 6934 else 6935 Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF; 6936 } 6937 auto *V = ValueSelect::get<T *>(Base); 6938 (void)V; 6939 assert((!V || GetVF(V) == Mask.size()) && 6940 "Expected base vector of VF number of elements."); 6941 Prev = Action(Mask, {nullptr, Res.first}); 6942 } else if (ShuffleMask.size() == 1) { 6943 // Base is undef and only 1 vector is shuffled - perform the action only for 6944 // single vector, if the mask is not the identity mask. 6945 std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask); 6946 if (Res.second) 6947 // Identity mask is found. 6948 Prev = Res.first; 6949 else 6950 Prev = Action(Mask, {ShuffleMask.begin()->first}); 6951 } else { 6952 // Base is undef and at least 2 input vectors shuffled - perform 2 vectors 6953 // shuffles step by step, combining shuffle between the steps. 6954 unsigned Vec1VF = GetVF(ShuffleMask.begin()->first); 6955 unsigned Vec2VF = GetVF(VMIt->first); 6956 if (Vec1VF == Vec2VF) { 6957 // No need to resize the input vectors since they are of the same size, we 6958 // can shuffle them directly. 6959 ArrayRef<int> SecMask = VMIt->second; 6960 for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) { 6961 if (SecMask[I] != UndefMaskElem) { 6962 assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars."); 6963 Mask[I] = SecMask[I] + Vec1VF; 6964 } 6965 } 6966 Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first}); 6967 } else { 6968 // Vectors of different sizes - resize and reshuffle. 6969 std::pair<T *, bool> Res1 = 6970 ResizeAction(ShuffleMask.begin()->first, Mask); 6971 std::pair<T *, bool> Res2 = ResizeAction(VMIt->first, VMIt->second); 6972 ArrayRef<int> SecMask = VMIt->second; 6973 for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) { 6974 if (Mask[I] != UndefMaskElem) { 6975 assert(SecMask[I] == UndefMaskElem && "Multiple uses of scalars."); 6976 if (Res1.second) 6977 Mask[I] = I; 6978 } else if (SecMask[I] != UndefMaskElem) { 6979 assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars."); 6980 Mask[I] = (Res2.second ? I : SecMask[I]) + VF; 6981 } 6982 } 6983 Prev = Action(Mask, {Res1.first, Res2.first}); 6984 } 6985 VMIt = std::next(VMIt); 6986 } 6987 // Perform requested actions for the remaining masks/vectors. 6988 for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) { 6989 // Shuffle other input vectors, if any. 6990 std::pair<T *, bool> Res = ResizeAction(VMIt->first, VMIt->second); 6991 ArrayRef<int> SecMask = VMIt->second; 6992 for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) { 6993 if (SecMask[I] != UndefMaskElem) { 6994 assert((Mask[I] == UndefMaskElem || IsBaseNotUndef) && 6995 "Multiple uses of scalars."); 6996 Mask[I] = (Res.second ? I : SecMask[I]) + VF; 6997 } else if (Mask[I] != UndefMaskElem) { 6998 Mask[I] = I; 6999 } 7000 } 7001 Prev = Action(Mask, {Prev, Res.first}); 7002 } 7003 return Prev; 7004 } 7005 7006 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) { 7007 InstructionCost Cost = 0; 7008 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size " 7009 << VectorizableTree.size() << ".\n"); 7010 7011 unsigned BundleWidth = VectorizableTree[0]->Scalars.size(); 7012 7013 for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) { 7014 TreeEntry &TE = *VectorizableTree[I]; 7015 7016 InstructionCost C = getEntryCost(&TE, VectorizedVals); 7017 Cost += C; 7018 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 7019 << " for bundle that starts with " << *TE.Scalars[0] 7020 << ".\n" 7021 << "SLP: Current total cost = " << Cost << "\n"); 7022 } 7023 7024 SmallPtrSet<Value *, 16> ExtractCostCalculated; 7025 InstructionCost ExtractCost = 0; 7026 SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks; 7027 SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers; 7028 SmallVector<APInt> DemandedElts; 7029 for (ExternalUser &EU : ExternalUses) { 7030 // We only add extract cost once for the same scalar. 7031 if (!isa_and_nonnull<InsertElementInst>(EU.User) && 7032 !ExtractCostCalculated.insert(EU.Scalar).second) 7033 continue; 7034 7035 // Uses by ephemeral values are free (because the ephemeral value will be 7036 // removed prior to code generation, and so the extraction will be 7037 // removed as well). 7038 if (EphValues.count(EU.User)) 7039 continue; 7040 7041 // No extract cost for vector "scalar" 7042 if (isa<FixedVectorType>(EU.Scalar->getType())) 7043 continue; 7044 7045 // Already counted the cost for external uses when tried to adjust the cost 7046 // for extractelements, no need to add it again. 7047 if (isa<ExtractElementInst>(EU.Scalar)) 7048 continue; 7049 7050 // If found user is an insertelement, do not calculate extract cost but try 7051 // to detect it as a final shuffled/identity match. 7052 if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) { 7053 if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) { 7054 Optional<unsigned> InsertIdx = getInsertIndex(VU); 7055 if (InsertIdx) { 7056 const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar); 7057 auto *It = 7058 find_if(FirstUsers, 7059 [VU](const std::pair<Value *, const TreeEntry *> &Pair) { 7060 return areTwoInsertFromSameBuildVector( 7061 VU, cast<InsertElementInst>(Pair.first)); 7062 }); 7063 int VecId = -1; 7064 if (It == FirstUsers.end()) { 7065 (void)ShuffleMasks.emplace_back(); 7066 SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE]; 7067 if (Mask.empty()) 7068 Mask.assign(FTy->getNumElements(), UndefMaskElem); 7069 // Find the insertvector, vectorized in tree, if any. 7070 Value *Base = VU; 7071 while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) { 7072 if (IEBase != EU.User && 7073 (!IEBase->hasOneUse() || 7074 getInsertIndex(IEBase).value_or(*InsertIdx) == *InsertIdx)) 7075 break; 7076 // Build the mask for the vectorized insertelement instructions. 7077 if (const TreeEntry *E = getTreeEntry(IEBase)) { 7078 VU = IEBase; 7079 do { 7080 IEBase = cast<InsertElementInst>(Base); 7081 int Idx = *getInsertIndex(IEBase); 7082 assert(Mask[Idx] == UndefMaskElem && 7083 "InsertElementInstruction used already."); 7084 Mask[Idx] = Idx; 7085 Base = IEBase->getOperand(0); 7086 } while (E == getTreeEntry(Base)); 7087 break; 7088 } 7089 Base = cast<InsertElementInst>(Base)->getOperand(0); 7090 } 7091 FirstUsers.emplace_back(VU, ScalarTE); 7092 DemandedElts.push_back(APInt::getZero(FTy->getNumElements())); 7093 VecId = FirstUsers.size() - 1; 7094 } else { 7095 if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first))) 7096 It->first = VU; 7097 VecId = std::distance(FirstUsers.begin(), It); 7098 } 7099 int InIdx = *InsertIdx; 7100 SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE]; 7101 if (Mask.empty()) 7102 Mask.assign(FTy->getNumElements(), UndefMaskElem); 7103 Mask[InIdx] = EU.Lane; 7104 DemandedElts[VecId].setBit(InIdx); 7105 continue; 7106 } 7107 } 7108 } 7109 7110 // If we plan to rewrite the tree in a smaller type, we will need to sign 7111 // extend the extracted value back to the original type. Here, we account 7112 // for the extract and the added cost of the sign extend if needed. 7113 auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth); 7114 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 7115 if (MinBWs.count(ScalarRoot)) { 7116 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 7117 auto Extend = 7118 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt; 7119 VecTy = FixedVectorType::get(MinTy, BundleWidth); 7120 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(), 7121 VecTy, EU.Lane); 7122 } else { 7123 ExtractCost += 7124 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane); 7125 } 7126 } 7127 7128 InstructionCost SpillCost = getSpillCost(); 7129 Cost += SpillCost + ExtractCost; 7130 auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask) { 7131 InstructionCost C = 0; 7132 unsigned VF = Mask.size(); 7133 unsigned VecVF = TE->getVectorFactor(); 7134 if (VF != VecVF && 7135 (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) || 7136 (all_of(Mask, 7137 [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) && 7138 !ShuffleVectorInst::isIdentityMask(Mask)))) { 7139 SmallVector<int> OrigMask(VecVF, UndefMaskElem); 7140 std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)), 7141 OrigMask.begin()); 7142 C = TTI->getShuffleCost( 7143 TTI::SK_PermuteSingleSrc, 7144 FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask); 7145 LLVM_DEBUG( 7146 dbgs() << "SLP: Adding cost " << C 7147 << " for final shuffle of insertelement external users.\n"; 7148 TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"); 7149 Cost += C; 7150 return std::make_pair(TE, true); 7151 } 7152 return std::make_pair(TE, false); 7153 }; 7154 // Calculate the cost of the reshuffled vectors, if any. 7155 for (int I = 0, E = FirstUsers.size(); I < E; ++I) { 7156 Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0); 7157 unsigned VF = ShuffleMasks[I].begin()->second.size(); 7158 auto *FTy = FixedVectorType::get( 7159 cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF); 7160 auto Vector = ShuffleMasks[I].takeVector(); 7161 auto &&EstimateShufflesCost = [this, FTy, 7162 &Cost](ArrayRef<int> Mask, 7163 ArrayRef<const TreeEntry *> TEs) { 7164 assert((TEs.size() == 1 || TEs.size() == 2) && 7165 "Expected exactly 1 or 2 tree entries."); 7166 if (TEs.size() == 1) { 7167 int Limit = 2 * Mask.size(); 7168 if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) || 7169 !ShuffleVectorInst::isIdentityMask(Mask)) { 7170 InstructionCost C = 7171 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask); 7172 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 7173 << " for final shuffle of insertelement " 7174 "external users.\n"; 7175 TEs.front()->dump(); 7176 dbgs() << "SLP: Current total cost = " << Cost << "\n"); 7177 Cost += C; 7178 } 7179 } else { 7180 InstructionCost C = 7181 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask); 7182 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 7183 << " for final shuffle of vector node and external " 7184 "insertelement users.\n"; 7185 if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump(); 7186 dbgs() << "SLP: Current total cost = " << Cost << "\n"); 7187 Cost += C; 7188 } 7189 return TEs.back(); 7190 }; 7191 (void)performExtractsShuffleAction<const TreeEntry>( 7192 makeMutableArrayRef(Vector.data(), Vector.size()), Base, 7193 [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF, 7194 EstimateShufflesCost); 7195 InstructionCost InsertCost = TTI->getScalarizationOverhead( 7196 cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I], 7197 /*Insert*/ true, /*Extract*/ false); 7198 Cost -= InsertCost; 7199 } 7200 7201 #ifndef NDEBUG 7202 SmallString<256> Str; 7203 { 7204 raw_svector_ostream OS(Str); 7205 OS << "SLP: Spill Cost = " << SpillCost << ".\n" 7206 << "SLP: Extract Cost = " << ExtractCost << ".\n" 7207 << "SLP: Total Cost = " << Cost << ".\n"; 7208 } 7209 LLVM_DEBUG(dbgs() << Str); 7210 if (ViewSLPTree) 7211 ViewGraph(this, "SLP" + F->getName(), false, Str); 7212 #endif 7213 7214 return Cost; 7215 } 7216 7217 Optional<TargetTransformInfo::ShuffleKind> 7218 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 7219 SmallVectorImpl<const TreeEntry *> &Entries) { 7220 // TODO: currently checking only for Scalars in the tree entry, need to count 7221 // reused elements too for better cost estimation. 7222 Mask.assign(TE->Scalars.size(), UndefMaskElem); 7223 Entries.clear(); 7224 // Build a lists of values to tree entries. 7225 DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs; 7226 for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) { 7227 if (EntryPtr.get() == TE) 7228 break; 7229 if (EntryPtr->State != TreeEntry::NeedToGather) 7230 continue; 7231 for (Value *V : EntryPtr->Scalars) 7232 ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get()); 7233 } 7234 // Find all tree entries used by the gathered values. If no common entries 7235 // found - not a shuffle. 7236 // Here we build a set of tree nodes for each gathered value and trying to 7237 // find the intersection between these sets. If we have at least one common 7238 // tree node for each gathered value - we have just a permutation of the 7239 // single vector. If we have 2 different sets, we're in situation where we 7240 // have a permutation of 2 input vectors. 7241 SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs; 7242 DenseMap<Value *, int> UsedValuesEntry; 7243 for (Value *V : TE->Scalars) { 7244 if (isa<UndefValue>(V)) 7245 continue; 7246 // Build a list of tree entries where V is used. 7247 SmallPtrSet<const TreeEntry *, 4> VToTEs; 7248 auto It = ValueToTEs.find(V); 7249 if (It != ValueToTEs.end()) 7250 VToTEs = It->second; 7251 if (const TreeEntry *VTE = getTreeEntry(V)) 7252 VToTEs.insert(VTE); 7253 if (VToTEs.empty()) 7254 return None; 7255 if (UsedTEs.empty()) { 7256 // The first iteration, just insert the list of nodes to vector. 7257 UsedTEs.push_back(VToTEs); 7258 } else { 7259 // Need to check if there are any previously used tree nodes which use V. 7260 // If there are no such nodes, consider that we have another one input 7261 // vector. 7262 SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs); 7263 unsigned Idx = 0; 7264 for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) { 7265 // Do we have a non-empty intersection of previously listed tree entries 7266 // and tree entries using current V? 7267 set_intersect(VToTEs, Set); 7268 if (!VToTEs.empty()) { 7269 // Yes, write the new subset and continue analysis for the next 7270 // scalar. 7271 Set.swap(VToTEs); 7272 break; 7273 } 7274 VToTEs = SavedVToTEs; 7275 ++Idx; 7276 } 7277 // No non-empty intersection found - need to add a second set of possible 7278 // source vectors. 7279 if (Idx == UsedTEs.size()) { 7280 // If the number of input vectors is greater than 2 - not a permutation, 7281 // fallback to the regular gather. 7282 if (UsedTEs.size() == 2) 7283 return None; 7284 UsedTEs.push_back(SavedVToTEs); 7285 Idx = UsedTEs.size() - 1; 7286 } 7287 UsedValuesEntry.try_emplace(V, Idx); 7288 } 7289 } 7290 7291 if (UsedTEs.empty()) { 7292 assert(all_of(TE->Scalars, UndefValue::classof) && 7293 "Expected vector of undefs only."); 7294 return None; 7295 } 7296 7297 unsigned VF = 0; 7298 if (UsedTEs.size() == 1) { 7299 // Try to find the perfect match in another gather node at first. 7300 auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) { 7301 return EntryPtr->isSame(TE->Scalars); 7302 }); 7303 if (It != UsedTEs.front().end()) { 7304 Entries.push_back(*It); 7305 std::iota(Mask.begin(), Mask.end(), 0); 7306 return TargetTransformInfo::SK_PermuteSingleSrc; 7307 } 7308 // No perfect match, just shuffle, so choose the first tree node. 7309 Entries.push_back(*UsedTEs.front().begin()); 7310 } else { 7311 // Try to find nodes with the same vector factor. 7312 assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries."); 7313 DenseMap<int, const TreeEntry *> VFToTE; 7314 for (const TreeEntry *TE : UsedTEs.front()) 7315 VFToTE.try_emplace(TE->getVectorFactor(), TE); 7316 for (const TreeEntry *TE : UsedTEs.back()) { 7317 auto It = VFToTE.find(TE->getVectorFactor()); 7318 if (It != VFToTE.end()) { 7319 VF = It->first; 7320 Entries.push_back(It->second); 7321 Entries.push_back(TE); 7322 break; 7323 } 7324 } 7325 // No 2 source vectors with the same vector factor - give up and do regular 7326 // gather. 7327 if (Entries.empty()) 7328 return None; 7329 } 7330 7331 // Build a shuffle mask for better cost estimation and vector emission. 7332 for (int I = 0, E = TE->Scalars.size(); I < E; ++I) { 7333 Value *V = TE->Scalars[I]; 7334 if (isa<UndefValue>(V)) 7335 continue; 7336 unsigned Idx = UsedValuesEntry.lookup(V); 7337 const TreeEntry *VTE = Entries[Idx]; 7338 int FoundLane = VTE->findLaneForValue(V); 7339 Mask[I] = Idx * VF + FoundLane; 7340 // Extra check required by isSingleSourceMaskImpl function (called by 7341 // ShuffleVectorInst::isSingleSourceMask). 7342 if (Mask[I] >= 2 * E) 7343 return None; 7344 } 7345 switch (Entries.size()) { 7346 case 1: 7347 return TargetTransformInfo::SK_PermuteSingleSrc; 7348 case 2: 7349 return TargetTransformInfo::SK_PermuteTwoSrc; 7350 default: 7351 break; 7352 } 7353 return None; 7354 } 7355 7356 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty, 7357 const APInt &ShuffledIndices, 7358 bool NeedToShuffle) const { 7359 InstructionCost Cost = 7360 TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true, 7361 /*Extract*/ false); 7362 if (NeedToShuffle) 7363 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty); 7364 return Cost; 7365 } 7366 7367 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const { 7368 // Find the type of the operands in VL. 7369 Type *ScalarTy = VL[0]->getType(); 7370 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 7371 ScalarTy = SI->getValueOperand()->getType(); 7372 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 7373 bool DuplicateNonConst = false; 7374 // Find the cost of inserting/extracting values from the vector. 7375 // Check if the same elements are inserted several times and count them as 7376 // shuffle candidates. 7377 APInt ShuffledElements = APInt::getZero(VL.size()); 7378 DenseSet<Value *> UniqueElements; 7379 // Iterate in reverse order to consider insert elements with the high cost. 7380 for (unsigned I = VL.size(); I > 0; --I) { 7381 unsigned Idx = I - 1; 7382 // No need to shuffle duplicates for constants. 7383 if (isConstant(VL[Idx])) { 7384 ShuffledElements.setBit(Idx); 7385 continue; 7386 } 7387 if (!UniqueElements.insert(VL[Idx]).second) { 7388 DuplicateNonConst = true; 7389 ShuffledElements.setBit(Idx); 7390 } 7391 } 7392 return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst); 7393 } 7394 7395 // Perform operand reordering on the instructions in VL and return the reordered 7396 // operands in Left and Right. 7397 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 7398 SmallVectorImpl<Value *> &Left, 7399 SmallVectorImpl<Value *> &Right, 7400 const DataLayout &DL, 7401 ScalarEvolution &SE, 7402 const BoUpSLP &R) { 7403 if (VL.empty()) 7404 return; 7405 VLOperands Ops(VL, DL, SE, R); 7406 // Reorder the operands in place. 7407 Ops.reorder(); 7408 Left = Ops.getVL(0); 7409 Right = Ops.getVL(1); 7410 } 7411 7412 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) { 7413 // Get the basic block this bundle is in. All instructions in the bundle 7414 // should be in this block (except for extractelement-like instructions with 7415 // constant indeces). 7416 auto *Front = E->getMainOp(); 7417 auto *BB = Front->getParent(); 7418 assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool { 7419 if (E->getOpcode() == Instruction::GetElementPtr && 7420 !isa<GetElementPtrInst>(V)) 7421 return true; 7422 auto *I = cast<Instruction>(V); 7423 return !E->isOpcodeOrAlt(I) || I->getParent() == BB || 7424 isVectorLikeInstWithConstOps(I); 7425 })); 7426 7427 auto &&FindLastInst = [E, Front, this, &BB]() { 7428 Instruction *LastInst = Front; 7429 for (Value *V : E->Scalars) { 7430 auto *I = dyn_cast<Instruction>(V); 7431 if (!I) 7432 continue; 7433 if (LastInst->getParent() == I->getParent()) { 7434 if (LastInst->comesBefore(I)) 7435 LastInst = I; 7436 continue; 7437 } 7438 assert(isVectorLikeInstWithConstOps(LastInst) && 7439 isVectorLikeInstWithConstOps(I) && 7440 "Expected vector-like insts only."); 7441 if (!DT->isReachableFromEntry(LastInst->getParent())) { 7442 LastInst = I; 7443 continue; 7444 } 7445 if (!DT->isReachableFromEntry(I->getParent())) 7446 continue; 7447 auto *NodeA = DT->getNode(LastInst->getParent()); 7448 auto *NodeB = DT->getNode(I->getParent()); 7449 assert(NodeA && "Should only process reachable instructions"); 7450 assert(NodeB && "Should only process reachable instructions"); 7451 assert((NodeA == NodeB) == 7452 (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && 7453 "Different nodes should have different DFS numbers"); 7454 if (NodeA->getDFSNumIn() < NodeB->getDFSNumIn()) 7455 LastInst = I; 7456 } 7457 BB = LastInst->getParent(); 7458 return LastInst; 7459 }; 7460 7461 auto &&FindFirstInst = [E, Front]() { 7462 Instruction *FirstInst = Front; 7463 for (Value *V : E->Scalars) { 7464 auto *I = dyn_cast<Instruction>(V); 7465 if (!I) 7466 continue; 7467 if (I->comesBefore(FirstInst)) 7468 FirstInst = I; 7469 } 7470 return FirstInst; 7471 }; 7472 7473 // Set the insert point to the beginning of the basic block if the entry 7474 // should not be scheduled. 7475 if (E->State != TreeEntry::NeedToGather && 7476 doesNotNeedToSchedule(E->Scalars)) { 7477 Instruction *InsertInst; 7478 if (all_of(E->Scalars, isUsedOutsideBlock)) 7479 InsertInst = FindLastInst(); 7480 else 7481 InsertInst = FindFirstInst(); 7482 // If the instruction is PHI, set the insert point after all the PHIs. 7483 if (isa<PHINode>(InsertInst)) 7484 InsertInst = BB->getFirstNonPHI(); 7485 BasicBlock::iterator InsertPt = InsertInst->getIterator(); 7486 Builder.SetInsertPoint(BB, InsertPt); 7487 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 7488 return; 7489 } 7490 7491 // The last instruction in the bundle in program order. 7492 Instruction *LastInst = nullptr; 7493 7494 // Find the last instruction. The common case should be that BB has been 7495 // scheduled, and the last instruction is VL.back(). So we start with 7496 // VL.back() and iterate over schedule data until we reach the end of the 7497 // bundle. The end of the bundle is marked by null ScheduleData. 7498 if (BlocksSchedules.count(BB)) { 7499 Value *V = E->isOneOf(E->Scalars.back()); 7500 if (doesNotNeedToBeScheduled(V)) 7501 V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled); 7502 auto *Bundle = BlocksSchedules[BB]->getScheduleData(V); 7503 if (Bundle && Bundle->isPartOfBundle()) 7504 for (; Bundle; Bundle = Bundle->NextInBundle) 7505 if (Bundle->OpValue == Bundle->Inst) 7506 LastInst = Bundle->Inst; 7507 } 7508 7509 // LastInst can still be null at this point if there's either not an entry 7510 // for BB in BlocksSchedules or there's no ScheduleData available for 7511 // VL.back(). This can be the case if buildTree_rec aborts for various 7512 // reasons (e.g., the maximum recursion depth is reached, the maximum region 7513 // size is reached, etc.). ScheduleData is initialized in the scheduling 7514 // "dry-run". 7515 // 7516 // If this happens, we can still find the last instruction by brute force. We 7517 // iterate forwards from Front (inclusive) until we either see all 7518 // instructions in the bundle or reach the end of the block. If Front is the 7519 // last instruction in program order, LastInst will be set to Front, and we 7520 // will visit all the remaining instructions in the block. 7521 // 7522 // One of the reasons we exit early from buildTree_rec is to place an upper 7523 // bound on compile-time. Thus, taking an additional compile-time hit here is 7524 // not ideal. However, this should be exceedingly rare since it requires that 7525 // we both exit early from buildTree_rec and that the bundle be out-of-order 7526 // (causing us to iterate all the way to the end of the block). 7527 if (!LastInst) { 7528 LastInst = FindLastInst(); 7529 // If the instruction is PHI, set the insert point after all the PHIs. 7530 if (isa<PHINode>(LastInst)) 7531 LastInst = BB->getFirstNonPHI()->getPrevNode(); 7532 } 7533 assert(LastInst && "Failed to find last instruction in bundle"); 7534 7535 // Set the insertion point after the last instruction in the bundle. Set the 7536 // debug location to Front. 7537 Builder.SetInsertPoint(BB, std::next(LastInst->getIterator())); 7538 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 7539 } 7540 7541 Value *BoUpSLP::gather(ArrayRef<Value *> VL) { 7542 // List of instructions/lanes from current block and/or the blocks which are 7543 // part of the current loop. These instructions will be inserted at the end to 7544 // make it possible to optimize loops and hoist invariant instructions out of 7545 // the loops body with better chances for success. 7546 SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts; 7547 SmallSet<int, 4> PostponedIndices; 7548 Loop *L = LI->getLoopFor(Builder.GetInsertBlock()); 7549 auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) { 7550 SmallPtrSet<BasicBlock *, 4> Visited; 7551 while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second) 7552 InsertBB = InsertBB->getSinglePredecessor(); 7553 return InsertBB && InsertBB == InstBB; 7554 }; 7555 for (int I = 0, E = VL.size(); I < E; ++I) { 7556 if (auto *Inst = dyn_cast<Instruction>(VL[I])) 7557 if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) || 7558 getTreeEntry(Inst) || (L && (L->contains(Inst)))) && 7559 PostponedIndices.insert(I).second) 7560 PostponedInsts.emplace_back(Inst, I); 7561 } 7562 7563 auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) { 7564 Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos)); 7565 auto *InsElt = dyn_cast<InsertElementInst>(Vec); 7566 if (!InsElt) 7567 return Vec; 7568 GatherShuffleSeq.insert(InsElt); 7569 CSEBlocks.insert(InsElt->getParent()); 7570 // Add to our 'need-to-extract' list. 7571 if (TreeEntry *Entry = getTreeEntry(V)) { 7572 // Find which lane we need to extract. 7573 unsigned FoundLane = Entry->findLaneForValue(V); 7574 ExternalUses.emplace_back(V, InsElt, FoundLane); 7575 } 7576 return Vec; 7577 }; 7578 Value *Val0 = 7579 isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0]; 7580 FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size()); 7581 Value *Vec = PoisonValue::get(VecTy); 7582 SmallVector<int> NonConsts; 7583 // Insert constant values at first. 7584 for (int I = 0, E = VL.size(); I < E; ++I) { 7585 if (PostponedIndices.contains(I)) 7586 continue; 7587 if (!isConstant(VL[I])) { 7588 NonConsts.push_back(I); 7589 continue; 7590 } 7591 Vec = CreateInsertElement(Vec, VL[I], I); 7592 } 7593 // Insert non-constant values. 7594 for (int I : NonConsts) 7595 Vec = CreateInsertElement(Vec, VL[I], I); 7596 // Append instructions, which are/may be part of the loop, in the end to make 7597 // it possible to hoist non-loop-based instructions. 7598 for (const std::pair<Value *, unsigned> &Pair : PostponedInsts) 7599 Vec = CreateInsertElement(Vec, Pair.first, Pair.second); 7600 7601 return Vec; 7602 } 7603 7604 namespace { 7605 /// Merges shuffle masks and emits final shuffle instruction, if required. 7606 class ShuffleInstructionBuilder { 7607 IRBuilderBase &Builder; 7608 const unsigned VF = 0; 7609 bool IsFinalized = false; 7610 SmallVector<int, 4> Mask; 7611 /// Holds all of the instructions that we gathered. 7612 SetVector<Instruction *> &GatherShuffleSeq; 7613 /// A list of blocks that we are going to CSE. 7614 SetVector<BasicBlock *> &CSEBlocks; 7615 7616 public: 7617 ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF, 7618 SetVector<Instruction *> &GatherShuffleSeq, 7619 SetVector<BasicBlock *> &CSEBlocks) 7620 : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq), 7621 CSEBlocks(CSEBlocks) {} 7622 7623 /// Adds a mask, inverting it before applying. 7624 void addInversedMask(ArrayRef<unsigned> SubMask) { 7625 if (SubMask.empty()) 7626 return; 7627 SmallVector<int, 4> NewMask; 7628 inversePermutation(SubMask, NewMask); 7629 addMask(NewMask); 7630 } 7631 7632 /// Functions adds masks, merging them into single one. 7633 void addMask(ArrayRef<unsigned> SubMask) { 7634 SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end()); 7635 addMask(NewMask); 7636 } 7637 7638 void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); } 7639 7640 Value *finalize(Value *V) { 7641 IsFinalized = true; 7642 unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements(); 7643 if (VF == ValueVF && Mask.empty()) 7644 return V; 7645 SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem); 7646 std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0); 7647 addMask(NormalizedMask); 7648 7649 if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask)) 7650 return V; 7651 Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle"); 7652 if (auto *I = dyn_cast<Instruction>(Vec)) { 7653 GatherShuffleSeq.insert(I); 7654 CSEBlocks.insert(I->getParent()); 7655 } 7656 return Vec; 7657 } 7658 7659 ~ShuffleInstructionBuilder() { 7660 assert((IsFinalized || Mask.empty()) && 7661 "Shuffle construction must be finalized."); 7662 } 7663 }; 7664 } // namespace 7665 7666 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { 7667 const unsigned VF = VL.size(); 7668 InstructionsState S = getSameOpcode(VL); 7669 // Special processing for GEPs bundle, which may include non-gep values. 7670 if (!S.getOpcode() && VL.front()->getType()->isPointerTy()) { 7671 const auto *It = 7672 find_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }); 7673 if (It != VL.end()) 7674 S = getSameOpcode(*It); 7675 } 7676 if (S.getOpcode()) { 7677 if (TreeEntry *E = getTreeEntry(S.OpValue)) 7678 if (E->isSame(VL)) { 7679 Value *V = vectorizeTree(E); 7680 if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) { 7681 if (!E->ReuseShuffleIndices.empty()) { 7682 // Reshuffle to get only unique values. 7683 // If some of the scalars are duplicated in the vectorization tree 7684 // entry, we do not vectorize them but instead generate a mask for 7685 // the reuses. But if there are several users of the same entry, 7686 // they may have different vectorization factors. This is especially 7687 // important for PHI nodes. In this case, we need to adapt the 7688 // resulting instruction for the user vectorization factor and have 7689 // to reshuffle it again to take only unique elements of the vector. 7690 // Without this code the function incorrectly returns reduced vector 7691 // instruction with the same elements, not with the unique ones. 7692 7693 // block: 7694 // %phi = phi <2 x > { .., %entry} {%shuffle, %block} 7695 // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0> 7696 // ... (use %2) 7697 // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0} 7698 // br %block 7699 SmallVector<int> UniqueIdxs(VF, UndefMaskElem); 7700 SmallSet<int, 4> UsedIdxs; 7701 int Pos = 0; 7702 int Sz = VL.size(); 7703 for (int Idx : E->ReuseShuffleIndices) { 7704 if (Idx != Sz && Idx != UndefMaskElem && 7705 UsedIdxs.insert(Idx).second) 7706 UniqueIdxs[Idx] = Pos; 7707 ++Pos; 7708 } 7709 assert(VF >= UsedIdxs.size() && "Expected vectorization factor " 7710 "less than original vector size."); 7711 UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem); 7712 V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle"); 7713 } else { 7714 assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() && 7715 "Expected vectorization factor less " 7716 "than original vector size."); 7717 SmallVector<int> UniformMask(VF, 0); 7718 std::iota(UniformMask.begin(), UniformMask.end(), 0); 7719 V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle"); 7720 } 7721 if (auto *I = dyn_cast<Instruction>(V)) { 7722 GatherShuffleSeq.insert(I); 7723 CSEBlocks.insert(I->getParent()); 7724 } 7725 } 7726 return V; 7727 } 7728 } 7729 7730 // Can't vectorize this, so simply build a new vector with each lane 7731 // corresponding to the requested value. 7732 return createBuildVector(VL); 7733 } 7734 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) { 7735 unsigned VF = VL.size(); 7736 // Exploit possible reuse of values across lanes. 7737 SmallVector<int> ReuseShuffleIndicies; 7738 SmallVector<Value *> UniqueValues; 7739 if (VL.size() > 2) { 7740 DenseMap<Value *, unsigned> UniquePositions; 7741 unsigned NumValues = 7742 std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) { 7743 return !isa<UndefValue>(V); 7744 }).base()); 7745 VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues)); 7746 int UniqueVals = 0; 7747 for (Value *V : VL.drop_back(VL.size() - VF)) { 7748 if (isa<UndefValue>(V)) { 7749 ReuseShuffleIndicies.emplace_back(UndefMaskElem); 7750 continue; 7751 } 7752 if (isConstant(V)) { 7753 ReuseShuffleIndicies.emplace_back(UniqueValues.size()); 7754 UniqueValues.emplace_back(V); 7755 continue; 7756 } 7757 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 7758 ReuseShuffleIndicies.emplace_back(Res.first->second); 7759 if (Res.second) { 7760 UniqueValues.emplace_back(V); 7761 ++UniqueVals; 7762 } 7763 } 7764 if (UniqueVals == 1 && UniqueValues.size() == 1) { 7765 // Emit pure splat vector. 7766 ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(), 7767 UndefMaskElem); 7768 } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) { 7769 if (UniqueValues.empty()) { 7770 assert(all_of(VL, UndefValue::classof) && "Expected list of undefs."); 7771 NumValues = VF; 7772 } 7773 ReuseShuffleIndicies.clear(); 7774 UniqueValues.clear(); 7775 UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues)); 7776 } 7777 UniqueValues.append(VF - UniqueValues.size(), 7778 PoisonValue::get(VL[0]->getType())); 7779 VL = UniqueValues; 7780 } 7781 7782 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 7783 CSEBlocks); 7784 Value *Vec = gather(VL); 7785 if (!ReuseShuffleIndicies.empty()) { 7786 ShuffleBuilder.addMask(ReuseShuffleIndicies); 7787 Vec = ShuffleBuilder.finalize(Vec); 7788 } 7789 return Vec; 7790 } 7791 7792 Value *BoUpSLP::vectorizeTree(TreeEntry *E) { 7793 IRBuilder<>::InsertPointGuard Guard(Builder); 7794 7795 if (E->VectorizedValue) { 7796 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"); 7797 return E->VectorizedValue; 7798 } 7799 7800 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 7801 unsigned VF = E->getVectorFactor(); 7802 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 7803 CSEBlocks); 7804 if (E->State == TreeEntry::NeedToGather) { 7805 if (E->getMainOp()) 7806 setInsertPointAfterBundle(E); 7807 Value *Vec; 7808 SmallVector<int> Mask; 7809 SmallVector<const TreeEntry *> Entries; 7810 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 7811 isGatherShuffledEntry(E, Mask, Entries); 7812 if (Shuffle) { 7813 assert((Entries.size() == 1 || Entries.size() == 2) && 7814 "Expected shuffle of 1 or 2 entries."); 7815 Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue, 7816 Entries.back()->VectorizedValue, Mask); 7817 if (auto *I = dyn_cast<Instruction>(Vec)) { 7818 GatherShuffleSeq.insert(I); 7819 CSEBlocks.insert(I->getParent()); 7820 } 7821 } else { 7822 Vec = gather(E->Scalars); 7823 } 7824 if (NeedToShuffleReuses) { 7825 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7826 Vec = ShuffleBuilder.finalize(Vec); 7827 } 7828 E->VectorizedValue = Vec; 7829 return Vec; 7830 } 7831 7832 assert((E->State == TreeEntry::Vectorize || 7833 E->State == TreeEntry::ScatterVectorize) && 7834 "Unhandled state"); 7835 unsigned ShuffleOrOp = 7836 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 7837 Instruction *VL0 = E->getMainOp(); 7838 Type *ScalarTy = VL0->getType(); 7839 if (auto *Store = dyn_cast<StoreInst>(VL0)) 7840 ScalarTy = Store->getValueOperand()->getType(); 7841 else if (auto *IE = dyn_cast<InsertElementInst>(VL0)) 7842 ScalarTy = IE->getOperand(1)->getType(); 7843 auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size()); 7844 switch (ShuffleOrOp) { 7845 case Instruction::PHI: { 7846 assert( 7847 (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) && 7848 "PHI reordering is free."); 7849 auto *PH = cast<PHINode>(VL0); 7850 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI()); 7851 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 7852 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); 7853 Value *V = NewPhi; 7854 7855 // Adjust insertion point once all PHI's have been generated. 7856 Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt()); 7857 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 7858 7859 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7860 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7861 V = ShuffleBuilder.finalize(V); 7862 7863 E->VectorizedValue = V; 7864 7865 // PHINodes may have multiple entries from the same block. We want to 7866 // visit every block once. 7867 SmallPtrSet<BasicBlock*, 4> VisitedBBs; 7868 7869 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 7870 ValueList Operands; 7871 BasicBlock *IBB = PH->getIncomingBlock(i); 7872 7873 if (!VisitedBBs.insert(IBB).second) { 7874 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB); 7875 continue; 7876 } 7877 7878 Builder.SetInsertPoint(IBB->getTerminator()); 7879 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 7880 Value *Vec = vectorizeTree(E->getOperand(i)); 7881 NewPhi->addIncoming(Vec, IBB); 7882 } 7883 7884 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && 7885 "Invalid number of incoming values"); 7886 return V; 7887 } 7888 7889 case Instruction::ExtractElement: { 7890 Value *V = E->getSingleOperand(0); 7891 Builder.SetInsertPoint(VL0); 7892 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7893 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7894 V = ShuffleBuilder.finalize(V); 7895 E->VectorizedValue = V; 7896 return V; 7897 } 7898 case Instruction::ExtractValue: { 7899 auto *LI = cast<LoadInst>(E->getSingleOperand(0)); 7900 Builder.SetInsertPoint(LI); 7901 auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace()); 7902 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy); 7903 LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign()); 7904 Value *NewV = propagateMetadata(V, E->Scalars); 7905 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7906 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7907 NewV = ShuffleBuilder.finalize(NewV); 7908 E->VectorizedValue = NewV; 7909 return NewV; 7910 } 7911 case Instruction::InsertElement: { 7912 assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique"); 7913 Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back())); 7914 Value *V = vectorizeTree(E->getOperand(1)); 7915 7916 // Create InsertVector shuffle if necessary 7917 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 7918 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); 7919 })); 7920 const unsigned NumElts = 7921 cast<FixedVectorType>(FirstInsert->getType())->getNumElements(); 7922 const unsigned NumScalars = E->Scalars.size(); 7923 7924 unsigned Offset = *getInsertIndex(VL0); 7925 assert(Offset < NumElts && "Failed to find vector index offset"); 7926 7927 // Create shuffle to resize vector 7928 SmallVector<int> Mask; 7929 if (!E->ReorderIndices.empty()) { 7930 inversePermutation(E->ReorderIndices, Mask); 7931 Mask.append(NumElts - NumScalars, UndefMaskElem); 7932 } else { 7933 Mask.assign(NumElts, UndefMaskElem); 7934 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 7935 } 7936 // Create InsertVector shuffle if necessary 7937 bool IsIdentity = true; 7938 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 7939 Mask.swap(PrevMask); 7940 for (unsigned I = 0; I < NumScalars; ++I) { 7941 Value *Scalar = E->Scalars[PrevMask[I]]; 7942 unsigned InsertIdx = *getInsertIndex(Scalar); 7943 IsIdentity &= InsertIdx - Offset == I; 7944 Mask[InsertIdx - Offset] = I; 7945 } 7946 if (!IsIdentity || NumElts != NumScalars) { 7947 V = Builder.CreateShuffleVector(V, Mask); 7948 if (auto *I = dyn_cast<Instruction>(V)) { 7949 GatherShuffleSeq.insert(I); 7950 CSEBlocks.insert(I->getParent()); 7951 } 7952 } 7953 7954 if ((!IsIdentity || Offset != 0 || 7955 !isUndefVector(FirstInsert->getOperand(0))) && 7956 NumElts != NumScalars) { 7957 SmallVector<int> InsertMask(NumElts); 7958 std::iota(InsertMask.begin(), InsertMask.end(), 0); 7959 for (unsigned I = 0; I < NumElts; I++) { 7960 if (Mask[I] != UndefMaskElem) 7961 InsertMask[Offset + I] = NumElts + I; 7962 } 7963 7964 V = Builder.CreateShuffleVector( 7965 FirstInsert->getOperand(0), V, InsertMask, 7966 cast<Instruction>(E->Scalars.back())->getName()); 7967 if (auto *I = dyn_cast<Instruction>(V)) { 7968 GatherShuffleSeq.insert(I); 7969 CSEBlocks.insert(I->getParent()); 7970 } 7971 } 7972 7973 ++NumVectorInstructions; 7974 E->VectorizedValue = V; 7975 return V; 7976 } 7977 case Instruction::ZExt: 7978 case Instruction::SExt: 7979 case Instruction::FPToUI: 7980 case Instruction::FPToSI: 7981 case Instruction::FPExt: 7982 case Instruction::PtrToInt: 7983 case Instruction::IntToPtr: 7984 case Instruction::SIToFP: 7985 case Instruction::UIToFP: 7986 case Instruction::Trunc: 7987 case Instruction::FPTrunc: 7988 case Instruction::BitCast: { 7989 setInsertPointAfterBundle(E); 7990 7991 Value *InVec = vectorizeTree(E->getOperand(0)); 7992 7993 if (E->VectorizedValue) { 7994 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7995 return E->VectorizedValue; 7996 } 7997 7998 auto *CI = cast<CastInst>(VL0); 7999 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); 8000 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8001 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8002 V = ShuffleBuilder.finalize(V); 8003 8004 E->VectorizedValue = V; 8005 ++NumVectorInstructions; 8006 return V; 8007 } 8008 case Instruction::FCmp: 8009 case Instruction::ICmp: { 8010 setInsertPointAfterBundle(E); 8011 8012 Value *L = vectorizeTree(E->getOperand(0)); 8013 Value *R = vectorizeTree(E->getOperand(1)); 8014 8015 if (E->VectorizedValue) { 8016 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 8017 return E->VectorizedValue; 8018 } 8019 8020 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 8021 Value *V = Builder.CreateCmp(P0, L, R); 8022 propagateIRFlags(V, E->Scalars, VL0); 8023 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8024 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8025 V = ShuffleBuilder.finalize(V); 8026 8027 E->VectorizedValue = V; 8028 ++NumVectorInstructions; 8029 return V; 8030 } 8031 case Instruction::Select: { 8032 setInsertPointAfterBundle(E); 8033 8034 Value *Cond = vectorizeTree(E->getOperand(0)); 8035 Value *True = vectorizeTree(E->getOperand(1)); 8036 Value *False = vectorizeTree(E->getOperand(2)); 8037 8038 if (E->VectorizedValue) { 8039 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 8040 return E->VectorizedValue; 8041 } 8042 8043 Value *V = Builder.CreateSelect(Cond, True, False); 8044 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8045 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8046 V = ShuffleBuilder.finalize(V); 8047 8048 E->VectorizedValue = V; 8049 ++NumVectorInstructions; 8050 return V; 8051 } 8052 case Instruction::FNeg: { 8053 setInsertPointAfterBundle(E); 8054 8055 Value *Op = vectorizeTree(E->getOperand(0)); 8056 8057 if (E->VectorizedValue) { 8058 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 8059 return E->VectorizedValue; 8060 } 8061 8062 Value *V = Builder.CreateUnOp( 8063 static_cast<Instruction::UnaryOps>(E->getOpcode()), Op); 8064 propagateIRFlags(V, E->Scalars, VL0); 8065 if (auto *I = dyn_cast<Instruction>(V)) 8066 V = propagateMetadata(I, E->Scalars); 8067 8068 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8069 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8070 V = ShuffleBuilder.finalize(V); 8071 8072 E->VectorizedValue = V; 8073 ++NumVectorInstructions; 8074 8075 return V; 8076 } 8077 case Instruction::Add: 8078 case Instruction::FAdd: 8079 case Instruction::Sub: 8080 case Instruction::FSub: 8081 case Instruction::Mul: 8082 case Instruction::FMul: 8083 case Instruction::UDiv: 8084 case Instruction::SDiv: 8085 case Instruction::FDiv: 8086 case Instruction::URem: 8087 case Instruction::SRem: 8088 case Instruction::FRem: 8089 case Instruction::Shl: 8090 case Instruction::LShr: 8091 case Instruction::AShr: 8092 case Instruction::And: 8093 case Instruction::Or: 8094 case Instruction::Xor: { 8095 setInsertPointAfterBundle(E); 8096 8097 Value *LHS = vectorizeTree(E->getOperand(0)); 8098 Value *RHS = vectorizeTree(E->getOperand(1)); 8099 8100 if (E->VectorizedValue) { 8101 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 8102 return E->VectorizedValue; 8103 } 8104 8105 Value *V = Builder.CreateBinOp( 8106 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, 8107 RHS); 8108 propagateIRFlags(V, E->Scalars, VL0); 8109 if (auto *I = dyn_cast<Instruction>(V)) 8110 V = propagateMetadata(I, E->Scalars); 8111 8112 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8113 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8114 V = ShuffleBuilder.finalize(V); 8115 8116 E->VectorizedValue = V; 8117 ++NumVectorInstructions; 8118 8119 return V; 8120 } 8121 case Instruction::Load: { 8122 // Loads are inserted at the head of the tree because we don't want to 8123 // sink them all the way down past store instructions. 8124 setInsertPointAfterBundle(E); 8125 8126 LoadInst *LI = cast<LoadInst>(VL0); 8127 Instruction *NewLI; 8128 unsigned AS = LI->getPointerAddressSpace(); 8129 Value *PO = LI->getPointerOperand(); 8130 if (E->State == TreeEntry::Vectorize) { 8131 Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS)); 8132 NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign()); 8133 8134 // The pointer operand uses an in-tree scalar so we add the new BitCast 8135 // or LoadInst to ExternalUses list to make sure that an extract will 8136 // be generated in the future. 8137 if (TreeEntry *Entry = getTreeEntry(PO)) { 8138 // Find which lane we need to extract. 8139 unsigned FoundLane = Entry->findLaneForValue(PO); 8140 ExternalUses.emplace_back( 8141 PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane); 8142 } 8143 } else { 8144 assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state"); 8145 Value *VecPtr = vectorizeTree(E->getOperand(0)); 8146 // Use the minimum alignment of the gathered loads. 8147 Align CommonAlignment = LI->getAlign(); 8148 for (Value *V : E->Scalars) 8149 CommonAlignment = 8150 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 8151 NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment); 8152 } 8153 Value *V = propagateMetadata(NewLI, E->Scalars); 8154 8155 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8156 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8157 V = ShuffleBuilder.finalize(V); 8158 E->VectorizedValue = V; 8159 ++NumVectorInstructions; 8160 return V; 8161 } 8162 case Instruction::Store: { 8163 auto *SI = cast<StoreInst>(VL0); 8164 unsigned AS = SI->getPointerAddressSpace(); 8165 8166 setInsertPointAfterBundle(E); 8167 8168 Value *VecValue = vectorizeTree(E->getOperand(0)); 8169 ShuffleBuilder.addMask(E->ReorderIndices); 8170 VecValue = ShuffleBuilder.finalize(VecValue); 8171 8172 Value *ScalarPtr = SI->getPointerOperand(); 8173 Value *VecPtr = Builder.CreateBitCast( 8174 ScalarPtr, VecValue->getType()->getPointerTo(AS)); 8175 StoreInst *ST = 8176 Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign()); 8177 8178 // The pointer operand uses an in-tree scalar, so add the new BitCast or 8179 // StoreInst to ExternalUses to make sure that an extract will be 8180 // generated in the future. 8181 if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) { 8182 // Find which lane we need to extract. 8183 unsigned FoundLane = Entry->findLaneForValue(ScalarPtr); 8184 ExternalUses.push_back(ExternalUser( 8185 ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST, 8186 FoundLane)); 8187 } 8188 8189 Value *V = propagateMetadata(ST, E->Scalars); 8190 8191 E->VectorizedValue = V; 8192 ++NumVectorInstructions; 8193 return V; 8194 } 8195 case Instruction::GetElementPtr: { 8196 auto *GEP0 = cast<GetElementPtrInst>(VL0); 8197 setInsertPointAfterBundle(E); 8198 8199 Value *Op0 = vectorizeTree(E->getOperand(0)); 8200 8201 SmallVector<Value *> OpVecs; 8202 for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) { 8203 Value *OpVec = vectorizeTree(E->getOperand(J)); 8204 OpVecs.push_back(OpVec); 8205 } 8206 8207 Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs); 8208 if (Instruction *I = dyn_cast<GetElementPtrInst>(V)) { 8209 SmallVector<Value *> GEPs; 8210 for (Value *V : E->Scalars) { 8211 if (isa<GetElementPtrInst>(V)) 8212 GEPs.push_back(V); 8213 } 8214 V = propagateMetadata(I, GEPs); 8215 } 8216 8217 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8218 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8219 V = ShuffleBuilder.finalize(V); 8220 8221 E->VectorizedValue = V; 8222 ++NumVectorInstructions; 8223 8224 return V; 8225 } 8226 case Instruction::Call: { 8227 CallInst *CI = cast<CallInst>(VL0); 8228 setInsertPointAfterBundle(E); 8229 8230 Intrinsic::ID IID = Intrinsic::not_intrinsic; 8231 if (Function *FI = CI->getCalledFunction()) 8232 IID = FI->getIntrinsicID(); 8233 8234 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 8235 8236 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 8237 bool UseIntrinsic = ID != Intrinsic::not_intrinsic && 8238 VecCallCosts.first <= VecCallCosts.second; 8239 8240 Value *ScalarArg = nullptr; 8241 std::vector<Value *> OpVecs; 8242 SmallVector<Type *, 2> TysForDecl = 8243 {FixedVectorType::get(CI->getType(), E->Scalars.size())}; 8244 for (int j = 0, e = CI->arg_size(); j < e; ++j) { 8245 ValueList OpVL; 8246 // Some intrinsics have scalar arguments. This argument should not be 8247 // vectorized. 8248 if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) { 8249 CallInst *CEI = cast<CallInst>(VL0); 8250 ScalarArg = CEI->getArgOperand(j); 8251 OpVecs.push_back(CEI->getArgOperand(j)); 8252 if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j)) 8253 TysForDecl.push_back(ScalarArg->getType()); 8254 continue; 8255 } 8256 8257 Value *OpVec = vectorizeTree(E->getOperand(j)); 8258 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n"); 8259 OpVecs.push_back(OpVec); 8260 if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j)) 8261 TysForDecl.push_back(OpVec->getType()); 8262 } 8263 8264 Function *CF; 8265 if (!UseIntrinsic) { 8266 VFShape Shape = 8267 VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 8268 VecTy->getNumElements())), 8269 false /*HasGlobalPred*/); 8270 CF = VFDatabase(*CI).getVectorizedFunction(Shape); 8271 } else { 8272 CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl); 8273 } 8274 8275 SmallVector<OperandBundleDef, 1> OpBundles; 8276 CI->getOperandBundlesAsDefs(OpBundles); 8277 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles); 8278 8279 // The scalar argument uses an in-tree scalar so we add the new vectorized 8280 // call to ExternalUses list to make sure that an extract will be 8281 // generated in the future. 8282 if (ScalarArg) { 8283 if (TreeEntry *Entry = getTreeEntry(ScalarArg)) { 8284 // Find which lane we need to extract. 8285 unsigned FoundLane = Entry->findLaneForValue(ScalarArg); 8286 ExternalUses.push_back( 8287 ExternalUser(ScalarArg, cast<User>(V), FoundLane)); 8288 } 8289 } 8290 8291 propagateIRFlags(V, E->Scalars, VL0); 8292 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8293 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8294 V = ShuffleBuilder.finalize(V); 8295 8296 E->VectorizedValue = V; 8297 ++NumVectorInstructions; 8298 return V; 8299 } 8300 case Instruction::ShuffleVector: { 8301 assert(E->isAltShuffle() && 8302 ((Instruction::isBinaryOp(E->getOpcode()) && 8303 Instruction::isBinaryOp(E->getAltOpcode())) || 8304 (Instruction::isCast(E->getOpcode()) && 8305 Instruction::isCast(E->getAltOpcode())) || 8306 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 8307 "Invalid Shuffle Vector Operand"); 8308 8309 Value *LHS = nullptr, *RHS = nullptr; 8310 if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) { 8311 setInsertPointAfterBundle(E); 8312 LHS = vectorizeTree(E->getOperand(0)); 8313 RHS = vectorizeTree(E->getOperand(1)); 8314 } else { 8315 setInsertPointAfterBundle(E); 8316 LHS = vectorizeTree(E->getOperand(0)); 8317 } 8318 8319 if (E->VectorizedValue) { 8320 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 8321 return E->VectorizedValue; 8322 } 8323 8324 Value *V0, *V1; 8325 if (Instruction::isBinaryOp(E->getOpcode())) { 8326 V0 = Builder.CreateBinOp( 8327 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS); 8328 V1 = Builder.CreateBinOp( 8329 static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS); 8330 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 8331 V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS); 8332 auto *AltCI = cast<CmpInst>(E->getAltOp()); 8333 CmpInst::Predicate AltPred = AltCI->getPredicate(); 8334 V1 = Builder.CreateCmp(AltPred, LHS, RHS); 8335 } else { 8336 V0 = Builder.CreateCast( 8337 static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy); 8338 V1 = Builder.CreateCast( 8339 static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy); 8340 } 8341 // Add V0 and V1 to later analysis to try to find and remove matching 8342 // instruction, if any. 8343 for (Value *V : {V0, V1}) { 8344 if (auto *I = dyn_cast<Instruction>(V)) { 8345 GatherShuffleSeq.insert(I); 8346 CSEBlocks.insert(I->getParent()); 8347 } 8348 } 8349 8350 // Create shuffle to take alternate operations from the vector. 8351 // Also, gather up main and alt scalar ops to propagate IR flags to 8352 // each vector operation. 8353 ValueList OpScalars, AltScalars; 8354 SmallVector<int> Mask; 8355 buildShuffleEntryMask( 8356 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 8357 [E](Instruction *I) { 8358 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 8359 return isAlternateInstruction(I, E->getMainOp(), E->getAltOp()); 8360 }, 8361 Mask, &OpScalars, &AltScalars); 8362 8363 propagateIRFlags(V0, OpScalars); 8364 propagateIRFlags(V1, AltScalars); 8365 8366 Value *V = Builder.CreateShuffleVector(V0, V1, Mask); 8367 if (auto *I = dyn_cast<Instruction>(V)) { 8368 V = propagateMetadata(I, E->Scalars); 8369 GatherShuffleSeq.insert(I); 8370 CSEBlocks.insert(I->getParent()); 8371 } 8372 V = ShuffleBuilder.finalize(V); 8373 8374 E->VectorizedValue = V; 8375 ++NumVectorInstructions; 8376 8377 return V; 8378 } 8379 default: 8380 llvm_unreachable("unknown inst"); 8381 } 8382 return nullptr; 8383 } 8384 8385 Value *BoUpSLP::vectorizeTree() { 8386 ExtraValueToDebugLocsMap ExternallyUsedValues; 8387 return vectorizeTree(ExternallyUsedValues); 8388 } 8389 8390 namespace { 8391 /// Data type for handling buildvector sequences with the reused scalars from 8392 /// other tree entries. 8393 struct ShuffledInsertData { 8394 /// List of insertelements to be replaced by shuffles. 8395 SmallVector<InsertElementInst *> InsertElements; 8396 /// The parent vectors and shuffle mask for the given list of inserts. 8397 MapVector<Value *, SmallVector<int>> ValueMasks; 8398 }; 8399 } // namespace 8400 8401 Value * 8402 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) { 8403 // All blocks must be scheduled before any instructions are inserted. 8404 for (auto &BSIter : BlocksSchedules) { 8405 scheduleBlock(BSIter.second.get()); 8406 } 8407 8408 Builder.SetInsertPoint(&F->getEntryBlock().front()); 8409 auto *VectorRoot = vectorizeTree(VectorizableTree[0].get()); 8410 8411 // If the vectorized tree can be rewritten in a smaller type, we truncate the 8412 // vectorized root. InstCombine will then rewrite the entire expression. We 8413 // sign extend the extracted values below. 8414 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 8415 if (MinBWs.count(ScalarRoot)) { 8416 if (auto *I = dyn_cast<Instruction>(VectorRoot)) { 8417 // If current instr is a phi and not the last phi, insert it after the 8418 // last phi node. 8419 if (isa<PHINode>(I)) 8420 Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt()); 8421 else 8422 Builder.SetInsertPoint(&*++BasicBlock::iterator(I)); 8423 } 8424 auto BundleWidth = VectorizableTree[0]->Scalars.size(); 8425 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 8426 auto *VecTy = FixedVectorType::get(MinTy, BundleWidth); 8427 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy); 8428 VectorizableTree[0]->VectorizedValue = Trunc; 8429 } 8430 8431 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() 8432 << " values .\n"); 8433 8434 SmallVector<ShuffledInsertData> ShuffledInserts; 8435 // Maps vector instruction to original insertelement instruction 8436 DenseMap<Value *, InsertElementInst *> VectorToInsertElement; 8437 // Extract all of the elements with the external uses. 8438 for (const auto &ExternalUse : ExternalUses) { 8439 Value *Scalar = ExternalUse.Scalar; 8440 llvm::User *User = ExternalUse.User; 8441 8442 // Skip users that we already RAUW. This happens when one instruction 8443 // has multiple uses of the same value. 8444 if (User && !is_contained(Scalar->users(), User)) 8445 continue; 8446 TreeEntry *E = getTreeEntry(Scalar); 8447 assert(E && "Invalid scalar"); 8448 assert(E->State != TreeEntry::NeedToGather && 8449 "Extracting from a gather list"); 8450 // Non-instruction pointers are not deleted, just skip them. 8451 if (E->getOpcode() == Instruction::GetElementPtr && 8452 !isa<GetElementPtrInst>(Scalar)) 8453 continue; 8454 8455 Value *Vec = E->VectorizedValue; 8456 assert(Vec && "Can't find vectorizable value"); 8457 8458 Value *Lane = Builder.getInt32(ExternalUse.Lane); 8459 auto ExtractAndExtendIfNeeded = [&](Value *Vec) { 8460 if (Scalar->getType() != Vec->getType()) { 8461 Value *Ex; 8462 // "Reuse" the existing extract to improve final codegen. 8463 if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) { 8464 Ex = Builder.CreateExtractElement(ES->getOperand(0), 8465 ES->getOperand(1)); 8466 } else { 8467 Ex = Builder.CreateExtractElement(Vec, Lane); 8468 } 8469 // If necessary, sign-extend or zero-extend ScalarRoot 8470 // to the larger type. 8471 if (!MinBWs.count(ScalarRoot)) 8472 return Ex; 8473 if (MinBWs[ScalarRoot].second) 8474 return Builder.CreateSExt(Ex, Scalar->getType()); 8475 return Builder.CreateZExt(Ex, Scalar->getType()); 8476 } 8477 assert(isa<FixedVectorType>(Scalar->getType()) && 8478 isa<InsertElementInst>(Scalar) && 8479 "In-tree scalar of vector type is not insertelement?"); 8480 auto *IE = cast<InsertElementInst>(Scalar); 8481 VectorToInsertElement.try_emplace(Vec, IE); 8482 return Vec; 8483 }; 8484 // If User == nullptr, the Scalar is used as extra arg. Generate 8485 // ExtractElement instruction and update the record for this scalar in 8486 // ExternallyUsedValues. 8487 if (!User) { 8488 assert(ExternallyUsedValues.count(Scalar) && 8489 "Scalar with nullptr as an external user must be registered in " 8490 "ExternallyUsedValues map"); 8491 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 8492 Builder.SetInsertPoint(VecI->getParent(), 8493 std::next(VecI->getIterator())); 8494 } else { 8495 Builder.SetInsertPoint(&F->getEntryBlock().front()); 8496 } 8497 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 8498 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent()); 8499 auto &NewInstLocs = ExternallyUsedValues[NewInst]; 8500 auto It = ExternallyUsedValues.find(Scalar); 8501 assert(It != ExternallyUsedValues.end() && 8502 "Externally used scalar is not found in ExternallyUsedValues"); 8503 NewInstLocs.append(It->second); 8504 ExternallyUsedValues.erase(Scalar); 8505 // Required to update internally referenced instructions. 8506 Scalar->replaceAllUsesWith(NewInst); 8507 continue; 8508 } 8509 8510 if (auto *VU = dyn_cast<InsertElementInst>(User)) { 8511 // Skip if the scalar is another vector op or Vec is not an instruction. 8512 if (!Scalar->getType()->isVectorTy() && isa<Instruction>(Vec)) { 8513 if (auto *FTy = dyn_cast<FixedVectorType>(User->getType())) { 8514 Optional<unsigned> InsertIdx = getInsertIndex(VU); 8515 if (InsertIdx) { 8516 // Need to use original vector, if the root is truncated. 8517 if (MinBWs.count(Scalar) && 8518 VectorizableTree[0]->VectorizedValue == Vec) 8519 Vec = VectorRoot; 8520 auto *It = 8521 find_if(ShuffledInserts, [VU](const ShuffledInsertData &Data) { 8522 // Checks if 2 insertelements are from the same buildvector. 8523 InsertElementInst *VecInsert = Data.InsertElements.front(); 8524 return areTwoInsertFromSameBuildVector(VU, VecInsert); 8525 }); 8526 unsigned Idx = *InsertIdx; 8527 if (It == ShuffledInserts.end()) { 8528 (void)ShuffledInserts.emplace_back(); 8529 It = std::next(ShuffledInserts.begin(), 8530 ShuffledInserts.size() - 1); 8531 SmallVectorImpl<int> &Mask = It->ValueMasks[Vec]; 8532 if (Mask.empty()) 8533 Mask.assign(FTy->getNumElements(), UndefMaskElem); 8534 // Find the insertvector, vectorized in tree, if any. 8535 Value *Base = VU; 8536 while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) { 8537 if (IEBase != User && 8538 (!IEBase->hasOneUse() || 8539 getInsertIndex(IEBase).value_or(Idx) == Idx)) 8540 break; 8541 // Build the mask for the vectorized insertelement instructions. 8542 if (const TreeEntry *E = getTreeEntry(IEBase)) { 8543 do { 8544 IEBase = cast<InsertElementInst>(Base); 8545 int IEIdx = *getInsertIndex(IEBase); 8546 assert(Mask[Idx] == UndefMaskElem && 8547 "InsertElementInstruction used already."); 8548 Mask[IEIdx] = IEIdx; 8549 Base = IEBase->getOperand(0); 8550 } while (E == getTreeEntry(Base)); 8551 break; 8552 } 8553 Base = cast<InsertElementInst>(Base)->getOperand(0); 8554 // After the vectorization the def-use chain has changed, need 8555 // to look through original insertelement instructions, if they 8556 // get replaced by vector instructions. 8557 auto It = VectorToInsertElement.find(Base); 8558 if (It != VectorToInsertElement.end()) 8559 Base = It->second; 8560 } 8561 } 8562 SmallVectorImpl<int> &Mask = It->ValueMasks[Vec]; 8563 if (Mask.empty()) 8564 Mask.assign(FTy->getNumElements(), UndefMaskElem); 8565 Mask[Idx] = ExternalUse.Lane; 8566 It->InsertElements.push_back(cast<InsertElementInst>(User)); 8567 continue; 8568 } 8569 } 8570 } 8571 } 8572 8573 // Generate extracts for out-of-tree users. 8574 // Find the insertion point for the extractelement lane. 8575 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 8576 if (PHINode *PH = dyn_cast<PHINode>(User)) { 8577 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { 8578 if (PH->getIncomingValue(i) == Scalar) { 8579 Instruction *IncomingTerminator = 8580 PH->getIncomingBlock(i)->getTerminator(); 8581 if (isa<CatchSwitchInst>(IncomingTerminator)) { 8582 Builder.SetInsertPoint(VecI->getParent(), 8583 std::next(VecI->getIterator())); 8584 } else { 8585 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator()); 8586 } 8587 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 8588 CSEBlocks.insert(PH->getIncomingBlock(i)); 8589 PH->setOperand(i, NewInst); 8590 } 8591 } 8592 } else { 8593 Builder.SetInsertPoint(cast<Instruction>(User)); 8594 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 8595 CSEBlocks.insert(cast<Instruction>(User)->getParent()); 8596 User->replaceUsesOfWith(Scalar, NewInst); 8597 } 8598 } else { 8599 Builder.SetInsertPoint(&F->getEntryBlock().front()); 8600 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 8601 CSEBlocks.insert(&F->getEntryBlock()); 8602 User->replaceUsesOfWith(Scalar, NewInst); 8603 } 8604 8605 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n"); 8606 } 8607 8608 // Checks if the mask is an identity mask. 8609 auto &&IsIdentityMask = [](ArrayRef<int> Mask, FixedVectorType *VecTy) { 8610 int Limit = Mask.size(); 8611 return VecTy->getNumElements() == Mask.size() && 8612 all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) && 8613 ShuffleVectorInst::isIdentityMask(Mask); 8614 }; 8615 // Tries to combine 2 different masks into single one. 8616 auto &&CombineMasks = [](SmallVectorImpl<int> &Mask, ArrayRef<int> ExtMask) { 8617 SmallVector<int> NewMask(ExtMask.size(), UndefMaskElem); 8618 for (int I = 0, Sz = ExtMask.size(); I < Sz; ++I) { 8619 if (ExtMask[I] == UndefMaskElem) 8620 continue; 8621 NewMask[I] = Mask[ExtMask[I]]; 8622 } 8623 Mask.swap(NewMask); 8624 }; 8625 // Peek through shuffles, trying to simplify the final shuffle code. 8626 auto &&PeekThroughShuffles = 8627 [&IsIdentityMask, &CombineMasks](Value *&V, SmallVectorImpl<int> &Mask, 8628 bool CheckForLengthChange = false) { 8629 while (auto *SV = dyn_cast<ShuffleVectorInst>(V)) { 8630 // Exit if not a fixed vector type or changing size shuffle. 8631 if (!isa<FixedVectorType>(SV->getType()) || 8632 (CheckForLengthChange && SV->changesLength())) 8633 break; 8634 // Exit if the identity or broadcast mask is found. 8635 if (IsIdentityMask(Mask, cast<FixedVectorType>(SV->getType())) || 8636 SV->isZeroEltSplat()) 8637 break; 8638 bool IsOp1Undef = isUndefVector(SV->getOperand(0)); 8639 bool IsOp2Undef = isUndefVector(SV->getOperand(1)); 8640 if (!IsOp1Undef && !IsOp2Undef) 8641 break; 8642 SmallVector<int> ShuffleMask(SV->getShuffleMask().begin(), 8643 SV->getShuffleMask().end()); 8644 CombineMasks(ShuffleMask, Mask); 8645 Mask.swap(ShuffleMask); 8646 if (IsOp2Undef) 8647 V = SV->getOperand(0); 8648 else 8649 V = SV->getOperand(1); 8650 } 8651 }; 8652 // Smart shuffle instruction emission, walks through shuffles trees and 8653 // tries to find the best matching vector for the actual shuffle 8654 // instruction. 8655 auto &&CreateShuffle = [this, &IsIdentityMask, &PeekThroughShuffles, 8656 &CombineMasks](Value *V1, Value *V2, 8657 ArrayRef<int> Mask) -> Value * { 8658 assert(V1 && "Expected at least one vector value."); 8659 if (V2 && !isUndefVector(V2)) { 8660 // Peek through shuffles. 8661 Value *Op1 = V1; 8662 Value *Op2 = V2; 8663 int VF = 8664 cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue(); 8665 SmallVector<int> CombinedMask1(Mask.size(), UndefMaskElem); 8666 SmallVector<int> CombinedMask2(Mask.size(), UndefMaskElem); 8667 for (int I = 0, E = Mask.size(); I < E; ++I) { 8668 if (Mask[I] < VF) 8669 CombinedMask1[I] = Mask[I]; 8670 else 8671 CombinedMask2[I] = Mask[I] - VF; 8672 } 8673 Value *PrevOp1; 8674 Value *PrevOp2; 8675 do { 8676 PrevOp1 = Op1; 8677 PrevOp2 = Op2; 8678 PeekThroughShuffles(Op1, CombinedMask1, /*CheckForLengthChange=*/true); 8679 PeekThroughShuffles(Op2, CombinedMask2, /*CheckForLengthChange=*/true); 8680 // Check if we have 2 resizing shuffles - need to peek through operands 8681 // again. 8682 if (auto *SV1 = dyn_cast<ShuffleVectorInst>(Op1)) 8683 if (auto *SV2 = dyn_cast<ShuffleVectorInst>(Op2)) 8684 if (SV1->getOperand(0)->getType() == 8685 SV2->getOperand(0)->getType() && 8686 SV1->getOperand(0)->getType() != SV1->getType() && 8687 isUndefVector(SV1->getOperand(1)) && 8688 isUndefVector(SV2->getOperand(1))) { 8689 Op1 = SV1->getOperand(0); 8690 Op2 = SV2->getOperand(0); 8691 SmallVector<int> ShuffleMask1(SV1->getShuffleMask().begin(), 8692 SV1->getShuffleMask().end()); 8693 CombineMasks(ShuffleMask1, CombinedMask1); 8694 CombinedMask1.swap(ShuffleMask1); 8695 SmallVector<int> ShuffleMask2(SV2->getShuffleMask().begin(), 8696 SV2->getShuffleMask().end()); 8697 CombineMasks(ShuffleMask2, CombinedMask2); 8698 CombinedMask2.swap(ShuffleMask2); 8699 } 8700 } while (PrevOp1 != Op1 || PrevOp2 != Op2); 8701 VF = cast<VectorType>(Op1->getType()) 8702 ->getElementCount() 8703 .getKnownMinValue(); 8704 for (int I = 0, E = Mask.size(); I < E; ++I) { 8705 if (CombinedMask2[I] != UndefMaskElem) { 8706 assert(CombinedMask1[I] == UndefMaskElem && 8707 "Expected undefined mask element"); 8708 CombinedMask1[I] = CombinedMask2[I] + (Op1 == Op2 ? 0 : VF); 8709 } 8710 } 8711 Value *Vec = Builder.CreateShuffleVector( 8712 Op1, Op1 == Op2 ? PoisonValue::get(Op1->getType()) : Op2, 8713 CombinedMask1); 8714 if (auto *I = dyn_cast<Instruction>(Vec)) { 8715 GatherShuffleSeq.insert(I); 8716 CSEBlocks.insert(I->getParent()); 8717 } 8718 return Vec; 8719 } 8720 if (isa<PoisonValue>(V1)) 8721 return PoisonValue::get(FixedVectorType::get( 8722 cast<VectorType>(V1->getType())->getElementType(), Mask.size())); 8723 Value *Op = V1; 8724 SmallVector<int> CombinedMask(Mask.begin(), Mask.end()); 8725 PeekThroughShuffles(Op, CombinedMask); 8726 if (!isa<FixedVectorType>(Op->getType()) || 8727 !IsIdentityMask(CombinedMask, cast<FixedVectorType>(Op->getType()))) { 8728 Value *Vec = Builder.CreateShuffleVector(Op, CombinedMask); 8729 if (auto *I = dyn_cast<Instruction>(Vec)) { 8730 GatherShuffleSeq.insert(I); 8731 CSEBlocks.insert(I->getParent()); 8732 } 8733 return Vec; 8734 } 8735 return Op; 8736 }; 8737 8738 auto &&ResizeToVF = [&CreateShuffle](Value *Vec, ArrayRef<int> Mask) { 8739 unsigned VF = Mask.size(); 8740 unsigned VecVF = cast<FixedVectorType>(Vec->getType())->getNumElements(); 8741 if (VF != VecVF) { 8742 if (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); })) { 8743 Vec = CreateShuffle(Vec, nullptr, Mask); 8744 return std::make_pair(Vec, true); 8745 } 8746 SmallVector<int> ResizeMask(VF, UndefMaskElem); 8747 for (unsigned I = 0; I < VF; ++I) { 8748 if (Mask[I] != UndefMaskElem) 8749 ResizeMask[Mask[I]] = Mask[I]; 8750 } 8751 Vec = CreateShuffle(Vec, nullptr, ResizeMask); 8752 } 8753 8754 return std::make_pair(Vec, false); 8755 }; 8756 // Perform shuffling of the vectorize tree entries for better handling of 8757 // external extracts. 8758 for (int I = 0, E = ShuffledInserts.size(); I < E; ++I) { 8759 // Find the first and the last instruction in the list of insertelements. 8760 sort(ShuffledInserts[I].InsertElements, isFirstInsertElement); 8761 InsertElementInst *FirstInsert = ShuffledInserts[I].InsertElements.front(); 8762 InsertElementInst *LastInsert = ShuffledInserts[I].InsertElements.back(); 8763 Builder.SetInsertPoint(LastInsert); 8764 auto Vector = ShuffledInserts[I].ValueMasks.takeVector(); 8765 Value *NewInst = performExtractsShuffleAction<Value>( 8766 makeMutableArrayRef(Vector.data(), Vector.size()), 8767 FirstInsert->getOperand(0), 8768 [](Value *Vec) { 8769 return cast<VectorType>(Vec->getType()) 8770 ->getElementCount() 8771 .getKnownMinValue(); 8772 }, 8773 ResizeToVF, 8774 [FirstInsert, &CreateShuffle](ArrayRef<int> Mask, 8775 ArrayRef<Value *> Vals) { 8776 assert((Vals.size() == 1 || Vals.size() == 2) && 8777 "Expected exactly 1 or 2 input values."); 8778 if (Vals.size() == 1) { 8779 // Do not create shuffle if the mask is a simple identity 8780 // non-resizing mask. 8781 if (Mask.size() != cast<FixedVectorType>(Vals.front()->getType()) 8782 ->getNumElements() || 8783 !ShuffleVectorInst::isIdentityMask(Mask)) 8784 return CreateShuffle(Vals.front(), nullptr, Mask); 8785 return Vals.front(); 8786 } 8787 return CreateShuffle(Vals.front() ? Vals.front() 8788 : FirstInsert->getOperand(0), 8789 Vals.back(), Mask); 8790 }); 8791 auto It = ShuffledInserts[I].InsertElements.rbegin(); 8792 // Rebuild buildvector chain. 8793 InsertElementInst *II = nullptr; 8794 if (It != ShuffledInserts[I].InsertElements.rend()) 8795 II = *It; 8796 SmallVector<Instruction *> Inserts; 8797 while (It != ShuffledInserts[I].InsertElements.rend()) { 8798 assert(II && "Must be an insertelement instruction."); 8799 if (*It == II) 8800 ++It; 8801 else 8802 Inserts.push_back(cast<Instruction>(II)); 8803 II = dyn_cast<InsertElementInst>(II->getOperand(0)); 8804 } 8805 for (Instruction *II : reverse(Inserts)) { 8806 II->replaceUsesOfWith(II->getOperand(0), NewInst); 8807 if (auto *NewI = dyn_cast<Instruction>(NewInst)) 8808 if (II->getParent() == NewI->getParent() && II->comesBefore(NewI)) 8809 II->moveAfter(NewI); 8810 NewInst = II; 8811 } 8812 LastInsert->replaceAllUsesWith(NewInst); 8813 for (InsertElementInst *IE : reverse(ShuffledInserts[I].InsertElements)) { 8814 IE->replaceUsesOfWith(IE->getOperand(1), 8815 PoisonValue::get(IE->getOperand(1)->getType())); 8816 eraseInstruction(IE); 8817 } 8818 CSEBlocks.insert(LastInsert->getParent()); 8819 } 8820 8821 // For each vectorized value: 8822 for (auto &TEPtr : VectorizableTree) { 8823 TreeEntry *Entry = TEPtr.get(); 8824 8825 // No need to handle users of gathered values. 8826 if (Entry->State == TreeEntry::NeedToGather) 8827 continue; 8828 8829 assert(Entry->VectorizedValue && "Can't find vectorizable value"); 8830 8831 // For each lane: 8832 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 8833 Value *Scalar = Entry->Scalars[Lane]; 8834 8835 if (Entry->getOpcode() == Instruction::GetElementPtr && 8836 !isa<GetElementPtrInst>(Scalar)) 8837 continue; 8838 #ifndef NDEBUG 8839 Type *Ty = Scalar->getType(); 8840 if (!Ty->isVoidTy()) { 8841 for (User *U : Scalar->users()) { 8842 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n"); 8843 8844 // It is legal to delete users in the ignorelist. 8845 assert((getTreeEntry(U) || 8846 (UserIgnoreList && UserIgnoreList->contains(U)) || 8847 (isa_and_nonnull<Instruction>(U) && 8848 isDeleted(cast<Instruction>(U)))) && 8849 "Deleting out-of-tree value"); 8850 } 8851 } 8852 #endif 8853 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n"); 8854 eraseInstruction(cast<Instruction>(Scalar)); 8855 } 8856 } 8857 8858 Builder.ClearInsertionPoint(); 8859 InstrElementSize.clear(); 8860 8861 return VectorizableTree[0]->VectorizedValue; 8862 } 8863 8864 void BoUpSLP::optimizeGatherSequence() { 8865 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size() 8866 << " gather sequences instructions.\n"); 8867 // LICM InsertElementInst sequences. 8868 for (Instruction *I : GatherShuffleSeq) { 8869 if (isDeleted(I)) 8870 continue; 8871 8872 // Check if this block is inside a loop. 8873 Loop *L = LI->getLoopFor(I->getParent()); 8874 if (!L) 8875 continue; 8876 8877 // Check if it has a preheader. 8878 BasicBlock *PreHeader = L->getLoopPreheader(); 8879 if (!PreHeader) 8880 continue; 8881 8882 // If the vector or the element that we insert into it are 8883 // instructions that are defined in this basic block then we can't 8884 // hoist this instruction. 8885 if (any_of(I->operands(), [L](Value *V) { 8886 auto *OpI = dyn_cast<Instruction>(V); 8887 return OpI && L->contains(OpI); 8888 })) 8889 continue; 8890 8891 // We can hoist this instruction. Move it to the pre-header. 8892 I->moveBefore(PreHeader->getTerminator()); 8893 } 8894 8895 // Make a list of all reachable blocks in our CSE queue. 8896 SmallVector<const DomTreeNode *, 8> CSEWorkList; 8897 CSEWorkList.reserve(CSEBlocks.size()); 8898 for (BasicBlock *BB : CSEBlocks) 8899 if (DomTreeNode *N = DT->getNode(BB)) { 8900 assert(DT->isReachableFromEntry(N)); 8901 CSEWorkList.push_back(N); 8902 } 8903 8904 // Sort blocks by domination. This ensures we visit a block after all blocks 8905 // dominating it are visited. 8906 llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) { 8907 assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && 8908 "Different nodes should have different DFS numbers"); 8909 return A->getDFSNumIn() < B->getDFSNumIn(); 8910 }); 8911 8912 // Less defined shuffles can be replaced by the more defined copies. 8913 // Between two shuffles one is less defined if it has the same vector operands 8914 // and its mask indeces are the same as in the first one or undefs. E.g. 8915 // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0, 8916 // poison, <0, 0, 0, 0>. 8917 auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2, 8918 SmallVectorImpl<int> &NewMask) { 8919 if (I1->getType() != I2->getType()) 8920 return false; 8921 auto *SI1 = dyn_cast<ShuffleVectorInst>(I1); 8922 auto *SI2 = dyn_cast<ShuffleVectorInst>(I2); 8923 if (!SI1 || !SI2) 8924 return I1->isIdenticalTo(I2); 8925 if (SI1->isIdenticalTo(SI2)) 8926 return true; 8927 for (int I = 0, E = SI1->getNumOperands(); I < E; ++I) 8928 if (SI1->getOperand(I) != SI2->getOperand(I)) 8929 return false; 8930 // Check if the second instruction is more defined than the first one. 8931 NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end()); 8932 ArrayRef<int> SM1 = SI1->getShuffleMask(); 8933 // Count trailing undefs in the mask to check the final number of used 8934 // registers. 8935 unsigned LastUndefsCnt = 0; 8936 for (int I = 0, E = NewMask.size(); I < E; ++I) { 8937 if (SM1[I] == UndefMaskElem) 8938 ++LastUndefsCnt; 8939 else 8940 LastUndefsCnt = 0; 8941 if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem && 8942 NewMask[I] != SM1[I]) 8943 return false; 8944 if (NewMask[I] == UndefMaskElem) 8945 NewMask[I] = SM1[I]; 8946 } 8947 // Check if the last undefs actually change the final number of used vector 8948 // registers. 8949 return SM1.size() - LastUndefsCnt > 1 && 8950 TTI->getNumberOfParts(SI1->getType()) == 8951 TTI->getNumberOfParts( 8952 FixedVectorType::get(SI1->getType()->getElementType(), 8953 SM1.size() - LastUndefsCnt)); 8954 }; 8955 // Perform O(N^2) search over the gather/shuffle sequences and merge identical 8956 // instructions. TODO: We can further optimize this scan if we split the 8957 // instructions into different buckets based on the insert lane. 8958 SmallVector<Instruction *, 16> Visited; 8959 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) { 8960 assert(*I && 8961 (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && 8962 "Worklist not sorted properly!"); 8963 BasicBlock *BB = (*I)->getBlock(); 8964 // For all instructions in blocks containing gather sequences: 8965 for (Instruction &In : llvm::make_early_inc_range(*BB)) { 8966 if (isDeleted(&In)) 8967 continue; 8968 if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) && 8969 !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In)) 8970 continue; 8971 8972 // Check if we can replace this instruction with any of the 8973 // visited instructions. 8974 bool Replaced = false; 8975 for (Instruction *&V : Visited) { 8976 SmallVector<int> NewMask; 8977 if (IsIdenticalOrLessDefined(&In, V, NewMask) && 8978 DT->dominates(V->getParent(), In.getParent())) { 8979 In.replaceAllUsesWith(V); 8980 eraseInstruction(&In); 8981 if (auto *SI = dyn_cast<ShuffleVectorInst>(V)) 8982 if (!NewMask.empty()) 8983 SI->setShuffleMask(NewMask); 8984 Replaced = true; 8985 break; 8986 } 8987 if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) && 8988 GatherShuffleSeq.contains(V) && 8989 IsIdenticalOrLessDefined(V, &In, NewMask) && 8990 DT->dominates(In.getParent(), V->getParent())) { 8991 In.moveAfter(V); 8992 V->replaceAllUsesWith(&In); 8993 eraseInstruction(V); 8994 if (auto *SI = dyn_cast<ShuffleVectorInst>(&In)) 8995 if (!NewMask.empty()) 8996 SI->setShuffleMask(NewMask); 8997 V = &In; 8998 Replaced = true; 8999 break; 9000 } 9001 } 9002 if (!Replaced) { 9003 assert(!is_contained(Visited, &In)); 9004 Visited.push_back(&In); 9005 } 9006 } 9007 } 9008 CSEBlocks.clear(); 9009 GatherShuffleSeq.clear(); 9010 } 9011 9012 BoUpSLP::ScheduleData * 9013 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) { 9014 ScheduleData *Bundle = nullptr; 9015 ScheduleData *PrevInBundle = nullptr; 9016 for (Value *V : VL) { 9017 if (doesNotNeedToBeScheduled(V)) 9018 continue; 9019 ScheduleData *BundleMember = getScheduleData(V); 9020 assert(BundleMember && 9021 "no ScheduleData for bundle member " 9022 "(maybe not in same basic block)"); 9023 assert(BundleMember->isSchedulingEntity() && 9024 "bundle member already part of other bundle"); 9025 if (PrevInBundle) { 9026 PrevInBundle->NextInBundle = BundleMember; 9027 } else { 9028 Bundle = BundleMember; 9029 } 9030 9031 // Group the instructions to a bundle. 9032 BundleMember->FirstInBundle = Bundle; 9033 PrevInBundle = BundleMember; 9034 } 9035 assert(Bundle && "Failed to find schedule bundle"); 9036 return Bundle; 9037 } 9038 9039 // Groups the instructions to a bundle (which is then a single scheduling entity) 9040 // and schedules instructions until the bundle gets ready. 9041 Optional<BoUpSLP::ScheduleData *> 9042 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 9043 const InstructionsState &S) { 9044 // No need to schedule PHIs, insertelement, extractelement and extractvalue 9045 // instructions. 9046 if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) || 9047 doesNotNeedToSchedule(VL)) 9048 return nullptr; 9049 9050 // Initialize the instruction bundle. 9051 Instruction *OldScheduleEnd = ScheduleEnd; 9052 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n"); 9053 9054 auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule, 9055 ScheduleData *Bundle) { 9056 // The scheduling region got new instructions at the lower end (or it is a 9057 // new region for the first bundle). This makes it necessary to 9058 // recalculate all dependencies. 9059 // It is seldom that this needs to be done a second time after adding the 9060 // initial bundle to the region. 9061 if (ScheduleEnd != OldScheduleEnd) { 9062 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) 9063 doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); }); 9064 ReSchedule = true; 9065 } 9066 if (Bundle) { 9067 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle 9068 << " in block " << BB->getName() << "\n"); 9069 calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP); 9070 } 9071 9072 if (ReSchedule) { 9073 resetSchedule(); 9074 initialFillReadyList(ReadyInsts); 9075 } 9076 9077 // Now try to schedule the new bundle or (if no bundle) just calculate 9078 // dependencies. As soon as the bundle is "ready" it means that there are no 9079 // cyclic dependencies and we can schedule it. Note that's important that we 9080 // don't "schedule" the bundle yet (see cancelScheduling). 9081 while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) && 9082 !ReadyInsts.empty()) { 9083 ScheduleData *Picked = ReadyInsts.pop_back_val(); 9084 assert(Picked->isSchedulingEntity() && Picked->isReady() && 9085 "must be ready to schedule"); 9086 schedule(Picked, ReadyInsts); 9087 } 9088 }; 9089 9090 // Make sure that the scheduling region contains all 9091 // instructions of the bundle. 9092 for (Value *V : VL) { 9093 if (doesNotNeedToBeScheduled(V)) 9094 continue; 9095 if (!extendSchedulingRegion(V, S)) { 9096 // If the scheduling region got new instructions at the lower end (or it 9097 // is a new region for the first bundle). This makes it necessary to 9098 // recalculate all dependencies. 9099 // Otherwise the compiler may crash trying to incorrectly calculate 9100 // dependencies and emit instruction in the wrong order at the actual 9101 // scheduling. 9102 TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr); 9103 return None; 9104 } 9105 } 9106 9107 bool ReSchedule = false; 9108 for (Value *V : VL) { 9109 if (doesNotNeedToBeScheduled(V)) 9110 continue; 9111 ScheduleData *BundleMember = getScheduleData(V); 9112 assert(BundleMember && 9113 "no ScheduleData for bundle member (maybe not in same basic block)"); 9114 9115 // Make sure we don't leave the pieces of the bundle in the ready list when 9116 // whole bundle might not be ready. 9117 ReadyInsts.remove(BundleMember); 9118 9119 if (!BundleMember->IsScheduled) 9120 continue; 9121 // A bundle member was scheduled as single instruction before and now 9122 // needs to be scheduled as part of the bundle. We just get rid of the 9123 // existing schedule. 9124 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember 9125 << " was already scheduled\n"); 9126 ReSchedule = true; 9127 } 9128 9129 auto *Bundle = buildBundle(VL); 9130 TryScheduleBundleImpl(ReSchedule, Bundle); 9131 if (!Bundle->isReady()) { 9132 cancelScheduling(VL, S.OpValue); 9133 return None; 9134 } 9135 return Bundle; 9136 } 9137 9138 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL, 9139 Value *OpValue) { 9140 if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) || 9141 doesNotNeedToSchedule(VL)) 9142 return; 9143 9144 if (doesNotNeedToBeScheduled(OpValue)) 9145 OpValue = *find_if_not(VL, doesNotNeedToBeScheduled); 9146 ScheduleData *Bundle = getScheduleData(OpValue); 9147 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n"); 9148 assert(!Bundle->IsScheduled && 9149 "Can't cancel bundle which is already scheduled"); 9150 assert(Bundle->isSchedulingEntity() && 9151 (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) && 9152 "tried to unbundle something which is not a bundle"); 9153 9154 // Remove the bundle from the ready list. 9155 if (Bundle->isReady()) 9156 ReadyInsts.remove(Bundle); 9157 9158 // Un-bundle: make single instructions out of the bundle. 9159 ScheduleData *BundleMember = Bundle; 9160 while (BundleMember) { 9161 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links"); 9162 BundleMember->FirstInBundle = BundleMember; 9163 ScheduleData *Next = BundleMember->NextInBundle; 9164 BundleMember->NextInBundle = nullptr; 9165 BundleMember->TE = nullptr; 9166 if (BundleMember->unscheduledDepsInBundle() == 0) { 9167 ReadyInsts.insert(BundleMember); 9168 } 9169 BundleMember = Next; 9170 } 9171 } 9172 9173 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() { 9174 // Allocate a new ScheduleData for the instruction. 9175 if (ChunkPos >= ChunkSize) { 9176 ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize)); 9177 ChunkPos = 0; 9178 } 9179 return &(ScheduleDataChunks.back()[ChunkPos++]); 9180 } 9181 9182 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V, 9183 const InstructionsState &S) { 9184 if (getScheduleData(V, isOneOf(S, V))) 9185 return true; 9186 Instruction *I = dyn_cast<Instruction>(V); 9187 assert(I && "bundle member must be an instruction"); 9188 assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && 9189 !doesNotNeedToBeScheduled(I) && 9190 "phi nodes/insertelements/extractelements/extractvalues don't need to " 9191 "be scheduled"); 9192 auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool { 9193 ScheduleData *ISD = getScheduleData(I); 9194 if (!ISD) 9195 return false; 9196 assert(isInSchedulingRegion(ISD) && 9197 "ScheduleData not in scheduling region"); 9198 ScheduleData *SD = allocateScheduleDataChunks(); 9199 SD->Inst = I; 9200 SD->init(SchedulingRegionID, S.OpValue); 9201 ExtraScheduleDataMap[I][S.OpValue] = SD; 9202 return true; 9203 }; 9204 if (CheckScheduleForI(I)) 9205 return true; 9206 if (!ScheduleStart) { 9207 // It's the first instruction in the new region. 9208 initScheduleData(I, I->getNextNode(), nullptr, nullptr); 9209 ScheduleStart = I; 9210 ScheduleEnd = I->getNextNode(); 9211 if (isOneOf(S, I) != I) 9212 CheckScheduleForI(I); 9213 assert(ScheduleEnd && "tried to vectorize a terminator?"); 9214 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n"); 9215 return true; 9216 } 9217 // Search up and down at the same time, because we don't know if the new 9218 // instruction is above or below the existing scheduling region. 9219 BasicBlock::reverse_iterator UpIter = 9220 ++ScheduleStart->getIterator().getReverse(); 9221 BasicBlock::reverse_iterator UpperEnd = BB->rend(); 9222 BasicBlock::iterator DownIter = ScheduleEnd->getIterator(); 9223 BasicBlock::iterator LowerEnd = BB->end(); 9224 while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I && 9225 &*DownIter != I) { 9226 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) { 9227 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n"); 9228 return false; 9229 } 9230 9231 ++UpIter; 9232 ++DownIter; 9233 } 9234 if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) { 9235 assert(I->getParent() == ScheduleStart->getParent() && 9236 "Instruction is in wrong basic block."); 9237 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion); 9238 ScheduleStart = I; 9239 if (isOneOf(S, I) != I) 9240 CheckScheduleForI(I); 9241 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I 9242 << "\n"); 9243 return true; 9244 } 9245 assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && 9246 "Expected to reach top of the basic block or instruction down the " 9247 "lower end."); 9248 assert(I->getParent() == ScheduleEnd->getParent() && 9249 "Instruction is in wrong basic block."); 9250 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion, 9251 nullptr); 9252 ScheduleEnd = I->getNextNode(); 9253 if (isOneOf(S, I) != I) 9254 CheckScheduleForI(I); 9255 assert(ScheduleEnd && "tried to vectorize a terminator?"); 9256 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n"); 9257 return true; 9258 } 9259 9260 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI, 9261 Instruction *ToI, 9262 ScheduleData *PrevLoadStore, 9263 ScheduleData *NextLoadStore) { 9264 ScheduleData *CurrentLoadStore = PrevLoadStore; 9265 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) { 9266 // No need to allocate data for non-schedulable instructions. 9267 if (doesNotNeedToBeScheduled(I)) 9268 continue; 9269 ScheduleData *SD = ScheduleDataMap.lookup(I); 9270 if (!SD) { 9271 SD = allocateScheduleDataChunks(); 9272 ScheduleDataMap[I] = SD; 9273 SD->Inst = I; 9274 } 9275 assert(!isInSchedulingRegion(SD) && 9276 "new ScheduleData already in scheduling region"); 9277 SD->init(SchedulingRegionID, I); 9278 9279 if (I->mayReadOrWriteMemory() && 9280 (!isa<IntrinsicInst>(I) || 9281 (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect && 9282 cast<IntrinsicInst>(I)->getIntrinsicID() != 9283 Intrinsic::pseudoprobe))) { 9284 // Update the linked list of memory accessing instructions. 9285 if (CurrentLoadStore) { 9286 CurrentLoadStore->NextLoadStore = SD; 9287 } else { 9288 FirstLoadStoreInRegion = SD; 9289 } 9290 CurrentLoadStore = SD; 9291 } 9292 9293 if (match(I, m_Intrinsic<Intrinsic::stacksave>()) || 9294 match(I, m_Intrinsic<Intrinsic::stackrestore>())) 9295 RegionHasStackSave = true; 9296 } 9297 if (NextLoadStore) { 9298 if (CurrentLoadStore) 9299 CurrentLoadStore->NextLoadStore = NextLoadStore; 9300 } else { 9301 LastLoadStoreInRegion = CurrentLoadStore; 9302 } 9303 } 9304 9305 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD, 9306 bool InsertInReadyList, 9307 BoUpSLP *SLP) { 9308 assert(SD->isSchedulingEntity()); 9309 9310 SmallVector<ScheduleData *, 10> WorkList; 9311 WorkList.push_back(SD); 9312 9313 while (!WorkList.empty()) { 9314 ScheduleData *SD = WorkList.pop_back_val(); 9315 for (ScheduleData *BundleMember = SD; BundleMember; 9316 BundleMember = BundleMember->NextInBundle) { 9317 assert(isInSchedulingRegion(BundleMember)); 9318 if (BundleMember->hasValidDependencies()) 9319 continue; 9320 9321 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember 9322 << "\n"); 9323 BundleMember->Dependencies = 0; 9324 BundleMember->resetUnscheduledDeps(); 9325 9326 // Handle def-use chain dependencies. 9327 if (BundleMember->OpValue != BundleMember->Inst) { 9328 if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) { 9329 BundleMember->Dependencies++; 9330 ScheduleData *DestBundle = UseSD->FirstInBundle; 9331 if (!DestBundle->IsScheduled) 9332 BundleMember->incrementUnscheduledDeps(1); 9333 if (!DestBundle->hasValidDependencies()) 9334 WorkList.push_back(DestBundle); 9335 } 9336 } else { 9337 for (User *U : BundleMember->Inst->users()) { 9338 if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) { 9339 BundleMember->Dependencies++; 9340 ScheduleData *DestBundle = UseSD->FirstInBundle; 9341 if (!DestBundle->IsScheduled) 9342 BundleMember->incrementUnscheduledDeps(1); 9343 if (!DestBundle->hasValidDependencies()) 9344 WorkList.push_back(DestBundle); 9345 } 9346 } 9347 } 9348 9349 auto makeControlDependent = [&](Instruction *I) { 9350 auto *DepDest = getScheduleData(I); 9351 assert(DepDest && "must be in schedule window"); 9352 DepDest->ControlDependencies.push_back(BundleMember); 9353 BundleMember->Dependencies++; 9354 ScheduleData *DestBundle = DepDest->FirstInBundle; 9355 if (!DestBundle->IsScheduled) 9356 BundleMember->incrementUnscheduledDeps(1); 9357 if (!DestBundle->hasValidDependencies()) 9358 WorkList.push_back(DestBundle); 9359 }; 9360 9361 // Any instruction which isn't safe to speculate at the begining of the 9362 // block is control dependend on any early exit or non-willreturn call 9363 // which proceeds it. 9364 if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) { 9365 for (Instruction *I = BundleMember->Inst->getNextNode(); 9366 I != ScheduleEnd; I = I->getNextNode()) { 9367 if (isSafeToSpeculativelyExecute(I, &*BB->begin())) 9368 continue; 9369 9370 // Add the dependency 9371 makeControlDependent(I); 9372 9373 if (!isGuaranteedToTransferExecutionToSuccessor(I)) 9374 // Everything past here must be control dependent on I. 9375 break; 9376 } 9377 } 9378 9379 if (RegionHasStackSave) { 9380 // If we have an inalloc alloca instruction, it needs to be scheduled 9381 // after any preceeding stacksave. We also need to prevent any alloca 9382 // from reordering above a preceeding stackrestore. 9383 if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) || 9384 match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) { 9385 for (Instruction *I = BundleMember->Inst->getNextNode(); 9386 I != ScheduleEnd; I = I->getNextNode()) { 9387 if (match(I, m_Intrinsic<Intrinsic::stacksave>()) || 9388 match(I, m_Intrinsic<Intrinsic::stackrestore>())) 9389 // Any allocas past here must be control dependent on I, and I 9390 // must be memory dependend on BundleMember->Inst. 9391 break; 9392 9393 if (!isa<AllocaInst>(I)) 9394 continue; 9395 9396 // Add the dependency 9397 makeControlDependent(I); 9398 } 9399 } 9400 9401 // In addition to the cases handle just above, we need to prevent 9402 // allocas from moving below a stacksave. The stackrestore case 9403 // is currently thought to be conservatism. 9404 if (isa<AllocaInst>(BundleMember->Inst)) { 9405 for (Instruction *I = BundleMember->Inst->getNextNode(); 9406 I != ScheduleEnd; I = I->getNextNode()) { 9407 if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) && 9408 !match(I, m_Intrinsic<Intrinsic::stackrestore>())) 9409 continue; 9410 9411 // Add the dependency 9412 makeControlDependent(I); 9413 break; 9414 } 9415 } 9416 } 9417 9418 // Handle the memory dependencies (if any). 9419 ScheduleData *DepDest = BundleMember->NextLoadStore; 9420 if (!DepDest) 9421 continue; 9422 Instruction *SrcInst = BundleMember->Inst; 9423 assert(SrcInst->mayReadOrWriteMemory() && 9424 "NextLoadStore list for non memory effecting bundle?"); 9425 MemoryLocation SrcLoc = getLocation(SrcInst); 9426 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory(); 9427 unsigned numAliased = 0; 9428 unsigned DistToSrc = 1; 9429 9430 for ( ; DepDest; DepDest = DepDest->NextLoadStore) { 9431 assert(isInSchedulingRegion(DepDest)); 9432 9433 // We have two limits to reduce the complexity: 9434 // 1) AliasedCheckLimit: It's a small limit to reduce calls to 9435 // SLP->isAliased (which is the expensive part in this loop). 9436 // 2) MaxMemDepDistance: It's for very large blocks and it aborts 9437 // the whole loop (even if the loop is fast, it's quadratic). 9438 // It's important for the loop break condition (see below) to 9439 // check this limit even between two read-only instructions. 9440 if (DistToSrc >= MaxMemDepDistance || 9441 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) && 9442 (numAliased >= AliasedCheckLimit || 9443 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) { 9444 9445 // We increment the counter only if the locations are aliased 9446 // (instead of counting all alias checks). This gives a better 9447 // balance between reduced runtime and accurate dependencies. 9448 numAliased++; 9449 9450 DepDest->MemoryDependencies.push_back(BundleMember); 9451 BundleMember->Dependencies++; 9452 ScheduleData *DestBundle = DepDest->FirstInBundle; 9453 if (!DestBundle->IsScheduled) { 9454 BundleMember->incrementUnscheduledDeps(1); 9455 } 9456 if (!DestBundle->hasValidDependencies()) { 9457 WorkList.push_back(DestBundle); 9458 } 9459 } 9460 9461 // Example, explaining the loop break condition: Let's assume our 9462 // starting instruction is i0 and MaxMemDepDistance = 3. 9463 // 9464 // +--------v--v--v 9465 // i0,i1,i2,i3,i4,i5,i6,i7,i8 9466 // +--------^--^--^ 9467 // 9468 // MaxMemDepDistance let us stop alias-checking at i3 and we add 9469 // dependencies from i0 to i3,i4,.. (even if they are not aliased). 9470 // Previously we already added dependencies from i3 to i6,i7,i8 9471 // (because of MaxMemDepDistance). As we added a dependency from 9472 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8 9473 // and we can abort this loop at i6. 9474 if (DistToSrc >= 2 * MaxMemDepDistance) 9475 break; 9476 DistToSrc++; 9477 } 9478 } 9479 if (InsertInReadyList && SD->isReady()) { 9480 ReadyInsts.insert(SD); 9481 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst 9482 << "\n"); 9483 } 9484 } 9485 } 9486 9487 void BoUpSLP::BlockScheduling::resetSchedule() { 9488 assert(ScheduleStart && 9489 "tried to reset schedule on block which has not been scheduled"); 9490 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 9491 doForAllOpcodes(I, [&](ScheduleData *SD) { 9492 assert(isInSchedulingRegion(SD) && 9493 "ScheduleData not in scheduling region"); 9494 SD->IsScheduled = false; 9495 SD->resetUnscheduledDeps(); 9496 }); 9497 } 9498 ReadyInsts.clear(); 9499 } 9500 9501 void BoUpSLP::scheduleBlock(BlockScheduling *BS) { 9502 if (!BS->ScheduleStart) 9503 return; 9504 9505 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n"); 9506 9507 // A key point - if we got here, pre-scheduling was able to find a valid 9508 // scheduling of the sub-graph of the scheduling window which consists 9509 // of all vector bundles and their transitive users. As such, we do not 9510 // need to reschedule anything *outside of* that subgraph. 9511 9512 BS->resetSchedule(); 9513 9514 // For the real scheduling we use a more sophisticated ready-list: it is 9515 // sorted by the original instruction location. This lets the final schedule 9516 // be as close as possible to the original instruction order. 9517 // WARNING: If changing this order causes a correctness issue, that means 9518 // there is some missing dependence edge in the schedule data graph. 9519 struct ScheduleDataCompare { 9520 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const { 9521 return SD2->SchedulingPriority < SD1->SchedulingPriority; 9522 } 9523 }; 9524 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts; 9525 9526 // Ensure that all dependency data is updated (for nodes in the sub-graph) 9527 // and fill the ready-list with initial instructions. 9528 int Idx = 0; 9529 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; 9530 I = I->getNextNode()) { 9531 BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) { 9532 TreeEntry *SDTE = getTreeEntry(SD->Inst); 9533 (void)SDTE; 9534 assert((isVectorLikeInstWithConstOps(SD->Inst) || 9535 SD->isPartOfBundle() == 9536 (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) && 9537 "scheduler and vectorizer bundle mismatch"); 9538 SD->FirstInBundle->SchedulingPriority = Idx++; 9539 9540 if (SD->isSchedulingEntity() && SD->isPartOfBundle()) 9541 BS->calculateDependencies(SD, false, this); 9542 }); 9543 } 9544 BS->initialFillReadyList(ReadyInsts); 9545 9546 Instruction *LastScheduledInst = BS->ScheduleEnd; 9547 9548 // Do the "real" scheduling. 9549 while (!ReadyInsts.empty()) { 9550 ScheduleData *picked = *ReadyInsts.begin(); 9551 ReadyInsts.erase(ReadyInsts.begin()); 9552 9553 // Move the scheduled instruction(s) to their dedicated places, if not 9554 // there yet. 9555 for (ScheduleData *BundleMember = picked; BundleMember; 9556 BundleMember = BundleMember->NextInBundle) { 9557 Instruction *pickedInst = BundleMember->Inst; 9558 if (pickedInst->getNextNode() != LastScheduledInst) 9559 pickedInst->moveBefore(LastScheduledInst); 9560 LastScheduledInst = pickedInst; 9561 } 9562 9563 BS->schedule(picked, ReadyInsts); 9564 } 9565 9566 // Check that we didn't break any of our invariants. 9567 #ifdef EXPENSIVE_CHECKS 9568 BS->verify(); 9569 #endif 9570 9571 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS) 9572 // Check that all schedulable entities got scheduled 9573 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) { 9574 BS->doForAllOpcodes(I, [&](ScheduleData *SD) { 9575 if (SD->isSchedulingEntity() && SD->hasValidDependencies()) { 9576 assert(SD->IsScheduled && "must be scheduled at this point"); 9577 } 9578 }); 9579 } 9580 #endif 9581 9582 // Avoid duplicate scheduling of the block. 9583 BS->ScheduleStart = nullptr; 9584 } 9585 9586 unsigned BoUpSLP::getVectorElementSize(Value *V) { 9587 // If V is a store, just return the width of the stored value (or value 9588 // truncated just before storing) without traversing the expression tree. 9589 // This is the common case. 9590 if (auto *Store = dyn_cast<StoreInst>(V)) 9591 return DL->getTypeSizeInBits(Store->getValueOperand()->getType()); 9592 9593 if (auto *IEI = dyn_cast<InsertElementInst>(V)) 9594 return getVectorElementSize(IEI->getOperand(1)); 9595 9596 auto E = InstrElementSize.find(V); 9597 if (E != InstrElementSize.end()) 9598 return E->second; 9599 9600 // If V is not a store, we can traverse the expression tree to find loads 9601 // that feed it. The type of the loaded value may indicate a more suitable 9602 // width than V's type. We want to base the vector element size on the width 9603 // of memory operations where possible. 9604 SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist; 9605 SmallPtrSet<Instruction *, 16> Visited; 9606 if (auto *I = dyn_cast<Instruction>(V)) { 9607 Worklist.emplace_back(I, I->getParent()); 9608 Visited.insert(I); 9609 } 9610 9611 // Traverse the expression tree in bottom-up order looking for loads. If we 9612 // encounter an instruction we don't yet handle, we give up. 9613 auto Width = 0u; 9614 while (!Worklist.empty()) { 9615 Instruction *I; 9616 BasicBlock *Parent; 9617 std::tie(I, Parent) = Worklist.pop_back_val(); 9618 9619 // We should only be looking at scalar instructions here. If the current 9620 // instruction has a vector type, skip. 9621 auto *Ty = I->getType(); 9622 if (isa<VectorType>(Ty)) 9623 continue; 9624 9625 // If the current instruction is a load, update MaxWidth to reflect the 9626 // width of the loaded value. 9627 if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) || 9628 isa<ExtractValueInst>(I)) 9629 Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty)); 9630 9631 // Otherwise, we need to visit the operands of the instruction. We only 9632 // handle the interesting cases from buildTree here. If an operand is an 9633 // instruction we haven't yet visited and from the same basic block as the 9634 // user or the use is a PHI node, we add it to the worklist. 9635 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 9636 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) || 9637 isa<UnaryOperator>(I)) { 9638 for (Use &U : I->operands()) 9639 if (auto *J = dyn_cast<Instruction>(U.get())) 9640 if (Visited.insert(J).second && 9641 (isa<PHINode>(I) || J->getParent() == Parent)) 9642 Worklist.emplace_back(J, J->getParent()); 9643 } else { 9644 break; 9645 } 9646 } 9647 9648 // If we didn't encounter a memory access in the expression tree, or if we 9649 // gave up for some reason, just return the width of V. Otherwise, return the 9650 // maximum width we found. 9651 if (!Width) { 9652 if (auto *CI = dyn_cast<CmpInst>(V)) 9653 V = CI->getOperand(0); 9654 Width = DL->getTypeSizeInBits(V->getType()); 9655 } 9656 9657 for (Instruction *I : Visited) 9658 InstrElementSize[I] = Width; 9659 9660 return Width; 9661 } 9662 9663 // Determine if a value V in a vectorizable expression Expr can be demoted to a 9664 // smaller type with a truncation. We collect the values that will be demoted 9665 // in ToDemote and additional roots that require investigating in Roots. 9666 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr, 9667 SmallVectorImpl<Value *> &ToDemote, 9668 SmallVectorImpl<Value *> &Roots) { 9669 // We can always demote constants. 9670 if (isa<Constant>(V)) { 9671 ToDemote.push_back(V); 9672 return true; 9673 } 9674 9675 // If the value is not an instruction in the expression with only one use, it 9676 // cannot be demoted. 9677 auto *I = dyn_cast<Instruction>(V); 9678 if (!I || !I->hasOneUse() || !Expr.count(I)) 9679 return false; 9680 9681 switch (I->getOpcode()) { 9682 9683 // We can always demote truncations and extensions. Since truncations can 9684 // seed additional demotion, we save the truncated value. 9685 case Instruction::Trunc: 9686 Roots.push_back(I->getOperand(0)); 9687 break; 9688 case Instruction::ZExt: 9689 case Instruction::SExt: 9690 if (isa<ExtractElementInst>(I->getOperand(0)) || 9691 isa<InsertElementInst>(I->getOperand(0))) 9692 return false; 9693 break; 9694 9695 // We can demote certain binary operations if we can demote both of their 9696 // operands. 9697 case Instruction::Add: 9698 case Instruction::Sub: 9699 case Instruction::Mul: 9700 case Instruction::And: 9701 case Instruction::Or: 9702 case Instruction::Xor: 9703 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) || 9704 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots)) 9705 return false; 9706 break; 9707 9708 // We can demote selects if we can demote their true and false values. 9709 case Instruction::Select: { 9710 SelectInst *SI = cast<SelectInst>(I); 9711 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) || 9712 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots)) 9713 return false; 9714 break; 9715 } 9716 9717 // We can demote phis if we can demote all their incoming operands. Note that 9718 // we don't need to worry about cycles since we ensure single use above. 9719 case Instruction::PHI: { 9720 PHINode *PN = cast<PHINode>(I); 9721 for (Value *IncValue : PN->incoming_values()) 9722 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots)) 9723 return false; 9724 break; 9725 } 9726 9727 // Otherwise, conservatively give up. 9728 default: 9729 return false; 9730 } 9731 9732 // Record the value that we can demote. 9733 ToDemote.push_back(V); 9734 return true; 9735 } 9736 9737 void BoUpSLP::computeMinimumValueSizes() { 9738 // If there are no external uses, the expression tree must be rooted by a 9739 // store. We can't demote in-memory values, so there is nothing to do here. 9740 if (ExternalUses.empty()) 9741 return; 9742 9743 // We only attempt to truncate integer expressions. 9744 auto &TreeRoot = VectorizableTree[0]->Scalars; 9745 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType()); 9746 if (!TreeRootIT) 9747 return; 9748 9749 // If the expression is not rooted by a store, these roots should have 9750 // external uses. We will rely on InstCombine to rewrite the expression in 9751 // the narrower type. However, InstCombine only rewrites single-use values. 9752 // This means that if a tree entry other than a root is used externally, it 9753 // must have multiple uses and InstCombine will not rewrite it. The code 9754 // below ensures that only the roots are used externally. 9755 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end()); 9756 for (auto &EU : ExternalUses) 9757 if (!Expr.erase(EU.Scalar)) 9758 return; 9759 if (!Expr.empty()) 9760 return; 9761 9762 // Collect the scalar values of the vectorizable expression. We will use this 9763 // context to determine which values can be demoted. If we see a truncation, 9764 // we mark it as seeding another demotion. 9765 for (auto &EntryPtr : VectorizableTree) 9766 Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end()); 9767 9768 // Ensure the roots of the vectorizable tree don't form a cycle. They must 9769 // have a single external user that is not in the vectorizable tree. 9770 for (auto *Root : TreeRoot) 9771 if (!Root->hasOneUse() || Expr.count(*Root->user_begin())) 9772 return; 9773 9774 // Conservatively determine if we can actually truncate the roots of the 9775 // expression. Collect the values that can be demoted in ToDemote and 9776 // additional roots that require investigating in Roots. 9777 SmallVector<Value *, 32> ToDemote; 9778 SmallVector<Value *, 4> Roots; 9779 for (auto *Root : TreeRoot) 9780 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots)) 9781 return; 9782 9783 // The maximum bit width required to represent all the values that can be 9784 // demoted without loss of precision. It would be safe to truncate the roots 9785 // of the expression to this width. 9786 auto MaxBitWidth = 8u; 9787 9788 // We first check if all the bits of the roots are demanded. If they're not, 9789 // we can truncate the roots to this narrower type. 9790 for (auto *Root : TreeRoot) { 9791 auto Mask = DB->getDemandedBits(cast<Instruction>(Root)); 9792 MaxBitWidth = std::max<unsigned>( 9793 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth); 9794 } 9795 9796 // True if the roots can be zero-extended back to their original type, rather 9797 // than sign-extended. We know that if the leading bits are not demanded, we 9798 // can safely zero-extend. So we initialize IsKnownPositive to True. 9799 bool IsKnownPositive = true; 9800 9801 // If all the bits of the roots are demanded, we can try a little harder to 9802 // compute a narrower type. This can happen, for example, if the roots are 9803 // getelementptr indices. InstCombine promotes these indices to the pointer 9804 // width. Thus, all their bits are technically demanded even though the 9805 // address computation might be vectorized in a smaller type. 9806 // 9807 // We start by looking at each entry that can be demoted. We compute the 9808 // maximum bit width required to store the scalar by using ValueTracking to 9809 // compute the number of high-order bits we can truncate. 9810 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) && 9811 llvm::all_of(TreeRoot, [](Value *R) { 9812 assert(R->hasOneUse() && "Root should have only one use!"); 9813 return isa<GetElementPtrInst>(R->user_back()); 9814 })) { 9815 MaxBitWidth = 8u; 9816 9817 // Determine if the sign bit of all the roots is known to be zero. If not, 9818 // IsKnownPositive is set to False. 9819 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) { 9820 KnownBits Known = computeKnownBits(R, *DL); 9821 return Known.isNonNegative(); 9822 }); 9823 9824 // Determine the maximum number of bits required to store the scalar 9825 // values. 9826 for (auto *Scalar : ToDemote) { 9827 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT); 9828 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType()); 9829 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth); 9830 } 9831 9832 // If we can't prove that the sign bit is zero, we must add one to the 9833 // maximum bit width to account for the unknown sign bit. This preserves 9834 // the existing sign bit so we can safely sign-extend the root back to the 9835 // original type. Otherwise, if we know the sign bit is zero, we will 9836 // zero-extend the root instead. 9837 // 9838 // FIXME: This is somewhat suboptimal, as there will be cases where adding 9839 // one to the maximum bit width will yield a larger-than-necessary 9840 // type. In general, we need to add an extra bit only if we can't 9841 // prove that the upper bit of the original type is equal to the 9842 // upper bit of the proposed smaller type. If these two bits are the 9843 // same (either zero or one) we know that sign-extending from the 9844 // smaller type will result in the same value. Here, since we can't 9845 // yet prove this, we are just making the proposed smaller type 9846 // larger to ensure correctness. 9847 if (!IsKnownPositive) 9848 ++MaxBitWidth; 9849 } 9850 9851 // Round MaxBitWidth up to the next power-of-two. 9852 if (!isPowerOf2_64(MaxBitWidth)) 9853 MaxBitWidth = NextPowerOf2(MaxBitWidth); 9854 9855 // If the maximum bit width we compute is less than the with of the roots' 9856 // type, we can proceed with the narrowing. Otherwise, do nothing. 9857 if (MaxBitWidth >= TreeRootIT->getBitWidth()) 9858 return; 9859 9860 // If we can truncate the root, we must collect additional values that might 9861 // be demoted as a result. That is, those seeded by truncations we will 9862 // modify. 9863 while (!Roots.empty()) 9864 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots); 9865 9866 // Finally, map the values we can demote to the maximum bit with we computed. 9867 for (auto *Scalar : ToDemote) 9868 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive); 9869 } 9870 9871 namespace { 9872 9873 /// The SLPVectorizer Pass. 9874 struct SLPVectorizer : public FunctionPass { 9875 SLPVectorizerPass Impl; 9876 9877 /// Pass identification, replacement for typeid 9878 static char ID; 9879 9880 explicit SLPVectorizer() : FunctionPass(ID) { 9881 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); 9882 } 9883 9884 bool doInitialization(Module &M) override { return false; } 9885 9886 bool runOnFunction(Function &F) override { 9887 if (skipFunction(F)) 9888 return false; 9889 9890 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 9891 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 9892 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 9893 auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr; 9894 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 9895 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 9896 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 9897 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 9898 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); 9899 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 9900 9901 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 9902 } 9903 9904 void getAnalysisUsage(AnalysisUsage &AU) const override { 9905 FunctionPass::getAnalysisUsage(AU); 9906 AU.addRequired<AssumptionCacheTracker>(); 9907 AU.addRequired<ScalarEvolutionWrapperPass>(); 9908 AU.addRequired<AAResultsWrapperPass>(); 9909 AU.addRequired<TargetTransformInfoWrapperPass>(); 9910 AU.addRequired<LoopInfoWrapperPass>(); 9911 AU.addRequired<DominatorTreeWrapperPass>(); 9912 AU.addRequired<DemandedBitsWrapperPass>(); 9913 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 9914 AU.addRequired<InjectTLIMappingsLegacy>(); 9915 AU.addPreserved<LoopInfoWrapperPass>(); 9916 AU.addPreserved<DominatorTreeWrapperPass>(); 9917 AU.addPreserved<AAResultsWrapperPass>(); 9918 AU.addPreserved<GlobalsAAWrapperPass>(); 9919 AU.setPreservesCFG(); 9920 } 9921 }; 9922 9923 } // end anonymous namespace 9924 9925 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) { 9926 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 9927 auto *TTI = &AM.getResult<TargetIRAnalysis>(F); 9928 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F); 9929 auto *AA = &AM.getResult<AAManager>(F); 9930 auto *LI = &AM.getResult<LoopAnalysis>(F); 9931 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 9932 auto *AC = &AM.getResult<AssumptionAnalysis>(F); 9933 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F); 9934 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 9935 9936 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 9937 if (!Changed) 9938 return PreservedAnalyses::all(); 9939 9940 PreservedAnalyses PA; 9941 PA.preserveSet<CFGAnalyses>(); 9942 return PA; 9943 } 9944 9945 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_, 9946 TargetTransformInfo *TTI_, 9947 TargetLibraryInfo *TLI_, AAResults *AA_, 9948 LoopInfo *LI_, DominatorTree *DT_, 9949 AssumptionCache *AC_, DemandedBits *DB_, 9950 OptimizationRemarkEmitter *ORE_) { 9951 if (!RunSLPVectorization) 9952 return false; 9953 SE = SE_; 9954 TTI = TTI_; 9955 TLI = TLI_; 9956 AA = AA_; 9957 LI = LI_; 9958 DT = DT_; 9959 AC = AC_; 9960 DB = DB_; 9961 DL = &F.getParent()->getDataLayout(); 9962 9963 Stores.clear(); 9964 GEPs.clear(); 9965 bool Changed = false; 9966 9967 // If the target claims to have no vector registers don't attempt 9968 // vectorization. 9969 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) { 9970 LLVM_DEBUG( 9971 dbgs() << "SLP: Didn't find any vector registers for target, abort.\n"); 9972 return false; 9973 } 9974 9975 // Don't vectorize when the attribute NoImplicitFloat is used. 9976 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) 9977 return false; 9978 9979 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"); 9980 9981 // Use the bottom up slp vectorizer to construct chains that start with 9982 // store instructions. 9983 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_); 9984 9985 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to 9986 // delete instructions. 9987 9988 // Update DFS numbers now so that we can use them for ordering. 9989 DT->updateDFSNumbers(); 9990 9991 // Scan the blocks in the function in post order. 9992 for (auto BB : post_order(&F.getEntryBlock())) { 9993 // Start new block - clear the list of reduction roots. 9994 R.clearReductionData(); 9995 collectSeedInstructions(BB); 9996 9997 // Vectorize trees that end at stores. 9998 if (!Stores.empty()) { 9999 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size() 10000 << " underlying objects.\n"); 10001 Changed |= vectorizeStoreChains(R); 10002 } 10003 10004 // Vectorize trees that end at reductions. 10005 Changed |= vectorizeChainsInBlock(BB, R); 10006 10007 // Vectorize the index computations of getelementptr instructions. This 10008 // is primarily intended to catch gather-like idioms ending at 10009 // non-consecutive loads. 10010 if (!GEPs.empty()) { 10011 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size() 10012 << " underlying objects.\n"); 10013 Changed |= vectorizeGEPIndices(BB, R); 10014 } 10015 } 10016 10017 if (Changed) { 10018 R.optimizeGatherSequence(); 10019 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n"); 10020 } 10021 return Changed; 10022 } 10023 10024 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R, 10025 unsigned Idx, unsigned MinVF) { 10026 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size() 10027 << "\n"); 10028 const unsigned Sz = R.getVectorElementSize(Chain[0]); 10029 unsigned VF = Chain.size(); 10030 10031 if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF) 10032 return false; 10033 10034 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx 10035 << "\n"); 10036 10037 R.buildTree(Chain); 10038 if (R.isTreeTinyAndNotFullyVectorizable()) 10039 return false; 10040 if (R.isLoadCombineCandidate()) 10041 return false; 10042 R.reorderTopToBottom(); 10043 R.reorderBottomToTop(); 10044 R.buildExternalUses(); 10045 10046 R.computeMinimumValueSizes(); 10047 10048 InstructionCost Cost = R.getTreeCost(); 10049 10050 LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n"); 10051 if (Cost < -SLPCostThreshold) { 10052 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n"); 10053 10054 using namespace ore; 10055 10056 R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized", 10057 cast<StoreInst>(Chain[0])) 10058 << "Stores SLP vectorized with cost " << NV("Cost", Cost) 10059 << " and with tree size " 10060 << NV("TreeSize", R.getTreeSize())); 10061 10062 R.vectorizeTree(); 10063 return true; 10064 } 10065 10066 return false; 10067 } 10068 10069 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores, 10070 BoUpSLP &R) { 10071 // We may run into multiple chains that merge into a single chain. We mark the 10072 // stores that we vectorized so that we don't visit the same store twice. 10073 BoUpSLP::ValueSet VectorizedStores; 10074 bool Changed = false; 10075 10076 int E = Stores.size(); 10077 SmallBitVector Tails(E, false); 10078 int MaxIter = MaxStoreLookup.getValue(); 10079 SmallVector<std::pair<int, int>, 16> ConsecutiveChain( 10080 E, std::make_pair(E, INT_MAX)); 10081 SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false)); 10082 int IterCnt; 10083 auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter, 10084 &CheckedPairs, 10085 &ConsecutiveChain](int K, int Idx) { 10086 if (IterCnt >= MaxIter) 10087 return true; 10088 if (CheckedPairs[Idx].test(K)) 10089 return ConsecutiveChain[K].second == 1 && 10090 ConsecutiveChain[K].first == Idx; 10091 ++IterCnt; 10092 CheckedPairs[Idx].set(K); 10093 CheckedPairs[K].set(Idx); 10094 Optional<int> Diff = getPointersDiff( 10095 Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(), 10096 Stores[Idx]->getValueOperand()->getType(), 10097 Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true); 10098 if (!Diff || *Diff == 0) 10099 return false; 10100 int Val = *Diff; 10101 if (Val < 0) { 10102 if (ConsecutiveChain[Idx].second > -Val) { 10103 Tails.set(K); 10104 ConsecutiveChain[Idx] = std::make_pair(K, -Val); 10105 } 10106 return false; 10107 } 10108 if (ConsecutiveChain[K].second <= Val) 10109 return false; 10110 10111 Tails.set(Idx); 10112 ConsecutiveChain[K] = std::make_pair(Idx, Val); 10113 return Val == 1; 10114 }; 10115 // Do a quadratic search on all of the given stores in reverse order and find 10116 // all of the pairs of stores that follow each other. 10117 for (int Idx = E - 1; Idx >= 0; --Idx) { 10118 // If a store has multiple consecutive store candidates, search according 10119 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ... 10120 // This is because usually pairing with immediate succeeding or preceding 10121 // candidate create the best chance to find slp vectorization opportunity. 10122 const int MaxLookDepth = std::max(E - Idx, Idx + 1); 10123 IterCnt = 0; 10124 for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset) 10125 if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) || 10126 (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx))) 10127 break; 10128 } 10129 10130 // Tracks if we tried to vectorize stores starting from the given tail 10131 // already. 10132 SmallBitVector TriedTails(E, false); 10133 // For stores that start but don't end a link in the chain: 10134 for (int Cnt = E; Cnt > 0; --Cnt) { 10135 int I = Cnt - 1; 10136 if (ConsecutiveChain[I].first == E || Tails.test(I)) 10137 continue; 10138 // We found a store instr that starts a chain. Now follow the chain and try 10139 // to vectorize it. 10140 BoUpSLP::ValueList Operands; 10141 // Collect the chain into a list. 10142 while (I != E && !VectorizedStores.count(Stores[I])) { 10143 Operands.push_back(Stores[I]); 10144 Tails.set(I); 10145 if (ConsecutiveChain[I].second != 1) { 10146 // Mark the new end in the chain and go back, if required. It might be 10147 // required if the original stores come in reversed order, for example. 10148 if (ConsecutiveChain[I].first != E && 10149 Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) && 10150 !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) { 10151 TriedTails.set(I); 10152 Tails.reset(ConsecutiveChain[I].first); 10153 if (Cnt < ConsecutiveChain[I].first + 2) 10154 Cnt = ConsecutiveChain[I].first + 2; 10155 } 10156 break; 10157 } 10158 // Move to the next value in the chain. 10159 I = ConsecutiveChain[I].first; 10160 } 10161 assert(!Operands.empty() && "Expected non-empty list of stores."); 10162 10163 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 10164 unsigned EltSize = R.getVectorElementSize(Operands[0]); 10165 unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize); 10166 10167 unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store), 10168 MaxElts); 10169 auto *Store = cast<StoreInst>(Operands[0]); 10170 Type *StoreTy = Store->getValueOperand()->getType(); 10171 Type *ValueTy = StoreTy; 10172 if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand())) 10173 ValueTy = Trunc->getSrcTy(); 10174 unsigned MinVF = TTI->getStoreMinimumVF( 10175 R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy); 10176 10177 // FIXME: Is division-by-2 the correct step? Should we assert that the 10178 // register size is a power-of-2? 10179 unsigned StartIdx = 0; 10180 for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) { 10181 for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) { 10182 ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size); 10183 if (!VectorizedStores.count(Slice.front()) && 10184 !VectorizedStores.count(Slice.back()) && 10185 vectorizeStoreChain(Slice, R, Cnt, MinVF)) { 10186 // Mark the vectorized stores so that we don't vectorize them again. 10187 VectorizedStores.insert(Slice.begin(), Slice.end()); 10188 Changed = true; 10189 // If we vectorized initial block, no need to try to vectorize it 10190 // again. 10191 if (Cnt == StartIdx) 10192 StartIdx += Size; 10193 Cnt += Size; 10194 continue; 10195 } 10196 ++Cnt; 10197 } 10198 // Check if the whole array was vectorized already - exit. 10199 if (StartIdx >= Operands.size()) 10200 break; 10201 } 10202 } 10203 10204 return Changed; 10205 } 10206 10207 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) { 10208 // Initialize the collections. We will make a single pass over the block. 10209 Stores.clear(); 10210 GEPs.clear(); 10211 10212 // Visit the store and getelementptr instructions in BB and organize them in 10213 // Stores and GEPs according to the underlying objects of their pointer 10214 // operands. 10215 for (Instruction &I : *BB) { 10216 // Ignore store instructions that are volatile or have a pointer operand 10217 // that doesn't point to a scalar type. 10218 if (auto *SI = dyn_cast<StoreInst>(&I)) { 10219 if (!SI->isSimple()) 10220 continue; 10221 if (!isValidElementType(SI->getValueOperand()->getType())) 10222 continue; 10223 Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI); 10224 } 10225 10226 // Ignore getelementptr instructions that have more than one index, a 10227 // constant index, or a pointer operand that doesn't point to a scalar 10228 // type. 10229 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 10230 auto Idx = GEP->idx_begin()->get(); 10231 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx)) 10232 continue; 10233 if (!isValidElementType(Idx->getType())) 10234 continue; 10235 if (GEP->getType()->isVectorTy()) 10236 continue; 10237 GEPs[GEP->getPointerOperand()].push_back(GEP); 10238 } 10239 } 10240 } 10241 10242 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { 10243 if (!A || !B) 10244 return false; 10245 if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B)) 10246 return false; 10247 Value *VL[] = {A, B}; 10248 return tryToVectorizeList(VL, R); 10249 } 10250 10251 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, 10252 bool LimitForRegisterSize) { 10253 if (VL.size() < 2) 10254 return false; 10255 10256 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " 10257 << VL.size() << ".\n"); 10258 10259 // Check that all of the parts are instructions of the same type, 10260 // we permit an alternate opcode via InstructionsState. 10261 InstructionsState S = getSameOpcode(VL); 10262 if (!S.getOpcode()) 10263 return false; 10264 10265 Instruction *I0 = cast<Instruction>(S.OpValue); 10266 // Make sure invalid types (including vector type) are rejected before 10267 // determining vectorization factor for scalar instructions. 10268 for (Value *V : VL) { 10269 Type *Ty = V->getType(); 10270 if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) { 10271 // NOTE: the following will give user internal llvm type name, which may 10272 // not be useful. 10273 R.getORE()->emit([&]() { 10274 std::string type_str; 10275 llvm::raw_string_ostream rso(type_str); 10276 Ty->print(rso); 10277 return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0) 10278 << "Cannot SLP vectorize list: type " 10279 << rso.str() + " is unsupported by vectorizer"; 10280 }); 10281 return false; 10282 } 10283 } 10284 10285 unsigned Sz = R.getVectorElementSize(I0); 10286 unsigned MinVF = R.getMinVF(Sz); 10287 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF); 10288 MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF); 10289 if (MaxVF < 2) { 10290 R.getORE()->emit([&]() { 10291 return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0) 10292 << "Cannot SLP vectorize list: vectorization factor " 10293 << "less than 2 is not supported"; 10294 }); 10295 return false; 10296 } 10297 10298 bool Changed = false; 10299 bool CandidateFound = false; 10300 InstructionCost MinCost = SLPCostThreshold.getValue(); 10301 Type *ScalarTy = VL[0]->getType(); 10302 if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 10303 ScalarTy = IE->getOperand(1)->getType(); 10304 10305 unsigned NextInst = 0, MaxInst = VL.size(); 10306 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) { 10307 // No actual vectorization should happen, if number of parts is the same as 10308 // provided vectorization factor (i.e. the scalar type is used for vector 10309 // code during codegen). 10310 auto *VecTy = FixedVectorType::get(ScalarTy, VF); 10311 if (TTI->getNumberOfParts(VecTy) == VF) 10312 continue; 10313 for (unsigned I = NextInst; I < MaxInst; ++I) { 10314 unsigned OpsWidth = 0; 10315 10316 if (I + VF > MaxInst) 10317 OpsWidth = MaxInst - I; 10318 else 10319 OpsWidth = VF; 10320 10321 if (!isPowerOf2_32(OpsWidth)) 10322 continue; 10323 10324 if ((LimitForRegisterSize && OpsWidth < MaxVF) || 10325 (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2)) 10326 break; 10327 10328 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth); 10329 // Check that a previous iteration of this loop did not delete the Value. 10330 if (llvm::any_of(Ops, [&R](Value *V) { 10331 auto *I = dyn_cast<Instruction>(V); 10332 return I && R.isDeleted(I); 10333 })) 10334 continue; 10335 10336 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " 10337 << "\n"); 10338 10339 R.buildTree(Ops); 10340 if (R.isTreeTinyAndNotFullyVectorizable()) 10341 continue; 10342 R.reorderTopToBottom(); 10343 R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front())); 10344 R.buildExternalUses(); 10345 10346 R.computeMinimumValueSizes(); 10347 InstructionCost Cost = R.getTreeCost(); 10348 CandidateFound = true; 10349 MinCost = std::min(MinCost, Cost); 10350 10351 if (Cost < -SLPCostThreshold) { 10352 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n"); 10353 R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList", 10354 cast<Instruction>(Ops[0])) 10355 << "SLP vectorized with cost " << ore::NV("Cost", Cost) 10356 << " and with tree size " 10357 << ore::NV("TreeSize", R.getTreeSize())); 10358 10359 R.vectorizeTree(); 10360 // Move to the next bundle. 10361 I += VF - 1; 10362 NextInst = I + 1; 10363 Changed = true; 10364 } 10365 } 10366 } 10367 10368 if (!Changed && CandidateFound) { 10369 R.getORE()->emit([&]() { 10370 return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0) 10371 << "List vectorization was possible but not beneficial with cost " 10372 << ore::NV("Cost", MinCost) << " >= " 10373 << ore::NV("Treshold", -SLPCostThreshold); 10374 }); 10375 } else if (!Changed) { 10376 R.getORE()->emit([&]() { 10377 return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0) 10378 << "Cannot SLP vectorize list: vectorization was impossible" 10379 << " with available vectorization factors"; 10380 }); 10381 } 10382 return Changed; 10383 } 10384 10385 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) { 10386 if (!I) 10387 return false; 10388 10389 if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) || 10390 isa<VectorType>(I->getType())) 10391 return false; 10392 10393 Value *P = I->getParent(); 10394 10395 // Vectorize in current basic block only. 10396 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0)); 10397 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1)); 10398 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P) 10399 return false; 10400 10401 // First collect all possible candidates 10402 SmallVector<std::pair<Value *, Value *>, 4> Candidates; 10403 Candidates.emplace_back(Op0, Op1); 10404 10405 auto *A = dyn_cast<BinaryOperator>(Op0); 10406 auto *B = dyn_cast<BinaryOperator>(Op1); 10407 // Try to skip B. 10408 if (A && B && B->hasOneUse()) { 10409 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); 10410 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); 10411 if (B0 && B0->getParent() == P) 10412 Candidates.emplace_back(A, B0); 10413 if (B1 && B1->getParent() == P) 10414 Candidates.emplace_back(A, B1); 10415 } 10416 // Try to skip A. 10417 if (B && A && A->hasOneUse()) { 10418 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); 10419 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); 10420 if (A0 && A0->getParent() == P) 10421 Candidates.emplace_back(A0, B); 10422 if (A1 && A1->getParent() == P) 10423 Candidates.emplace_back(A1, B); 10424 } 10425 10426 if (Candidates.size() == 1) 10427 return tryToVectorizePair(Op0, Op1, R); 10428 10429 // We have multiple options. Try to pick the single best. 10430 Optional<int> BestCandidate = R.findBestRootPair(Candidates); 10431 if (!BestCandidate) 10432 return false; 10433 return tryToVectorizePair(Candidates[*BestCandidate].first, 10434 Candidates[*BestCandidate].second, R); 10435 } 10436 10437 namespace { 10438 10439 /// Model horizontal reductions. 10440 /// 10441 /// A horizontal reduction is a tree of reduction instructions that has values 10442 /// that can be put into a vector as its leaves. For example: 10443 /// 10444 /// mul mul mul mul 10445 /// \ / \ / 10446 /// + + 10447 /// \ / 10448 /// + 10449 /// This tree has "mul" as its leaf values and "+" as its reduction 10450 /// instructions. A reduction can feed into a store or a binary operation 10451 /// feeding a phi. 10452 /// ... 10453 /// \ / 10454 /// + 10455 /// | 10456 /// phi += 10457 /// 10458 /// Or: 10459 /// ... 10460 /// \ / 10461 /// + 10462 /// | 10463 /// *p = 10464 /// 10465 class HorizontalReduction { 10466 using ReductionOpsType = SmallVector<Value *, 16>; 10467 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>; 10468 ReductionOpsListType ReductionOps; 10469 /// List of possibly reduced values. 10470 SmallVector<SmallVector<Value *>> ReducedVals; 10471 /// Maps reduced value to the corresponding reduction operation. 10472 DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps; 10473 // Use map vector to make stable output. 10474 MapVector<Instruction *, Value *> ExtraArgs; 10475 WeakTrackingVH ReductionRoot; 10476 /// The type of reduction operation. 10477 RecurKind RdxKind; 10478 10479 static bool isCmpSelMinMax(Instruction *I) { 10480 return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) && 10481 RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I)); 10482 } 10483 10484 // And/or are potentially poison-safe logical patterns like: 10485 // select x, y, false 10486 // select x, true, y 10487 static bool isBoolLogicOp(Instruction *I) { 10488 return match(I, m_LogicalAnd(m_Value(), m_Value())) || 10489 match(I, m_LogicalOr(m_Value(), m_Value())); 10490 } 10491 10492 /// Checks if instruction is associative and can be vectorized. 10493 static bool isVectorizable(RecurKind Kind, Instruction *I) { 10494 if (Kind == RecurKind::None) 10495 return false; 10496 10497 // Integer ops that map to select instructions or intrinsics are fine. 10498 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) || 10499 isBoolLogicOp(I)) 10500 return true; 10501 10502 if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) { 10503 // FP min/max are associative except for NaN and -0.0. We do not 10504 // have to rule out -0.0 here because the intrinsic semantics do not 10505 // specify a fixed result for it. 10506 return I->getFastMathFlags().noNaNs(); 10507 } 10508 10509 return I->isAssociative(); 10510 } 10511 10512 static Value *getRdxOperand(Instruction *I, unsigned Index) { 10513 // Poison-safe 'or' takes the form: select X, true, Y 10514 // To make that work with the normal operand processing, we skip the 10515 // true value operand. 10516 // TODO: Change the code and data structures to handle this without a hack. 10517 if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1) 10518 return I->getOperand(2); 10519 return I->getOperand(Index); 10520 } 10521 10522 /// Creates reduction operation with the current opcode. 10523 static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS, 10524 Value *RHS, const Twine &Name, bool UseSelect) { 10525 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind); 10526 switch (Kind) { 10527 case RecurKind::Or: 10528 if (UseSelect && 10529 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 10530 return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name); 10531 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 10532 Name); 10533 case RecurKind::And: 10534 if (UseSelect && 10535 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 10536 return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name); 10537 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 10538 Name); 10539 case RecurKind::Add: 10540 case RecurKind::Mul: 10541 case RecurKind::Xor: 10542 case RecurKind::FAdd: 10543 case RecurKind::FMul: 10544 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 10545 Name); 10546 case RecurKind::FMax: 10547 return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS); 10548 case RecurKind::FMin: 10549 return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS); 10550 case RecurKind::SMax: 10551 if (UseSelect) { 10552 Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name); 10553 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 10554 } 10555 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS); 10556 case RecurKind::SMin: 10557 if (UseSelect) { 10558 Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name); 10559 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 10560 } 10561 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS); 10562 case RecurKind::UMax: 10563 if (UseSelect) { 10564 Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name); 10565 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 10566 } 10567 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS); 10568 case RecurKind::UMin: 10569 if (UseSelect) { 10570 Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name); 10571 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 10572 } 10573 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS); 10574 default: 10575 llvm_unreachable("Unknown reduction operation."); 10576 } 10577 } 10578 10579 /// Creates reduction operation with the current opcode with the IR flags 10580 /// from \p ReductionOps, dropping nuw/nsw flags. 10581 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 10582 Value *RHS, const Twine &Name, 10583 const ReductionOpsListType &ReductionOps) { 10584 bool UseSelect = ReductionOps.size() == 2 || 10585 // Logical or/and. 10586 (ReductionOps.size() == 1 && 10587 isa<SelectInst>(ReductionOps.front().front())); 10588 assert((!UseSelect || ReductionOps.size() != 2 || 10589 isa<SelectInst>(ReductionOps[1][0])) && 10590 "Expected cmp + select pairs for reduction"); 10591 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect); 10592 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 10593 if (auto *Sel = dyn_cast<SelectInst>(Op)) { 10594 propagateIRFlags(Sel->getCondition(), ReductionOps[0], nullptr, 10595 /*IncludeWrapFlags=*/false); 10596 propagateIRFlags(Op, ReductionOps[1], nullptr, 10597 /*IncludeWrapFlags=*/false); 10598 return Op; 10599 } 10600 } 10601 propagateIRFlags(Op, ReductionOps[0], nullptr, /*IncludeWrapFlags=*/false); 10602 return Op; 10603 } 10604 10605 static RecurKind getRdxKind(Value *V) { 10606 auto *I = dyn_cast<Instruction>(V); 10607 if (!I) 10608 return RecurKind::None; 10609 if (match(I, m_Add(m_Value(), m_Value()))) 10610 return RecurKind::Add; 10611 if (match(I, m_Mul(m_Value(), m_Value()))) 10612 return RecurKind::Mul; 10613 if (match(I, m_And(m_Value(), m_Value())) || 10614 match(I, m_LogicalAnd(m_Value(), m_Value()))) 10615 return RecurKind::And; 10616 if (match(I, m_Or(m_Value(), m_Value())) || 10617 match(I, m_LogicalOr(m_Value(), m_Value()))) 10618 return RecurKind::Or; 10619 if (match(I, m_Xor(m_Value(), m_Value()))) 10620 return RecurKind::Xor; 10621 if (match(I, m_FAdd(m_Value(), m_Value()))) 10622 return RecurKind::FAdd; 10623 if (match(I, m_FMul(m_Value(), m_Value()))) 10624 return RecurKind::FMul; 10625 10626 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value()))) 10627 return RecurKind::FMax; 10628 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value()))) 10629 return RecurKind::FMin; 10630 10631 // This matches either cmp+select or intrinsics. SLP is expected to handle 10632 // either form. 10633 // TODO: If we are canonicalizing to intrinsics, we can remove several 10634 // special-case paths that deal with selects. 10635 if (match(I, m_SMax(m_Value(), m_Value()))) 10636 return RecurKind::SMax; 10637 if (match(I, m_SMin(m_Value(), m_Value()))) 10638 return RecurKind::SMin; 10639 if (match(I, m_UMax(m_Value(), m_Value()))) 10640 return RecurKind::UMax; 10641 if (match(I, m_UMin(m_Value(), m_Value()))) 10642 return RecurKind::UMin; 10643 10644 if (auto *Select = dyn_cast<SelectInst>(I)) { 10645 // Try harder: look for min/max pattern based on instructions producing 10646 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2). 10647 // During the intermediate stages of SLP, it's very common to have 10648 // pattern like this (since optimizeGatherSequence is run only once 10649 // at the end): 10650 // %1 = extractelement <2 x i32> %a, i32 0 10651 // %2 = extractelement <2 x i32> %a, i32 1 10652 // %cond = icmp sgt i32 %1, %2 10653 // %3 = extractelement <2 x i32> %a, i32 0 10654 // %4 = extractelement <2 x i32> %a, i32 1 10655 // %select = select i1 %cond, i32 %3, i32 %4 10656 CmpInst::Predicate Pred; 10657 Instruction *L1; 10658 Instruction *L2; 10659 10660 Value *LHS = Select->getTrueValue(); 10661 Value *RHS = Select->getFalseValue(); 10662 Value *Cond = Select->getCondition(); 10663 10664 // TODO: Support inverse predicates. 10665 if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) { 10666 if (!isa<ExtractElementInst>(RHS) || 10667 !L2->isIdenticalTo(cast<Instruction>(RHS))) 10668 return RecurKind::None; 10669 } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) { 10670 if (!isa<ExtractElementInst>(LHS) || 10671 !L1->isIdenticalTo(cast<Instruction>(LHS))) 10672 return RecurKind::None; 10673 } else { 10674 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS)) 10675 return RecurKind::None; 10676 if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) || 10677 !L1->isIdenticalTo(cast<Instruction>(LHS)) || 10678 !L2->isIdenticalTo(cast<Instruction>(RHS))) 10679 return RecurKind::None; 10680 } 10681 10682 switch (Pred) { 10683 default: 10684 return RecurKind::None; 10685 case CmpInst::ICMP_SGT: 10686 case CmpInst::ICMP_SGE: 10687 return RecurKind::SMax; 10688 case CmpInst::ICMP_SLT: 10689 case CmpInst::ICMP_SLE: 10690 return RecurKind::SMin; 10691 case CmpInst::ICMP_UGT: 10692 case CmpInst::ICMP_UGE: 10693 return RecurKind::UMax; 10694 case CmpInst::ICMP_ULT: 10695 case CmpInst::ICMP_ULE: 10696 return RecurKind::UMin; 10697 } 10698 } 10699 return RecurKind::None; 10700 } 10701 10702 /// Get the index of the first operand. 10703 static unsigned getFirstOperandIndex(Instruction *I) { 10704 return isCmpSelMinMax(I) ? 1 : 0; 10705 } 10706 10707 /// Total number of operands in the reduction operation. 10708 static unsigned getNumberOfOperands(Instruction *I) { 10709 return isCmpSelMinMax(I) ? 3 : 2; 10710 } 10711 10712 /// Checks if the instruction is in basic block \p BB. 10713 /// For a cmp+sel min/max reduction check that both ops are in \p BB. 10714 static bool hasSameParent(Instruction *I, BasicBlock *BB) { 10715 if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) { 10716 auto *Sel = cast<SelectInst>(I); 10717 auto *Cmp = dyn_cast<Instruction>(Sel->getCondition()); 10718 return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB; 10719 } 10720 return I->getParent() == BB; 10721 } 10722 10723 /// Expected number of uses for reduction operations/reduced values. 10724 static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) { 10725 if (IsCmpSelMinMax) { 10726 // SelectInst must be used twice while the condition op must have single 10727 // use only. 10728 if (auto *Sel = dyn_cast<SelectInst>(I)) 10729 return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse(); 10730 return I->hasNUses(2); 10731 } 10732 10733 // Arithmetic reduction operation must be used once only. 10734 return I->hasOneUse(); 10735 } 10736 10737 /// Initializes the list of reduction operations. 10738 void initReductionOps(Instruction *I) { 10739 if (isCmpSelMinMax(I)) 10740 ReductionOps.assign(2, ReductionOpsType()); 10741 else 10742 ReductionOps.assign(1, ReductionOpsType()); 10743 } 10744 10745 /// Add all reduction operations for the reduction instruction \p I. 10746 void addReductionOps(Instruction *I) { 10747 if (isCmpSelMinMax(I)) { 10748 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition()); 10749 ReductionOps[1].emplace_back(I); 10750 } else { 10751 ReductionOps[0].emplace_back(I); 10752 } 10753 } 10754 10755 static Value *getLHS(RecurKind Kind, Instruction *I) { 10756 if (Kind == RecurKind::None) 10757 return nullptr; 10758 return I->getOperand(getFirstOperandIndex(I)); 10759 } 10760 static Value *getRHS(RecurKind Kind, Instruction *I) { 10761 if (Kind == RecurKind::None) 10762 return nullptr; 10763 return I->getOperand(getFirstOperandIndex(I) + 1); 10764 } 10765 10766 public: 10767 HorizontalReduction() = default; 10768 10769 /// Try to find a reduction tree. 10770 bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst, 10771 ScalarEvolution &SE, const DataLayout &DL, 10772 const TargetLibraryInfo &TLI) { 10773 assert((!Phi || is_contained(Phi->operands(), Inst)) && 10774 "Phi needs to use the binary operator"); 10775 assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || 10776 isa<IntrinsicInst>(Inst)) && 10777 "Expected binop, select, or intrinsic for reduction matching"); 10778 RdxKind = getRdxKind(Inst); 10779 10780 // We could have a initial reductions that is not an add. 10781 // r *= v1 + v2 + v3 + v4 10782 // In such a case start looking for a tree rooted in the first '+'. 10783 if (Phi) { 10784 if (getLHS(RdxKind, Inst) == Phi) { 10785 Phi = nullptr; 10786 Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst)); 10787 if (!Inst) 10788 return false; 10789 RdxKind = getRdxKind(Inst); 10790 } else if (getRHS(RdxKind, Inst) == Phi) { 10791 Phi = nullptr; 10792 Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst)); 10793 if (!Inst) 10794 return false; 10795 RdxKind = getRdxKind(Inst); 10796 } 10797 } 10798 10799 if (!isVectorizable(RdxKind, Inst)) 10800 return false; 10801 10802 // Analyze "regular" integer/FP types for reductions - no target-specific 10803 // types or pointers. 10804 Type *Ty = Inst->getType(); 10805 if (!isValidElementType(Ty) || Ty->isPointerTy()) 10806 return false; 10807 10808 // Though the ultimate reduction may have multiple uses, its condition must 10809 // have only single use. 10810 if (auto *Sel = dyn_cast<SelectInst>(Inst)) 10811 if (!Sel->getCondition()->hasOneUse()) 10812 return false; 10813 10814 ReductionRoot = Inst; 10815 10816 // Iterate through all the operands of the possible reduction tree and 10817 // gather all the reduced values, sorting them by their value id. 10818 BasicBlock *BB = Inst->getParent(); 10819 bool IsCmpSelMinMax = isCmpSelMinMax(Inst); 10820 SmallVector<Instruction *> Worklist(1, Inst); 10821 // Checks if the operands of the \p TreeN instruction are also reduction 10822 // operations or should be treated as reduced values or an extra argument, 10823 // which is not part of the reduction. 10824 auto &&CheckOperands = [this, IsCmpSelMinMax, 10825 BB](Instruction *TreeN, 10826 SmallVectorImpl<Value *> &ExtraArgs, 10827 SmallVectorImpl<Value *> &PossibleReducedVals, 10828 SmallVectorImpl<Instruction *> &ReductionOps) { 10829 for (int I = getFirstOperandIndex(TreeN), 10830 End = getNumberOfOperands(TreeN); 10831 I < End; ++I) { 10832 Value *EdgeVal = getRdxOperand(TreeN, I); 10833 ReducedValsToOps[EdgeVal].push_back(TreeN); 10834 auto *EdgeInst = dyn_cast<Instruction>(EdgeVal); 10835 // Edge has wrong parent - mark as an extra argument. 10836 if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) && 10837 !hasSameParent(EdgeInst, BB)) { 10838 ExtraArgs.push_back(EdgeVal); 10839 continue; 10840 } 10841 // If the edge is not an instruction, or it is different from the main 10842 // reduction opcode or has too many uses - possible reduced value. 10843 if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind || 10844 IsCmpSelMinMax != isCmpSelMinMax(EdgeInst) || 10845 !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) || 10846 !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) { 10847 PossibleReducedVals.push_back(EdgeVal); 10848 continue; 10849 } 10850 ReductionOps.push_back(EdgeInst); 10851 } 10852 }; 10853 // Try to regroup reduced values so that it gets more profitable to try to 10854 // reduce them. Values are grouped by their value ids, instructions - by 10855 // instruction op id and/or alternate op id, plus do extra analysis for 10856 // loads (grouping them by the distabce between pointers) and cmp 10857 // instructions (grouping them by the predicate). 10858 MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>> 10859 PossibleReducedVals; 10860 initReductionOps(Inst); 10861 while (!Worklist.empty()) { 10862 Instruction *TreeN = Worklist.pop_back_val(); 10863 SmallVector<Value *> Args; 10864 SmallVector<Value *> PossibleRedVals; 10865 SmallVector<Instruction *> PossibleReductionOps; 10866 CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps); 10867 // If too many extra args - mark the instruction itself as a reduction 10868 // value, not a reduction operation. 10869 if (Args.size() < 2) { 10870 addReductionOps(TreeN); 10871 // Add extra args. 10872 if (!Args.empty()) { 10873 assert(Args.size() == 1 && "Expected only single argument."); 10874 ExtraArgs[TreeN] = Args.front(); 10875 } 10876 // Add reduction values. The values are sorted for better vectorization 10877 // results. 10878 for (Value *V : PossibleRedVals) { 10879 size_t Key, Idx; 10880 std::tie(Key, Idx) = generateKeySubkey( 10881 V, &TLI, 10882 [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) { 10883 auto It = PossibleReducedVals.find(Key); 10884 if (It != PossibleReducedVals.end()) { 10885 for (const auto &LoadData : It->second) { 10886 auto *RLI = cast<LoadInst>(LoadData.second.front().first); 10887 if (getPointersDiff(RLI->getType(), 10888 RLI->getPointerOperand(), LI->getType(), 10889 LI->getPointerOperand(), DL, SE, 10890 /*StrictCheck=*/true)) 10891 return hash_value(RLI->getPointerOperand()); 10892 } 10893 } 10894 return hash_value(LI->getPointerOperand()); 10895 }, 10896 /*AllowAlternate=*/false); 10897 ++PossibleReducedVals[Key][Idx] 10898 .insert(std::make_pair(V, 0)) 10899 .first->second; 10900 } 10901 Worklist.append(PossibleReductionOps.rbegin(), 10902 PossibleReductionOps.rend()); 10903 } else { 10904 size_t Key, Idx; 10905 std::tie(Key, Idx) = generateKeySubkey( 10906 TreeN, &TLI, 10907 [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) { 10908 auto It = PossibleReducedVals.find(Key); 10909 if (It != PossibleReducedVals.end()) { 10910 for (const auto &LoadData : It->second) { 10911 auto *RLI = cast<LoadInst>(LoadData.second.front().first); 10912 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(), 10913 LI->getType(), LI->getPointerOperand(), 10914 DL, SE, /*StrictCheck=*/true)) 10915 return hash_value(RLI->getPointerOperand()); 10916 } 10917 } 10918 return hash_value(LI->getPointerOperand()); 10919 }, 10920 /*AllowAlternate=*/false); 10921 ++PossibleReducedVals[Key][Idx] 10922 .insert(std::make_pair(TreeN, 0)) 10923 .first->second; 10924 } 10925 } 10926 auto PossibleReducedValsVect = PossibleReducedVals.takeVector(); 10927 // Sort values by the total number of values kinds to start the reduction 10928 // from the longest possible reduced values sequences. 10929 for (auto &PossibleReducedVals : PossibleReducedValsVect) { 10930 auto PossibleRedVals = PossibleReducedVals.second.takeVector(); 10931 SmallVector<SmallVector<Value *>> PossibleRedValsVect; 10932 for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end(); 10933 It != E; ++It) { 10934 PossibleRedValsVect.emplace_back(); 10935 auto RedValsVect = It->second.takeVector(); 10936 stable_sort(RedValsVect, [](const auto &P1, const auto &P2) { 10937 return P1.second < P2.second; 10938 }); 10939 for (const std::pair<Value *, unsigned> &Data : RedValsVect) 10940 PossibleRedValsVect.back().append(Data.second, Data.first); 10941 } 10942 stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) { 10943 return P1.size() > P2.size(); 10944 }); 10945 ReducedVals.emplace_back(); 10946 for (ArrayRef<Value *> Data : PossibleRedValsVect) 10947 ReducedVals.back().append(Data.rbegin(), Data.rend()); 10948 } 10949 // Sort the reduced values by number of same/alternate opcode and/or pointer 10950 // operand. 10951 stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) { 10952 return P1.size() > P2.size(); 10953 }); 10954 return true; 10955 } 10956 10957 /// Attempt to vectorize the tree found by matchAssociativeReduction. 10958 Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) { 10959 constexpr int ReductionLimit = 4; 10960 constexpr unsigned RegMaxNumber = 4; 10961 constexpr unsigned RedValsMaxNumber = 128; 10962 // If there are a sufficient number of reduction values, reduce 10963 // to a nearby power-of-2. We can safely generate oversized 10964 // vectors and rely on the backend to split them to legal sizes. 10965 unsigned NumReducedVals = std::accumulate( 10966 ReducedVals.begin(), ReducedVals.end(), 0, 10967 [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); }); 10968 if (NumReducedVals < ReductionLimit) 10969 return nullptr; 10970 10971 IRBuilder<> Builder(cast<Instruction>(ReductionRoot)); 10972 10973 // Track the reduced values in case if they are replaced by extractelement 10974 // because of the vectorization. 10975 DenseMap<Value *, WeakTrackingVH> TrackedVals; 10976 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues; 10977 // The same extra argument may be used several times, so log each attempt 10978 // to use it. 10979 for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) { 10980 assert(Pair.first && "DebugLoc must be set."); 10981 ExternallyUsedValues[Pair.second].push_back(Pair.first); 10982 TrackedVals.try_emplace(Pair.second, Pair.second); 10983 } 10984 10985 // The compare instruction of a min/max is the insertion point for new 10986 // instructions and may be replaced with a new compare instruction. 10987 auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) { 10988 assert(isa<SelectInst>(RdxRootInst) && 10989 "Expected min/max reduction to have select root instruction"); 10990 Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition(); 10991 assert(isa<Instruction>(ScalarCond) && 10992 "Expected min/max reduction to have compare condition"); 10993 return cast<Instruction>(ScalarCond); 10994 }; 10995 10996 // The reduction root is used as the insertion point for new instructions, 10997 // so set it as externally used to prevent it from being deleted. 10998 ExternallyUsedValues[ReductionRoot]; 10999 SmallDenseSet<Value *> IgnoreList; 11000 for (ReductionOpsType &RdxOps : ReductionOps) 11001 for (Value *RdxOp : RdxOps) { 11002 if (!RdxOp) 11003 continue; 11004 IgnoreList.insert(RdxOp); 11005 } 11006 bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot)); 11007 11008 // Need to track reduced vals, they may be changed during vectorization of 11009 // subvectors. 11010 for (ArrayRef<Value *> Candidates : ReducedVals) 11011 for (Value *V : Candidates) 11012 TrackedVals.try_emplace(V, V); 11013 11014 DenseMap<Value *, unsigned> VectorizedVals; 11015 Value *VectorizedTree = nullptr; 11016 bool CheckForReusedReductionOps = false; 11017 // Try to vectorize elements based on their type. 11018 for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) { 11019 ArrayRef<Value *> OrigReducedVals = ReducedVals[I]; 11020 InstructionsState S = getSameOpcode(OrigReducedVals); 11021 SmallVector<Value *> Candidates; 11022 DenseMap<Value *, Value *> TrackedToOrig; 11023 for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) { 11024 Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second; 11025 // Check if the reduction value was not overriden by the extractelement 11026 // instruction because of the vectorization and exclude it, if it is not 11027 // compatible with other values. 11028 if (auto *Inst = dyn_cast<Instruction>(RdxVal)) 11029 if (isVectorLikeInstWithConstOps(Inst) && 11030 (!S.getOpcode() || !S.isOpcodeOrAlt(Inst))) 11031 continue; 11032 Candidates.push_back(RdxVal); 11033 TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]); 11034 } 11035 bool ShuffledExtracts = false; 11036 // Try to handle shuffled extractelements. 11037 if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() && 11038 I + 1 < E) { 11039 InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]); 11040 if (NextS.getOpcode() == Instruction::ExtractElement && 11041 !NextS.isAltShuffle()) { 11042 SmallVector<Value *> CommonCandidates(Candidates); 11043 for (Value *RV : ReducedVals[I + 1]) { 11044 Value *RdxVal = TrackedVals.find(RV)->second; 11045 // Check if the reduction value was not overriden by the 11046 // extractelement instruction because of the vectorization and 11047 // exclude it, if it is not compatible with other values. 11048 if (auto *Inst = dyn_cast<Instruction>(RdxVal)) 11049 if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst)) 11050 continue; 11051 CommonCandidates.push_back(RdxVal); 11052 TrackedToOrig.try_emplace(RdxVal, RV); 11053 } 11054 SmallVector<int> Mask; 11055 if (isFixedVectorShuffle(CommonCandidates, Mask)) { 11056 ++I; 11057 Candidates.swap(CommonCandidates); 11058 ShuffledExtracts = true; 11059 } 11060 } 11061 } 11062 unsigned NumReducedVals = Candidates.size(); 11063 if (NumReducedVals < ReductionLimit) 11064 continue; 11065 11066 unsigned MaxVecRegSize = V.getMaxVecRegSize(); 11067 unsigned EltSize = V.getVectorElementSize(Candidates[0]); 11068 unsigned MaxElts = RegMaxNumber * PowerOf2Floor(MaxVecRegSize / EltSize); 11069 11070 unsigned ReduxWidth = std::min<unsigned>( 11071 PowerOf2Floor(NumReducedVals), std::max(RedValsMaxNumber, MaxElts)); 11072 unsigned Start = 0; 11073 unsigned Pos = Start; 11074 // Restarts vectorization attempt with lower vector factor. 11075 unsigned PrevReduxWidth = ReduxWidth; 11076 bool CheckForReusedReductionOpsLocal = false; 11077 auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals, 11078 &CheckForReusedReductionOpsLocal, 11079 &PrevReduxWidth, &V, 11080 &IgnoreList](bool IgnoreVL = false) { 11081 bool IsAnyRedOpGathered = !IgnoreVL && V.isAnyGathered(IgnoreList); 11082 if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) { 11083 // Check if any of the reduction ops are gathered. If so, worth 11084 // trying again with less number of reduction ops. 11085 CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered; 11086 } 11087 ++Pos; 11088 if (Pos < NumReducedVals - ReduxWidth + 1) 11089 return IsAnyRedOpGathered; 11090 Pos = Start; 11091 ReduxWidth /= 2; 11092 return IsAnyRedOpGathered; 11093 }; 11094 while (Pos < NumReducedVals - ReduxWidth + 1 && 11095 ReduxWidth >= ReductionLimit) { 11096 // Dependency in tree of the reduction ops - drop this attempt, try 11097 // later. 11098 if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth && 11099 Start == 0) { 11100 CheckForReusedReductionOps = true; 11101 break; 11102 } 11103 PrevReduxWidth = ReduxWidth; 11104 ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth); 11105 // Beeing analyzed already - skip. 11106 if (V.areAnalyzedReductionVals(VL)) { 11107 (void)AdjustReducedVals(/*IgnoreVL=*/true); 11108 continue; 11109 } 11110 // Early exit if any of the reduction values were deleted during 11111 // previous vectorization attempts. 11112 if (any_of(VL, [&V](Value *RedVal) { 11113 auto *RedValI = dyn_cast<Instruction>(RedVal); 11114 if (!RedValI) 11115 return false; 11116 return V.isDeleted(RedValI); 11117 })) 11118 break; 11119 V.buildTree(VL, IgnoreList); 11120 if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) { 11121 if (!AdjustReducedVals()) 11122 V.analyzedReductionVals(VL); 11123 continue; 11124 } 11125 if (V.isLoadCombineReductionCandidate(RdxKind)) { 11126 if (!AdjustReducedVals()) 11127 V.analyzedReductionVals(VL); 11128 continue; 11129 } 11130 V.reorderTopToBottom(); 11131 // No need to reorder the root node at all. 11132 V.reorderBottomToTop(/*IgnoreReorder=*/true); 11133 // Keep extracted other reduction values, if they are used in the 11134 // vectorization trees. 11135 BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues( 11136 ExternallyUsedValues); 11137 for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) { 11138 if (Cnt == I || (ShuffledExtracts && Cnt == I - 1)) 11139 continue; 11140 for_each(ReducedVals[Cnt], 11141 [&LocalExternallyUsedValues, &TrackedVals](Value *V) { 11142 if (isa<Instruction>(V)) 11143 LocalExternallyUsedValues[TrackedVals[V]]; 11144 }); 11145 } 11146 // Number of uses of the candidates in the vector of values. 11147 SmallDenseMap<Value *, unsigned> NumUses; 11148 for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) { 11149 Value *V = Candidates[Cnt]; 11150 if (NumUses.count(V) > 0) 11151 continue; 11152 NumUses[V] = std::count(VL.begin(), VL.end(), V); 11153 } 11154 for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) { 11155 Value *V = Candidates[Cnt]; 11156 if (NumUses.count(V) > 0) 11157 continue; 11158 NumUses[V] = std::count(VL.begin(), VL.end(), V); 11159 } 11160 // Gather externally used values. 11161 SmallPtrSet<Value *, 4> Visited; 11162 for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) { 11163 Value *V = Candidates[Cnt]; 11164 if (!Visited.insert(V).second) 11165 continue; 11166 unsigned NumOps = VectorizedVals.lookup(V) + NumUses[V]; 11167 if (NumOps != ReducedValsToOps.find(V)->second.size()) 11168 LocalExternallyUsedValues[V]; 11169 } 11170 for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) { 11171 Value *V = Candidates[Cnt]; 11172 if (!Visited.insert(V).second) 11173 continue; 11174 unsigned NumOps = VectorizedVals.lookup(V) + NumUses[V]; 11175 if (NumOps != ReducedValsToOps.find(V)->second.size()) 11176 LocalExternallyUsedValues[V]; 11177 } 11178 V.buildExternalUses(LocalExternallyUsedValues); 11179 11180 V.computeMinimumValueSizes(); 11181 11182 // Intersect the fast-math-flags from all reduction operations. 11183 FastMathFlags RdxFMF; 11184 RdxFMF.set(); 11185 for (Value *U : IgnoreList) 11186 if (auto *FPMO = dyn_cast<FPMathOperator>(U)) 11187 RdxFMF &= FPMO->getFastMathFlags(); 11188 // Estimate cost. 11189 InstructionCost TreeCost = V.getTreeCost(VL); 11190 InstructionCost ReductionCost = 11191 getReductionCost(TTI, VL, ReduxWidth, RdxFMF); 11192 InstructionCost Cost = TreeCost + ReductionCost; 11193 if (!Cost.isValid()) { 11194 LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n"); 11195 return nullptr; 11196 } 11197 if (Cost >= -SLPCostThreshold) { 11198 V.getORE()->emit([&]() { 11199 return OptimizationRemarkMissed( 11200 SV_NAME, "HorSLPNotBeneficial", 11201 ReducedValsToOps.find(VL[0])->second.front()) 11202 << "Vectorizing horizontal reduction is possible" 11203 << "but not beneficial with cost " << ore::NV("Cost", Cost) 11204 << " and threshold " 11205 << ore::NV("Threshold", -SLPCostThreshold); 11206 }); 11207 if (!AdjustReducedVals()) 11208 V.analyzedReductionVals(VL); 11209 continue; 11210 } 11211 11212 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" 11213 << Cost << ". (HorRdx)\n"); 11214 V.getORE()->emit([&]() { 11215 return OptimizationRemark( 11216 SV_NAME, "VectorizedHorizontalReduction", 11217 ReducedValsToOps.find(VL[0])->second.front()) 11218 << "Vectorized horizontal reduction with cost " 11219 << ore::NV("Cost", Cost) << " and with tree size " 11220 << ore::NV("TreeSize", V.getTreeSize()); 11221 }); 11222 11223 Builder.setFastMathFlags(RdxFMF); 11224 11225 // Vectorize a tree. 11226 Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues); 11227 11228 // Emit a reduction. If the root is a select (min/max idiom), the insert 11229 // point is the compare condition of that select. 11230 Instruction *RdxRootInst = cast<Instruction>(ReductionRoot); 11231 if (IsCmpSelMinMax) 11232 Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst)); 11233 else 11234 Builder.SetInsertPoint(RdxRootInst); 11235 11236 // To prevent poison from leaking across what used to be sequential, 11237 // safe, scalar boolean logic operations, the reduction operand must be 11238 // frozen. 11239 if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst)) 11240 VectorizedRoot = Builder.CreateFreeze(VectorizedRoot); 11241 11242 Value *ReducedSubTree = 11243 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI); 11244 11245 if (!VectorizedTree) { 11246 // Initialize the final value in the reduction. 11247 VectorizedTree = ReducedSubTree; 11248 } else { 11249 // Update the final value in the reduction. 11250 Builder.SetCurrentDebugLocation( 11251 cast<Instruction>(ReductionOps.front().front())->getDebugLoc()); 11252 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 11253 ReducedSubTree, "op.rdx", ReductionOps); 11254 } 11255 // Count vectorized reduced values to exclude them from final reduction. 11256 for (Value *V : VL) 11257 ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0) 11258 .first->getSecond(); 11259 Pos += ReduxWidth; 11260 Start = Pos; 11261 ReduxWidth = PowerOf2Floor(NumReducedVals - Pos); 11262 } 11263 } 11264 if (VectorizedTree) { 11265 // Finish the reduction. 11266 // Need to add extra arguments and not vectorized possible reduction 11267 // values. 11268 // Try to avoid dependencies between the scalar remainders after 11269 // reductions. 11270 auto &&FinalGen = 11271 [this, &Builder, 11272 &TrackedVals](ArrayRef<std::pair<Instruction *, Value *>> InstVals) { 11273 unsigned Sz = InstVals.size(); 11274 SmallVector<std::pair<Instruction *, Value *>> ExtraReds(Sz / 2 + 11275 Sz % 2); 11276 for (unsigned I = 0, E = (Sz / 2) * 2; I < E; I += 2) { 11277 Instruction *RedOp = InstVals[I + 1].first; 11278 Builder.SetCurrentDebugLocation(RedOp->getDebugLoc()); 11279 Value *RdxVal1 = InstVals[I].second; 11280 Value *StableRdxVal1 = RdxVal1; 11281 auto It1 = TrackedVals.find(RdxVal1); 11282 if (It1 != TrackedVals.end()) 11283 StableRdxVal1 = It1->second; 11284 Value *RdxVal2 = InstVals[I + 1].second; 11285 Value *StableRdxVal2 = RdxVal2; 11286 auto It2 = TrackedVals.find(RdxVal2); 11287 if (It2 != TrackedVals.end()) 11288 StableRdxVal2 = It2->second; 11289 Value *ExtraRed = createOp(Builder, RdxKind, StableRdxVal1, 11290 StableRdxVal2, "op.rdx", ReductionOps); 11291 ExtraReds[I / 2] = std::make_pair(InstVals[I].first, ExtraRed); 11292 } 11293 if (Sz % 2 == 1) 11294 ExtraReds[Sz / 2] = InstVals.back(); 11295 return ExtraReds; 11296 }; 11297 SmallVector<std::pair<Instruction *, Value *>> ExtraReductions; 11298 SmallPtrSet<Value *, 8> Visited; 11299 for (ArrayRef<Value *> Candidates : ReducedVals) { 11300 for (Value *RdxVal : Candidates) { 11301 if (!Visited.insert(RdxVal).second) 11302 continue; 11303 unsigned NumOps = VectorizedVals.lookup(RdxVal); 11304 for (Instruction *RedOp : 11305 makeArrayRef(ReducedValsToOps.find(RdxVal)->second) 11306 .drop_back(NumOps)) 11307 ExtraReductions.emplace_back(RedOp, RdxVal); 11308 } 11309 } 11310 for (auto &Pair : ExternallyUsedValues) { 11311 // Add each externally used value to the final reduction. 11312 for (auto *I : Pair.second) 11313 ExtraReductions.emplace_back(I, Pair.first); 11314 } 11315 // Iterate through all not-vectorized reduction values/extra arguments. 11316 while (ExtraReductions.size() > 1) { 11317 SmallVector<std::pair<Instruction *, Value *>> NewReds = 11318 FinalGen(ExtraReductions); 11319 ExtraReductions.swap(NewReds); 11320 } 11321 // Final reduction. 11322 if (ExtraReductions.size() == 1) { 11323 Instruction *RedOp = ExtraReductions.back().first; 11324 Builder.SetCurrentDebugLocation(RedOp->getDebugLoc()); 11325 Value *RdxVal = ExtraReductions.back().second; 11326 Value *StableRdxVal = RdxVal; 11327 auto It = TrackedVals.find(RdxVal); 11328 if (It != TrackedVals.end()) 11329 StableRdxVal = It->second; 11330 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 11331 StableRdxVal, "op.rdx", ReductionOps); 11332 } 11333 11334 ReductionRoot->replaceAllUsesWith(VectorizedTree); 11335 11336 // The original scalar reduction is expected to have no remaining 11337 // uses outside the reduction tree itself. Assert that we got this 11338 // correct, replace internal uses with undef, and mark for eventual 11339 // deletion. 11340 #ifndef NDEBUG 11341 SmallSet<Value *, 4> IgnoreSet; 11342 for (ArrayRef<Value *> RdxOps : ReductionOps) 11343 IgnoreSet.insert(RdxOps.begin(), RdxOps.end()); 11344 #endif 11345 for (ArrayRef<Value *> RdxOps : ReductionOps) { 11346 for (Value *Ignore : RdxOps) { 11347 if (!Ignore) 11348 continue; 11349 #ifndef NDEBUG 11350 for (auto *U : Ignore->users()) { 11351 assert(IgnoreSet.count(U) && 11352 "All users must be either in the reduction ops list."); 11353 } 11354 #endif 11355 if (!Ignore->use_empty()) { 11356 Value *Undef = UndefValue::get(Ignore->getType()); 11357 Ignore->replaceAllUsesWith(Undef); 11358 } 11359 V.eraseInstruction(cast<Instruction>(Ignore)); 11360 } 11361 } 11362 } else if (!CheckForReusedReductionOps) { 11363 for (ReductionOpsType &RdxOps : ReductionOps) 11364 for (Value *RdxOp : RdxOps) 11365 V.analyzedReductionRoot(cast<Instruction>(RdxOp)); 11366 } 11367 return VectorizedTree; 11368 } 11369 11370 private: 11371 /// Calculate the cost of a reduction. 11372 InstructionCost getReductionCost(TargetTransformInfo *TTI, 11373 ArrayRef<Value *> ReducedVals, 11374 unsigned ReduxWidth, FastMathFlags FMF) { 11375 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 11376 Value *FirstReducedVal = ReducedVals.front(); 11377 Type *ScalarTy = FirstReducedVal->getType(); 11378 FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth); 11379 InstructionCost VectorCost = 0, ScalarCost; 11380 // If all of the reduced values are constant, the vector cost is 0, since 11381 // the reduction value can be calculated at the compile time. 11382 bool AllConsts = all_of(ReducedVals, isConstant); 11383 switch (RdxKind) { 11384 case RecurKind::Add: 11385 case RecurKind::Mul: 11386 case RecurKind::Or: 11387 case RecurKind::And: 11388 case RecurKind::Xor: 11389 case RecurKind::FAdd: 11390 case RecurKind::FMul: { 11391 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind); 11392 if (!AllConsts) 11393 VectorCost = 11394 TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind); 11395 ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind); 11396 break; 11397 } 11398 case RecurKind::FMax: 11399 case RecurKind::FMin: { 11400 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 11401 if (!AllConsts) { 11402 auto *VecCondTy = 11403 cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 11404 VectorCost = 11405 TTI->getMinMaxReductionCost(VectorTy, VecCondTy, 11406 /*IsUnsigned=*/false, CostKind); 11407 } 11408 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 11409 ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy, 11410 SclCondTy, RdxPred, CostKind) + 11411 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 11412 SclCondTy, RdxPred, CostKind); 11413 break; 11414 } 11415 case RecurKind::SMax: 11416 case RecurKind::SMin: 11417 case RecurKind::UMax: 11418 case RecurKind::UMin: { 11419 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 11420 if (!AllConsts) { 11421 auto *VecCondTy = 11422 cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 11423 bool IsUnsigned = 11424 RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin; 11425 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, 11426 IsUnsigned, CostKind); 11427 } 11428 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 11429 ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy, 11430 SclCondTy, RdxPred, CostKind) + 11431 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 11432 SclCondTy, RdxPred, CostKind); 11433 break; 11434 } 11435 default: 11436 llvm_unreachable("Expected arithmetic or min/max reduction operation"); 11437 } 11438 11439 // Scalar cost is repeated for N-1 elements. 11440 ScalarCost *= (ReduxWidth - 1); 11441 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost 11442 << " for reduction that starts with " << *FirstReducedVal 11443 << " (It is a splitting reduction)\n"); 11444 return VectorCost - ScalarCost; 11445 } 11446 11447 /// Emit a horizontal reduction of the vectorized value. 11448 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder, 11449 unsigned ReduxWidth, const TargetTransformInfo *TTI) { 11450 assert(VectorizedValue && "Need to have a vectorized tree node"); 11451 assert(isPowerOf2_32(ReduxWidth) && 11452 "We only handle power-of-two reductions for now"); 11453 assert(RdxKind != RecurKind::FMulAdd && 11454 "A call to the llvm.fmuladd intrinsic is not handled yet"); 11455 11456 ++NumVectorInstructions; 11457 return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind); 11458 } 11459 }; 11460 11461 } // end anonymous namespace 11462 11463 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) { 11464 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) 11465 return cast<FixedVectorType>(IE->getType())->getNumElements(); 11466 11467 unsigned AggregateSize = 1; 11468 auto *IV = cast<InsertValueInst>(InsertInst); 11469 Type *CurrentType = IV->getType(); 11470 do { 11471 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 11472 for (auto *Elt : ST->elements()) 11473 if (Elt != ST->getElementType(0)) // check homogeneity 11474 return None; 11475 AggregateSize *= ST->getNumElements(); 11476 CurrentType = ST->getElementType(0); 11477 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 11478 AggregateSize *= AT->getNumElements(); 11479 CurrentType = AT->getElementType(); 11480 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) { 11481 AggregateSize *= VT->getNumElements(); 11482 return AggregateSize; 11483 } else if (CurrentType->isSingleValueType()) { 11484 return AggregateSize; 11485 } else { 11486 return None; 11487 } 11488 } while (true); 11489 } 11490 11491 static void findBuildAggregate_rec(Instruction *LastInsertInst, 11492 TargetTransformInfo *TTI, 11493 SmallVectorImpl<Value *> &BuildVectorOpds, 11494 SmallVectorImpl<Value *> &InsertElts, 11495 unsigned OperandOffset) { 11496 do { 11497 Value *InsertedOperand = LastInsertInst->getOperand(1); 11498 Optional<unsigned> OperandIndex = 11499 getInsertIndex(LastInsertInst, OperandOffset); 11500 if (!OperandIndex) 11501 return; 11502 if (isa<InsertElementInst>(InsertedOperand) || 11503 isa<InsertValueInst>(InsertedOperand)) { 11504 findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI, 11505 BuildVectorOpds, InsertElts, *OperandIndex); 11506 11507 } else { 11508 BuildVectorOpds[*OperandIndex] = InsertedOperand; 11509 InsertElts[*OperandIndex] = LastInsertInst; 11510 } 11511 LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0)); 11512 } while (LastInsertInst != nullptr && 11513 (isa<InsertValueInst>(LastInsertInst) || 11514 isa<InsertElementInst>(LastInsertInst)) && 11515 LastInsertInst->hasOneUse()); 11516 } 11517 11518 /// Recognize construction of vectors like 11519 /// %ra = insertelement <4 x float> poison, float %s0, i32 0 11520 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1 11521 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2 11522 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3 11523 /// starting from the last insertelement or insertvalue instruction. 11524 /// 11525 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>}, 11526 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on. 11527 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples. 11528 /// 11529 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type. 11530 /// 11531 /// \return true if it matches. 11532 static bool findBuildAggregate(Instruction *LastInsertInst, 11533 TargetTransformInfo *TTI, 11534 SmallVectorImpl<Value *> &BuildVectorOpds, 11535 SmallVectorImpl<Value *> &InsertElts) { 11536 11537 assert((isa<InsertElementInst>(LastInsertInst) || 11538 isa<InsertValueInst>(LastInsertInst)) && 11539 "Expected insertelement or insertvalue instruction!"); 11540 11541 assert((BuildVectorOpds.empty() && InsertElts.empty()) && 11542 "Expected empty result vectors!"); 11543 11544 Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst); 11545 if (!AggregateSize) 11546 return false; 11547 BuildVectorOpds.resize(*AggregateSize); 11548 InsertElts.resize(*AggregateSize); 11549 11550 findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0); 11551 llvm::erase_value(BuildVectorOpds, nullptr); 11552 llvm::erase_value(InsertElts, nullptr); 11553 if (BuildVectorOpds.size() >= 2) 11554 return true; 11555 11556 return false; 11557 } 11558 11559 /// Try and get a reduction value from a phi node. 11560 /// 11561 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions 11562 /// if they come from either \p ParentBB or a containing loop latch. 11563 /// 11564 /// \returns A candidate reduction value if possible, or \code nullptr \endcode 11565 /// if not possible. 11566 static Value *getReductionValue(const DominatorTree *DT, PHINode *P, 11567 BasicBlock *ParentBB, LoopInfo *LI) { 11568 // There are situations where the reduction value is not dominated by the 11569 // reduction phi. Vectorizing such cases has been reported to cause 11570 // miscompiles. See PR25787. 11571 auto DominatedReduxValue = [&](Value *R) { 11572 return isa<Instruction>(R) && 11573 DT->dominates(P->getParent(), cast<Instruction>(R)->getParent()); 11574 }; 11575 11576 Value *Rdx = nullptr; 11577 11578 // Return the incoming value if it comes from the same BB as the phi node. 11579 if (P->getIncomingBlock(0) == ParentBB) { 11580 Rdx = P->getIncomingValue(0); 11581 } else if (P->getIncomingBlock(1) == ParentBB) { 11582 Rdx = P->getIncomingValue(1); 11583 } 11584 11585 if (Rdx && DominatedReduxValue(Rdx)) 11586 return Rdx; 11587 11588 // Otherwise, check whether we have a loop latch to look at. 11589 Loop *BBL = LI->getLoopFor(ParentBB); 11590 if (!BBL) 11591 return nullptr; 11592 BasicBlock *BBLatch = BBL->getLoopLatch(); 11593 if (!BBLatch) 11594 return nullptr; 11595 11596 // There is a loop latch, return the incoming value if it comes from 11597 // that. This reduction pattern occasionally turns up. 11598 if (P->getIncomingBlock(0) == BBLatch) { 11599 Rdx = P->getIncomingValue(0); 11600 } else if (P->getIncomingBlock(1) == BBLatch) { 11601 Rdx = P->getIncomingValue(1); 11602 } 11603 11604 if (Rdx && DominatedReduxValue(Rdx)) 11605 return Rdx; 11606 11607 return nullptr; 11608 } 11609 11610 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) { 11611 if (match(I, m_BinOp(m_Value(V0), m_Value(V1)))) 11612 return true; 11613 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1)))) 11614 return true; 11615 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1)))) 11616 return true; 11617 if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1)))) 11618 return true; 11619 if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1)))) 11620 return true; 11621 if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1)))) 11622 return true; 11623 if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1)))) 11624 return true; 11625 return false; 11626 } 11627 11628 /// Attempt to reduce a horizontal reduction. 11629 /// If it is legal to match a horizontal reduction feeding the phi node \a P 11630 /// with reduction operators \a Root (or one of its operands) in a basic block 11631 /// \a BB, then check if it can be done. If horizontal reduction is not found 11632 /// and root instruction is a binary operation, vectorization of the operands is 11633 /// attempted. 11634 /// \returns true if a horizontal reduction was matched and reduced or operands 11635 /// of one of the binary instruction were vectorized. 11636 /// \returns false if a horizontal reduction was not matched (or not possible) 11637 /// or no vectorization of any binary operation feeding \a Root instruction was 11638 /// performed. 11639 static bool tryToVectorizeHorReductionOrInstOperands( 11640 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, 11641 TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL, 11642 const TargetLibraryInfo &TLI, 11643 const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) { 11644 if (!ShouldVectorizeHor) 11645 return false; 11646 11647 if (!Root) 11648 return false; 11649 11650 if (Root->getParent() != BB || isa<PHINode>(Root)) 11651 return false; 11652 // Start analysis starting from Root instruction. If horizontal reduction is 11653 // found, try to vectorize it. If it is not a horizontal reduction or 11654 // vectorization is not possible or not effective, and currently analyzed 11655 // instruction is a binary operation, try to vectorize the operands, using 11656 // pre-order DFS traversal order. If the operands were not vectorized, repeat 11657 // the same procedure considering each operand as a possible root of the 11658 // horizontal reduction. 11659 // Interrupt the process if the Root instruction itself was vectorized or all 11660 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized. 11661 // Skip the analysis of CmpInsts. Compiler implements postanalysis of the 11662 // CmpInsts so we can skip extra attempts in 11663 // tryToVectorizeHorReductionOrInstOperands and save compile time. 11664 std::queue<std::pair<Instruction *, unsigned>> Stack; 11665 Stack.emplace(Root, 0); 11666 SmallPtrSet<Value *, 8> VisitedInstrs; 11667 SmallVector<WeakTrackingVH> PostponedInsts; 11668 bool Res = false; 11669 auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst, 11670 Value *&B0, 11671 Value *&B1) -> Value * { 11672 if (R.isAnalyzedReductionRoot(Inst)) 11673 return nullptr; 11674 bool IsBinop = matchRdxBop(Inst, B0, B1); 11675 bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value())); 11676 if (IsBinop || IsSelect) { 11677 HorizontalReduction HorRdx; 11678 if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI)) 11679 return HorRdx.tryToReduce(R, TTI); 11680 } 11681 return nullptr; 11682 }; 11683 while (!Stack.empty()) { 11684 Instruction *Inst; 11685 unsigned Level; 11686 std::tie(Inst, Level) = Stack.front(); 11687 Stack.pop(); 11688 // Do not try to analyze instruction that has already been vectorized. 11689 // This may happen when we vectorize instruction operands on a previous 11690 // iteration while stack was populated before that happened. 11691 if (R.isDeleted(Inst)) 11692 continue; 11693 Value *B0 = nullptr, *B1 = nullptr; 11694 if (Value *V = TryToReduce(Inst, B0, B1)) { 11695 Res = true; 11696 // Set P to nullptr to avoid re-analysis of phi node in 11697 // matchAssociativeReduction function unless this is the root node. 11698 P = nullptr; 11699 if (auto *I = dyn_cast<Instruction>(V)) { 11700 // Try to find another reduction. 11701 Stack.emplace(I, Level); 11702 continue; 11703 } 11704 } else { 11705 bool IsBinop = B0 && B1; 11706 if (P && IsBinop) { 11707 Inst = dyn_cast<Instruction>(B0); 11708 if (Inst == P) 11709 Inst = dyn_cast<Instruction>(B1); 11710 if (!Inst) { 11711 // Set P to nullptr to avoid re-analysis of phi node in 11712 // matchAssociativeReduction function unless this is the root node. 11713 P = nullptr; 11714 continue; 11715 } 11716 } 11717 // Set P to nullptr to avoid re-analysis of phi node in 11718 // matchAssociativeReduction function unless this is the root node. 11719 P = nullptr; 11720 // Do not try to vectorize CmpInst operands, this is done separately. 11721 // Final attempt for binop args vectorization should happen after the loop 11722 // to try to find reductions. 11723 if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst)) 11724 PostponedInsts.push_back(Inst); 11725 } 11726 11727 // Try to vectorize operands. 11728 // Continue analysis for the instruction from the same basic block only to 11729 // save compile time. 11730 if (++Level < RecursionMaxDepth) 11731 for (auto *Op : Inst->operand_values()) 11732 if (VisitedInstrs.insert(Op).second) 11733 if (auto *I = dyn_cast<Instruction>(Op)) 11734 // Do not try to vectorize CmpInst operands, this is done 11735 // separately. 11736 if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) && 11737 !R.isDeleted(I) && I->getParent() == BB) 11738 Stack.emplace(I, Level); 11739 } 11740 // Try to vectorized binops where reductions were not found. 11741 for (Value *V : PostponedInsts) 11742 if (auto *Inst = dyn_cast<Instruction>(V)) 11743 if (!R.isDeleted(Inst)) 11744 Res |= Vectorize(Inst, R); 11745 return Res; 11746 } 11747 11748 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V, 11749 BasicBlock *BB, BoUpSLP &R, 11750 TargetTransformInfo *TTI) { 11751 auto *I = dyn_cast_or_null<Instruction>(V); 11752 if (!I) 11753 return false; 11754 11755 if (!isa<BinaryOperator>(I)) 11756 P = nullptr; 11757 // Try to match and vectorize a horizontal reduction. 11758 auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool { 11759 return tryToVectorize(I, R); 11760 }; 11761 return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL, 11762 *TLI, ExtraVectorization); 11763 } 11764 11765 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI, 11766 BasicBlock *BB, BoUpSLP &R) { 11767 const DataLayout &DL = BB->getModule()->getDataLayout(); 11768 if (!R.canMapToVector(IVI->getType(), DL)) 11769 return false; 11770 11771 SmallVector<Value *, 16> BuildVectorOpds; 11772 SmallVector<Value *, 16> BuildVectorInsts; 11773 if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts)) 11774 return false; 11775 11776 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n"); 11777 // Aggregate value is unlikely to be processed in vector register. 11778 return tryToVectorizeList(BuildVectorOpds, R); 11779 } 11780 11781 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI, 11782 BasicBlock *BB, BoUpSLP &R) { 11783 SmallVector<Value *, 16> BuildVectorInsts; 11784 SmallVector<Value *, 16> BuildVectorOpds; 11785 SmallVector<int> Mask; 11786 if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) || 11787 (llvm::all_of( 11788 BuildVectorOpds, 11789 [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) && 11790 isFixedVectorShuffle(BuildVectorOpds, Mask))) 11791 return false; 11792 11793 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n"); 11794 return tryToVectorizeList(BuildVectorInsts, R); 11795 } 11796 11797 template <typename T> 11798 static bool 11799 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming, 11800 function_ref<unsigned(T *)> Limit, 11801 function_ref<bool(T *, T *)> Comparator, 11802 function_ref<bool(T *, T *)> AreCompatible, 11803 function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper, 11804 bool LimitForRegisterSize) { 11805 bool Changed = false; 11806 // Sort by type, parent, operands. 11807 stable_sort(Incoming, Comparator); 11808 11809 // Try to vectorize elements base on their type. 11810 SmallVector<T *> Candidates; 11811 for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) { 11812 // Look for the next elements with the same type, parent and operand 11813 // kinds. 11814 auto *SameTypeIt = IncIt; 11815 while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt)) 11816 ++SameTypeIt; 11817 11818 // Try to vectorize them. 11819 unsigned NumElts = (SameTypeIt - IncIt); 11820 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes (" 11821 << NumElts << ")\n"); 11822 // The vectorization is a 3-state attempt: 11823 // 1. Try to vectorize instructions with the same/alternate opcodes with the 11824 // size of maximal register at first. 11825 // 2. Try to vectorize remaining instructions with the same type, if 11826 // possible. This may result in the better vectorization results rather than 11827 // if we try just to vectorize instructions with the same/alternate opcodes. 11828 // 3. Final attempt to try to vectorize all instructions with the 11829 // same/alternate ops only, this may result in some extra final 11830 // vectorization. 11831 if (NumElts > 1 && 11832 TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) { 11833 // Success start over because instructions might have been changed. 11834 Changed = true; 11835 } else if (NumElts < Limit(*IncIt) && 11836 (Candidates.empty() || 11837 Candidates.front()->getType() == (*IncIt)->getType())) { 11838 Candidates.append(IncIt, std::next(IncIt, NumElts)); 11839 } 11840 // Final attempt to vectorize instructions with the same types. 11841 if (Candidates.size() > 1 && 11842 (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) { 11843 if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) { 11844 // Success start over because instructions might have been changed. 11845 Changed = true; 11846 } else if (LimitForRegisterSize) { 11847 // Try to vectorize using small vectors. 11848 for (auto *It = Candidates.begin(), *End = Candidates.end(); 11849 It != End;) { 11850 auto *SameTypeIt = It; 11851 while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It)) 11852 ++SameTypeIt; 11853 unsigned NumElts = (SameTypeIt - It); 11854 if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts), 11855 /*LimitForRegisterSize=*/false)) 11856 Changed = true; 11857 It = SameTypeIt; 11858 } 11859 } 11860 Candidates.clear(); 11861 } 11862 11863 // Start over at the next instruction of a different type (or the end). 11864 IncIt = SameTypeIt; 11865 } 11866 return Changed; 11867 } 11868 11869 /// Compare two cmp instructions. If IsCompatibility is true, function returns 11870 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding 11871 /// operands. If IsCompatibility is false, function implements strict weak 11872 /// ordering relation between two cmp instructions, returning true if the first 11873 /// instruction is "less" than the second, i.e. its predicate is less than the 11874 /// predicate of the second or the operands IDs are less than the operands IDs 11875 /// of the second cmp instruction. 11876 template <bool IsCompatibility> 11877 static bool compareCmp(Value *V, Value *V2, 11878 function_ref<bool(Instruction *)> IsDeleted) { 11879 auto *CI1 = cast<CmpInst>(V); 11880 auto *CI2 = cast<CmpInst>(V2); 11881 if (IsDeleted(CI2) || !isValidElementType(CI2->getType())) 11882 return false; 11883 if (CI1->getOperand(0)->getType()->getTypeID() < 11884 CI2->getOperand(0)->getType()->getTypeID()) 11885 return !IsCompatibility; 11886 if (CI1->getOperand(0)->getType()->getTypeID() > 11887 CI2->getOperand(0)->getType()->getTypeID()) 11888 return false; 11889 CmpInst::Predicate Pred1 = CI1->getPredicate(); 11890 CmpInst::Predicate Pred2 = CI2->getPredicate(); 11891 CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1); 11892 CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2); 11893 CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1); 11894 CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2); 11895 if (BasePred1 < BasePred2) 11896 return !IsCompatibility; 11897 if (BasePred1 > BasePred2) 11898 return false; 11899 // Compare operands. 11900 bool LEPreds = Pred1 <= Pred2; 11901 bool GEPreds = Pred1 >= Pred2; 11902 for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) { 11903 auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1); 11904 auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1); 11905 if (Op1->getValueID() < Op2->getValueID()) 11906 return !IsCompatibility; 11907 if (Op1->getValueID() > Op2->getValueID()) 11908 return false; 11909 if (auto *I1 = dyn_cast<Instruction>(Op1)) 11910 if (auto *I2 = dyn_cast<Instruction>(Op2)) { 11911 if (I1->getParent() != I2->getParent()) 11912 return false; 11913 InstructionsState S = getSameOpcode({I1, I2}); 11914 if (S.getOpcode()) 11915 continue; 11916 return false; 11917 } 11918 } 11919 return IsCompatibility; 11920 } 11921 11922 bool SLPVectorizerPass::vectorizeSimpleInstructions( 11923 SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R, 11924 bool AtTerminator) { 11925 bool OpsChanged = false; 11926 SmallVector<Instruction *, 4> PostponedCmps; 11927 for (auto *I : reverse(Instructions)) { 11928 if (R.isDeleted(I)) 11929 continue; 11930 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) { 11931 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R); 11932 } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) { 11933 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R); 11934 } else if (isa<CmpInst>(I)) { 11935 PostponedCmps.push_back(I); 11936 continue; 11937 } 11938 // Try to find reductions in buildvector sequnces. 11939 OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI); 11940 } 11941 if (AtTerminator) { 11942 // Try to find reductions first. 11943 for (Instruction *I : PostponedCmps) { 11944 if (R.isDeleted(I)) 11945 continue; 11946 for (Value *Op : I->operands()) 11947 OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI); 11948 } 11949 // Try to vectorize operands as vector bundles. 11950 for (Instruction *I : PostponedCmps) { 11951 if (R.isDeleted(I)) 11952 continue; 11953 OpsChanged |= tryToVectorize(I, R); 11954 } 11955 // Try to vectorize list of compares. 11956 // Sort by type, compare predicate, etc. 11957 auto &&CompareSorter = [&R](Value *V, Value *V2) { 11958 return compareCmp<false>(V, V2, 11959 [&R](Instruction *I) { return R.isDeleted(I); }); 11960 }; 11961 11962 auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) { 11963 if (V1 == V2) 11964 return true; 11965 return compareCmp<true>(V1, V2, 11966 [&R](Instruction *I) { return R.isDeleted(I); }); 11967 }; 11968 auto Limit = [&R](Value *V) { 11969 unsigned EltSize = R.getVectorElementSize(V); 11970 return std::max(2U, R.getMaxVecRegSize() / EltSize); 11971 }; 11972 11973 SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end()); 11974 OpsChanged |= tryToVectorizeSequence<Value>( 11975 Vals, Limit, CompareSorter, AreCompatibleCompares, 11976 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 11977 // Exclude possible reductions from other blocks. 11978 bool ArePossiblyReducedInOtherBlock = 11979 any_of(Candidates, [](Value *V) { 11980 return any_of(V->users(), [V](User *U) { 11981 return isa<SelectInst>(U) && 11982 cast<SelectInst>(U)->getParent() != 11983 cast<Instruction>(V)->getParent(); 11984 }); 11985 }); 11986 if (ArePossiblyReducedInOtherBlock) 11987 return false; 11988 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 11989 }, 11990 /*LimitForRegisterSize=*/true); 11991 Instructions.clear(); 11992 } else { 11993 // Insert in reverse order since the PostponedCmps vector was filled in 11994 // reverse order. 11995 Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend()); 11996 } 11997 return OpsChanged; 11998 } 11999 12000 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { 12001 bool Changed = false; 12002 SmallVector<Value *, 4> Incoming; 12003 SmallPtrSet<Value *, 16> VisitedInstrs; 12004 // Maps phi nodes to the non-phi nodes found in the use tree for each phi 12005 // node. Allows better to identify the chains that can be vectorized in the 12006 // better way. 12007 DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes; 12008 auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) { 12009 assert(isValidElementType(V1->getType()) && 12010 isValidElementType(V2->getType()) && 12011 "Expected vectorizable types only."); 12012 // It is fine to compare type IDs here, since we expect only vectorizable 12013 // types, like ints, floats and pointers, we don't care about other type. 12014 if (V1->getType()->getTypeID() < V2->getType()->getTypeID()) 12015 return true; 12016 if (V1->getType()->getTypeID() > V2->getType()->getTypeID()) 12017 return false; 12018 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 12019 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 12020 if (Opcodes1.size() < Opcodes2.size()) 12021 return true; 12022 if (Opcodes1.size() > Opcodes2.size()) 12023 return false; 12024 Optional<bool> ConstOrder; 12025 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 12026 // Undefs are compatible with any other value. 12027 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) { 12028 if (!ConstOrder) 12029 ConstOrder = 12030 !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]); 12031 continue; 12032 } 12033 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 12034 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 12035 DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent()); 12036 DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent()); 12037 if (!NodeI1) 12038 return NodeI2 != nullptr; 12039 if (!NodeI2) 12040 return false; 12041 assert((NodeI1 == NodeI2) == 12042 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 12043 "Different nodes should have different DFS numbers"); 12044 if (NodeI1 != NodeI2) 12045 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 12046 InstructionsState S = getSameOpcode({I1, I2}); 12047 if (S.getOpcode()) 12048 continue; 12049 return I1->getOpcode() < I2->getOpcode(); 12050 } 12051 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) { 12052 if (!ConstOrder) 12053 ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID(); 12054 continue; 12055 } 12056 if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID()) 12057 return true; 12058 if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID()) 12059 return false; 12060 } 12061 return ConstOrder && *ConstOrder; 12062 }; 12063 auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) { 12064 if (V1 == V2) 12065 return true; 12066 if (V1->getType() != V2->getType()) 12067 return false; 12068 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 12069 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 12070 if (Opcodes1.size() != Opcodes2.size()) 12071 return false; 12072 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 12073 // Undefs are compatible with any other value. 12074 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) 12075 continue; 12076 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 12077 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 12078 if (I1->getParent() != I2->getParent()) 12079 return false; 12080 InstructionsState S = getSameOpcode({I1, I2}); 12081 if (S.getOpcode()) 12082 continue; 12083 return false; 12084 } 12085 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) 12086 continue; 12087 if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID()) 12088 return false; 12089 } 12090 return true; 12091 }; 12092 auto Limit = [&R](Value *V) { 12093 unsigned EltSize = R.getVectorElementSize(V); 12094 return std::max(2U, R.getMaxVecRegSize() / EltSize); 12095 }; 12096 12097 bool HaveVectorizedPhiNodes = false; 12098 do { 12099 // Collect the incoming values from the PHIs. 12100 Incoming.clear(); 12101 for (Instruction &I : *BB) { 12102 PHINode *P = dyn_cast<PHINode>(&I); 12103 if (!P) 12104 break; 12105 12106 // No need to analyze deleted, vectorized and non-vectorizable 12107 // instructions. 12108 if (!VisitedInstrs.count(P) && !R.isDeleted(P) && 12109 isValidElementType(P->getType())) 12110 Incoming.push_back(P); 12111 } 12112 12113 // Find the corresponding non-phi nodes for better matching when trying to 12114 // build the tree. 12115 for (Value *V : Incoming) { 12116 SmallVectorImpl<Value *> &Opcodes = 12117 PHIToOpcodes.try_emplace(V).first->getSecond(); 12118 if (!Opcodes.empty()) 12119 continue; 12120 SmallVector<Value *, 4> Nodes(1, V); 12121 SmallPtrSet<Value *, 4> Visited; 12122 while (!Nodes.empty()) { 12123 auto *PHI = cast<PHINode>(Nodes.pop_back_val()); 12124 if (!Visited.insert(PHI).second) 12125 continue; 12126 for (Value *V : PHI->incoming_values()) { 12127 if (auto *PHI1 = dyn_cast<PHINode>((V))) { 12128 Nodes.push_back(PHI1); 12129 continue; 12130 } 12131 Opcodes.emplace_back(V); 12132 } 12133 } 12134 } 12135 12136 HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>( 12137 Incoming, Limit, PHICompare, AreCompatiblePHIs, 12138 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 12139 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 12140 }, 12141 /*LimitForRegisterSize=*/true); 12142 Changed |= HaveVectorizedPhiNodes; 12143 VisitedInstrs.insert(Incoming.begin(), Incoming.end()); 12144 } while (HaveVectorizedPhiNodes); 12145 12146 VisitedInstrs.clear(); 12147 12148 SmallVector<Instruction *, 8> PostProcessInstructions; 12149 SmallDenseSet<Instruction *, 4> KeyNodes; 12150 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 12151 // Skip instructions with scalable type. The num of elements is unknown at 12152 // compile-time for scalable type. 12153 if (isa<ScalableVectorType>(it->getType())) 12154 continue; 12155 12156 // Skip instructions marked for the deletion. 12157 if (R.isDeleted(&*it)) 12158 continue; 12159 // We may go through BB multiple times so skip the one we have checked. 12160 if (!VisitedInstrs.insert(&*it).second) { 12161 if (it->use_empty() && KeyNodes.contains(&*it) && 12162 vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 12163 it->isTerminator())) { 12164 // We would like to start over since some instructions are deleted 12165 // and the iterator may become invalid value. 12166 Changed = true; 12167 it = BB->begin(); 12168 e = BB->end(); 12169 } 12170 continue; 12171 } 12172 12173 if (isa<DbgInfoIntrinsic>(it)) 12174 continue; 12175 12176 // Try to vectorize reductions that use PHINodes. 12177 if (PHINode *P = dyn_cast<PHINode>(it)) { 12178 // Check that the PHI is a reduction PHI. 12179 if (P->getNumIncomingValues() == 2) { 12180 // Try to match and vectorize a horizontal reduction. 12181 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R, 12182 TTI)) { 12183 Changed = true; 12184 it = BB->begin(); 12185 e = BB->end(); 12186 continue; 12187 } 12188 } 12189 // Try to vectorize the incoming values of the PHI, to catch reductions 12190 // that feed into PHIs. 12191 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) { 12192 // Skip if the incoming block is the current BB for now. Also, bypass 12193 // unreachable IR for efficiency and to avoid crashing. 12194 // TODO: Collect the skipped incoming values and try to vectorize them 12195 // after processing BB. 12196 if (BB == P->getIncomingBlock(I) || 12197 !DT->isReachableFromEntry(P->getIncomingBlock(I))) 12198 continue; 12199 12200 Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I), 12201 P->getIncomingBlock(I), R, TTI); 12202 } 12203 continue; 12204 } 12205 12206 // Ran into an instruction without users, like terminator, or function call 12207 // with ignored return value, store. Ignore unused instructions (basing on 12208 // instruction type, except for CallInst and InvokeInst). 12209 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) || 12210 isa<InvokeInst>(it))) { 12211 KeyNodes.insert(&*it); 12212 bool OpsChanged = false; 12213 if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) { 12214 for (auto *V : it->operand_values()) { 12215 // Try to match and vectorize a horizontal reduction. 12216 OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI); 12217 } 12218 } 12219 // Start vectorization of post-process list of instructions from the 12220 // top-tree instructions to try to vectorize as many instructions as 12221 // possible. 12222 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 12223 it->isTerminator()); 12224 if (OpsChanged) { 12225 // We would like to start over since some instructions are deleted 12226 // and the iterator may become invalid value. 12227 Changed = true; 12228 it = BB->begin(); 12229 e = BB->end(); 12230 continue; 12231 } 12232 } 12233 12234 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) || 12235 isa<InsertValueInst>(it)) 12236 PostProcessInstructions.push_back(&*it); 12237 } 12238 12239 return Changed; 12240 } 12241 12242 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) { 12243 auto Changed = false; 12244 for (auto &Entry : GEPs) { 12245 // If the getelementptr list has fewer than two elements, there's nothing 12246 // to do. 12247 if (Entry.second.size() < 2) 12248 continue; 12249 12250 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length " 12251 << Entry.second.size() << ".\n"); 12252 12253 // Process the GEP list in chunks suitable for the target's supported 12254 // vector size. If a vector register can't hold 1 element, we are done. We 12255 // are trying to vectorize the index computations, so the maximum number of 12256 // elements is based on the size of the index expression, rather than the 12257 // size of the GEP itself (the target's pointer size). 12258 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 12259 unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin()); 12260 if (MaxVecRegSize < EltSize) 12261 continue; 12262 12263 unsigned MaxElts = MaxVecRegSize / EltSize; 12264 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) { 12265 auto Len = std::min<unsigned>(BE - BI, MaxElts); 12266 ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len); 12267 12268 // Initialize a set a candidate getelementptrs. Note that we use a 12269 // SetVector here to preserve program order. If the index computations 12270 // are vectorizable and begin with loads, we want to minimize the chance 12271 // of having to reorder them later. 12272 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end()); 12273 12274 // Some of the candidates may have already been vectorized after we 12275 // initially collected them. If so, they are marked as deleted, so remove 12276 // them from the set of candidates. 12277 Candidates.remove_if( 12278 [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); }); 12279 12280 // Remove from the set of candidates all pairs of getelementptrs with 12281 // constant differences. Such getelementptrs are likely not good 12282 // candidates for vectorization in a bottom-up phase since one can be 12283 // computed from the other. We also ensure all candidate getelementptr 12284 // indices are unique. 12285 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) { 12286 auto *GEPI = GEPList[I]; 12287 if (!Candidates.count(GEPI)) 12288 continue; 12289 auto *SCEVI = SE->getSCEV(GEPList[I]); 12290 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) { 12291 auto *GEPJ = GEPList[J]; 12292 auto *SCEVJ = SE->getSCEV(GEPList[J]); 12293 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) { 12294 Candidates.remove(GEPI); 12295 Candidates.remove(GEPJ); 12296 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) { 12297 Candidates.remove(GEPJ); 12298 } 12299 } 12300 } 12301 12302 // We break out of the above computation as soon as we know there are 12303 // fewer than two candidates remaining. 12304 if (Candidates.size() < 2) 12305 continue; 12306 12307 // Add the single, non-constant index of each candidate to the bundle. We 12308 // ensured the indices met these constraints when we originally collected 12309 // the getelementptrs. 12310 SmallVector<Value *, 16> Bundle(Candidates.size()); 12311 auto BundleIndex = 0u; 12312 for (auto *V : Candidates) { 12313 auto *GEP = cast<GetElementPtrInst>(V); 12314 auto *GEPIdx = GEP->idx_begin()->get(); 12315 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)); 12316 Bundle[BundleIndex++] = GEPIdx; 12317 } 12318 12319 // Try and vectorize the indices. We are currently only interested in 12320 // gather-like cases of the form: 12321 // 12322 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ... 12323 // 12324 // where the loads of "a", the loads of "b", and the subtractions can be 12325 // performed in parallel. It's likely that detecting this pattern in a 12326 // bottom-up phase will be simpler and less costly than building a 12327 // full-blown top-down phase beginning at the consecutive loads. 12328 Changed |= tryToVectorizeList(Bundle, R); 12329 } 12330 } 12331 return Changed; 12332 } 12333 12334 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) { 12335 bool Changed = false; 12336 // Sort by type, base pointers and values operand. Value operands must be 12337 // compatible (have the same opcode, same parent), otherwise it is 12338 // definitely not profitable to try to vectorize them. 12339 auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) { 12340 if (V->getPointerOperandType()->getTypeID() < 12341 V2->getPointerOperandType()->getTypeID()) 12342 return true; 12343 if (V->getPointerOperandType()->getTypeID() > 12344 V2->getPointerOperandType()->getTypeID()) 12345 return false; 12346 // UndefValues are compatible with all other values. 12347 if (isa<UndefValue>(V->getValueOperand()) || 12348 isa<UndefValue>(V2->getValueOperand())) 12349 return false; 12350 if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand())) 12351 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 12352 DomTreeNodeBase<llvm::BasicBlock> *NodeI1 = 12353 DT->getNode(I1->getParent()); 12354 DomTreeNodeBase<llvm::BasicBlock> *NodeI2 = 12355 DT->getNode(I2->getParent()); 12356 assert(NodeI1 && "Should only process reachable instructions"); 12357 assert(NodeI2 && "Should only process reachable instructions"); 12358 assert((NodeI1 == NodeI2) == 12359 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 12360 "Different nodes should have different DFS numbers"); 12361 if (NodeI1 != NodeI2) 12362 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 12363 InstructionsState S = getSameOpcode({I1, I2}); 12364 if (S.getOpcode()) 12365 return false; 12366 return I1->getOpcode() < I2->getOpcode(); 12367 } 12368 if (isa<Constant>(V->getValueOperand()) && 12369 isa<Constant>(V2->getValueOperand())) 12370 return false; 12371 return V->getValueOperand()->getValueID() < 12372 V2->getValueOperand()->getValueID(); 12373 }; 12374 12375 auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) { 12376 if (V1 == V2) 12377 return true; 12378 if (V1->getPointerOperandType() != V2->getPointerOperandType()) 12379 return false; 12380 // Undefs are compatible with any other value. 12381 if (isa<UndefValue>(V1->getValueOperand()) || 12382 isa<UndefValue>(V2->getValueOperand())) 12383 return true; 12384 if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand())) 12385 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 12386 if (I1->getParent() != I2->getParent()) 12387 return false; 12388 InstructionsState S = getSameOpcode({I1, I2}); 12389 return S.getOpcode() > 0; 12390 } 12391 if (isa<Constant>(V1->getValueOperand()) && 12392 isa<Constant>(V2->getValueOperand())) 12393 return true; 12394 return V1->getValueOperand()->getValueID() == 12395 V2->getValueOperand()->getValueID(); 12396 }; 12397 auto Limit = [&R, this](StoreInst *SI) { 12398 unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType()); 12399 return R.getMinVF(EltSize); 12400 }; 12401 12402 // Attempt to sort and vectorize each of the store-groups. 12403 for (auto &Pair : Stores) { 12404 if (Pair.second.size() < 2) 12405 continue; 12406 12407 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " 12408 << Pair.second.size() << ".\n"); 12409 12410 if (!isValidElementType(Pair.second.front()->getValueOperand()->getType())) 12411 continue; 12412 12413 Changed |= tryToVectorizeSequence<StoreInst>( 12414 Pair.second, Limit, StoreSorter, AreCompatibleStores, 12415 [this, &R](ArrayRef<StoreInst *> Candidates, bool) { 12416 return vectorizeStores(Candidates, R); 12417 }, 12418 /*LimitForRegisterSize=*/false); 12419 } 12420 return Changed; 12421 } 12422 12423 char SLPVectorizer::ID = 0; 12424 12425 static const char lv_name[] = "SLP Vectorizer"; 12426 12427 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false) 12428 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 12429 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 12430 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12431 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 12432 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 12433 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) 12434 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 12435 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy) 12436 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) 12437 12438 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); } 12439