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.getValue(), 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.getValue(), 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.getValue(); 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 SmallVectorImpl<unsigned> &Order, 3487 SmallVectorImpl<Value *> &PointerOps) { 3488 // Check that a vectorized load would load the same memory as a scalar 3489 // load. For example, we don't want to vectorize loads that are smaller 3490 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 3491 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 3492 // from such a struct, we read/write packed bits disagreeing with the 3493 // unvectorized version. 3494 Type *ScalarTy = VL0->getType(); 3495 3496 if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy)) 3497 return LoadsState::Gather; 3498 3499 // Make sure all loads in the bundle are simple - we can't vectorize 3500 // atomic or volatile loads. 3501 PointerOps.clear(); 3502 PointerOps.resize(VL.size()); 3503 auto *POIter = PointerOps.begin(); 3504 for (Value *V : VL) { 3505 auto *L = cast<LoadInst>(V); 3506 if (!L->isSimple()) 3507 return LoadsState::Gather; 3508 *POIter = L->getPointerOperand(); 3509 ++POIter; 3510 } 3511 3512 Order.clear(); 3513 // Check the order of pointer operands. 3514 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) { 3515 Value *Ptr0; 3516 Value *PtrN; 3517 if (Order.empty()) { 3518 Ptr0 = PointerOps.front(); 3519 PtrN = PointerOps.back(); 3520 } else { 3521 Ptr0 = PointerOps[Order.front()]; 3522 PtrN = PointerOps[Order.back()]; 3523 } 3524 Optional<int> Diff = 3525 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE); 3526 // Check that the sorted loads are consecutive. 3527 if (static_cast<unsigned>(*Diff) == VL.size() - 1) 3528 return LoadsState::Vectorize; 3529 Align CommonAlignment = cast<LoadInst>(VL0)->getAlign(); 3530 for (Value *V : VL) 3531 CommonAlignment = 3532 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 3533 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 3534 if (TTI.isLegalMaskedGather(VecTy, CommonAlignment) && 3535 !TTI.forceScalarizeMaskedGather(VecTy, CommonAlignment)) 3536 return LoadsState::ScatterVectorize; 3537 } 3538 3539 return LoadsState::Gather; 3540 } 3541 3542 bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy, 3543 const DataLayout &DL, ScalarEvolution &SE, 3544 SmallVectorImpl<unsigned> &SortedIndices) { 3545 assert(llvm::all_of( 3546 VL, [](const Value *V) { return V->getType()->isPointerTy(); }) && 3547 "Expected list of pointer operands."); 3548 // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each 3549 // Ptr into, sort and return the sorted indices with values next to one 3550 // another. 3551 MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases; 3552 Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U)); 3553 3554 unsigned Cnt = 1; 3555 for (Value *Ptr : VL.drop_front()) { 3556 bool Found = any_of(Bases, [&](auto &Base) { 3557 Optional<int> Diff = 3558 getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE, 3559 /*StrictCheck=*/true); 3560 if (!Diff) 3561 return false; 3562 3563 Base.second.emplace_back(Ptr, *Diff, Cnt++); 3564 return true; 3565 }); 3566 3567 if (!Found) { 3568 // If we haven't found enough to usefully cluster, return early. 3569 if (Bases.size() > VL.size() / 2 - 1) 3570 return false; 3571 3572 // Not found already - add a new Base 3573 Bases[Ptr].emplace_back(Ptr, 0, Cnt++); 3574 } 3575 } 3576 3577 // For each of the bases sort the pointers by Offset and check if any of the 3578 // base become consecutively allocated. 3579 bool AnyConsecutive = false; 3580 for (auto &Base : Bases) { 3581 auto &Vec = Base.second; 3582 if (Vec.size() > 1) { 3583 llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X, 3584 const std::tuple<Value *, int, unsigned> &Y) { 3585 return std::get<1>(X) < std::get<1>(Y); 3586 }); 3587 int InitialOffset = std::get<1>(Vec[0]); 3588 AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) { 3589 return std::get<1>(P.value()) == int(P.index()) + InitialOffset; 3590 }); 3591 } 3592 } 3593 3594 // Fill SortedIndices array only if it looks worth-while to sort the ptrs. 3595 SortedIndices.clear(); 3596 if (!AnyConsecutive) 3597 return false; 3598 3599 for (auto &Base : Bases) { 3600 for (auto &T : Base.second) 3601 SortedIndices.push_back(std::get<2>(T)); 3602 } 3603 3604 assert(SortedIndices.size() == VL.size() && 3605 "Expected SortedIndices to be the size of VL"); 3606 return true; 3607 } 3608 3609 Optional<BoUpSLP::OrdersType> 3610 BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) { 3611 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only."); 3612 Type *ScalarTy = TE.Scalars[0]->getType(); 3613 3614 SmallVector<Value *> Ptrs; 3615 Ptrs.reserve(TE.Scalars.size()); 3616 for (Value *V : TE.Scalars) { 3617 auto *L = dyn_cast<LoadInst>(V); 3618 if (!L || !L->isSimple()) 3619 return None; 3620 Ptrs.push_back(L->getPointerOperand()); 3621 } 3622 3623 BoUpSLP::OrdersType Order; 3624 if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order)) 3625 return Order; 3626 return None; 3627 } 3628 3629 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE, 3630 bool TopToBottom) { 3631 // No need to reorder if need to shuffle reuses, still need to shuffle the 3632 // node. 3633 if (!TE.ReuseShuffleIndices.empty()) 3634 return None; 3635 if (TE.State == TreeEntry::Vectorize && 3636 (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) || 3637 (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) && 3638 !TE.isAltShuffle()) 3639 return TE.ReorderIndices; 3640 if (TE.State == TreeEntry::NeedToGather) { 3641 // TODO: add analysis of other gather nodes with extractelement 3642 // instructions and other values/instructions, not only undefs. 3643 if (((TE.getOpcode() == Instruction::ExtractElement && 3644 !TE.isAltShuffle()) || 3645 (all_of(TE.Scalars, 3646 [](Value *V) { 3647 return isa<UndefValue, ExtractElementInst>(V); 3648 }) && 3649 any_of(TE.Scalars, 3650 [](Value *V) { return isa<ExtractElementInst>(V); }))) && 3651 all_of(TE.Scalars, 3652 [](Value *V) { 3653 auto *EE = dyn_cast<ExtractElementInst>(V); 3654 return !EE || isa<FixedVectorType>(EE->getVectorOperandType()); 3655 }) && 3656 allSameType(TE.Scalars)) { 3657 // Check that gather of extractelements can be represented as 3658 // just a shuffle of a single vector. 3659 OrdersType CurrentOrder; 3660 bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder); 3661 if (Reuse || !CurrentOrder.empty()) { 3662 if (!CurrentOrder.empty()) 3663 fixupOrderingIndices(CurrentOrder); 3664 return CurrentOrder; 3665 } 3666 } 3667 if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE)) 3668 return CurrentOrder; 3669 if (TE.Scalars.size() >= 4) 3670 if (Optional<OrdersType> Order = findPartiallyOrderedLoads(TE)) 3671 return Order; 3672 } 3673 return None; 3674 } 3675 3676 void BoUpSLP::reorderTopToBottom() { 3677 // Maps VF to the graph nodes. 3678 DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries; 3679 // ExtractElement gather nodes which can be vectorized and need to handle 3680 // their ordering. 3681 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3682 3683 // Maps a TreeEntry to the reorder indices of external users. 3684 DenseMap<const TreeEntry *, SmallVector<OrdersType, 1>> 3685 ExternalUserReorderMap; 3686 // Find all reorderable nodes with the given VF. 3687 // Currently the are vectorized stores,loads,extracts + some gathering of 3688 // extracts. 3689 for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders, 3690 &ExternalUserReorderMap]( 3691 const std::unique_ptr<TreeEntry> &TE) { 3692 // Look for external users that will probably be vectorized. 3693 SmallVector<OrdersType, 1> ExternalUserReorderIndices = 3694 findExternalStoreUsersReorderIndices(TE.get()); 3695 if (!ExternalUserReorderIndices.empty()) { 3696 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 3697 ExternalUserReorderMap.try_emplace(TE.get(), 3698 std::move(ExternalUserReorderIndices)); 3699 } 3700 3701 if (Optional<OrdersType> CurrentOrder = 3702 getReorderingData(*TE, /*TopToBottom=*/true)) { 3703 // Do not include ordering for nodes used in the alt opcode vectorization, 3704 // better to reorder them during bottom-to-top stage. If follow the order 3705 // here, it causes reordering of the whole graph though actually it is 3706 // profitable just to reorder the subgraph that starts from the alternate 3707 // opcode vectorization node. Such nodes already end-up with the shuffle 3708 // instruction and it is just enough to change this shuffle rather than 3709 // rotate the scalars for the whole graph. 3710 unsigned Cnt = 0; 3711 const TreeEntry *UserTE = TE.get(); 3712 while (UserTE && Cnt < RecursionMaxDepth) { 3713 if (UserTE->UserTreeIndices.size() != 1) 3714 break; 3715 if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) { 3716 return EI.UserTE->State == TreeEntry::Vectorize && 3717 EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0; 3718 })) 3719 return; 3720 UserTE = UserTE->UserTreeIndices.back().UserTE; 3721 ++Cnt; 3722 } 3723 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 3724 if (TE->State != TreeEntry::Vectorize) 3725 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3726 } 3727 }); 3728 3729 // Reorder the graph nodes according to their vectorization factor. 3730 for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1; 3731 VF /= 2) { 3732 auto It = VFToOrderedEntries.find(VF); 3733 if (It == VFToOrderedEntries.end()) 3734 continue; 3735 // Try to find the most profitable order. We just are looking for the most 3736 // used order and reorder scalar elements in the nodes according to this 3737 // mostly used order. 3738 ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef(); 3739 // All operands are reordered and used only in this node - propagate the 3740 // most used order to the user node. 3741 MapVector<OrdersType, unsigned, 3742 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3743 OrdersUses; 3744 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3745 for (const TreeEntry *OpTE : OrderedEntries) { 3746 // No need to reorder this nodes, still need to extend and to use shuffle, 3747 // just need to merge reordering shuffle and the reuse shuffle. 3748 if (!OpTE->ReuseShuffleIndices.empty()) 3749 continue; 3750 // Count number of orders uses. 3751 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3752 if (OpTE->State == TreeEntry::NeedToGather) { 3753 auto It = GathersToOrders.find(OpTE); 3754 if (It != GathersToOrders.end()) 3755 return It->second; 3756 } 3757 return OpTE->ReorderIndices; 3758 }(); 3759 // First consider the order of the external scalar users. 3760 auto It = ExternalUserReorderMap.find(OpTE); 3761 if (It != ExternalUserReorderMap.end()) { 3762 const auto &ExternalUserReorderIndices = It->second; 3763 for (const OrdersType &ExtOrder : ExternalUserReorderIndices) 3764 ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second; 3765 // No other useful reorder data in this entry. 3766 if (Order.empty()) 3767 continue; 3768 } 3769 // Stores actually store the mask, not the order, need to invert. 3770 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3771 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3772 SmallVector<int> Mask; 3773 inversePermutation(Order, Mask); 3774 unsigned E = Order.size(); 3775 OrdersType CurrentOrder(E, E); 3776 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3777 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3778 }); 3779 fixupOrderingIndices(CurrentOrder); 3780 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 3781 } else { 3782 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 3783 } 3784 } 3785 // Set order of the user node. 3786 if (OrdersUses.empty()) 3787 continue; 3788 // Choose the most used order. 3789 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3790 unsigned Cnt = OrdersUses.front().second; 3791 for (const auto &Pair : drop_begin(OrdersUses)) { 3792 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3793 BestOrder = Pair.first; 3794 Cnt = Pair.second; 3795 } 3796 } 3797 // Set order of the user node. 3798 if (BestOrder.empty()) 3799 continue; 3800 SmallVector<int> Mask; 3801 inversePermutation(BestOrder, Mask); 3802 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3803 unsigned E = BestOrder.size(); 3804 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3805 return I < E ? static_cast<int>(I) : UndefMaskElem; 3806 }); 3807 // Do an actual reordering, if profitable. 3808 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 3809 // Just do the reordering for the nodes with the given VF. 3810 if (TE->Scalars.size() != VF) { 3811 if (TE->ReuseShuffleIndices.size() == VF) { 3812 // Need to reorder the reuses masks of the operands with smaller VF to 3813 // be able to find the match between the graph nodes and scalar 3814 // operands of the given node during vectorization/cost estimation. 3815 assert(all_of(TE->UserTreeIndices, 3816 [VF, &TE](const EdgeInfo &EI) { 3817 return EI.UserTE->Scalars.size() == VF || 3818 EI.UserTE->Scalars.size() == 3819 TE->Scalars.size(); 3820 }) && 3821 "All users must be of VF size."); 3822 // Update ordering of the operands with the smaller VF than the given 3823 // one. 3824 reorderReuses(TE->ReuseShuffleIndices, Mask); 3825 } 3826 continue; 3827 } 3828 if (TE->State == TreeEntry::Vectorize && 3829 isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst, 3830 InsertElementInst>(TE->getMainOp()) && 3831 !TE->isAltShuffle()) { 3832 // Build correct orders for extract{element,value}, loads and 3833 // stores. 3834 reorderOrder(TE->ReorderIndices, Mask); 3835 if (isa<InsertElementInst, StoreInst>(TE->getMainOp())) 3836 TE->reorderOperands(Mask); 3837 } else { 3838 // Reorder the node and its operands. 3839 TE->reorderOperands(Mask); 3840 assert(TE->ReorderIndices.empty() && 3841 "Expected empty reorder sequence."); 3842 reorderScalars(TE->Scalars, Mask); 3843 } 3844 if (!TE->ReuseShuffleIndices.empty()) { 3845 // Apply reversed order to keep the original ordering of the reused 3846 // elements to avoid extra reorder indices shuffling. 3847 OrdersType CurrentOrder; 3848 reorderOrder(CurrentOrder, MaskOrder); 3849 SmallVector<int> NewReuses; 3850 inversePermutation(CurrentOrder, NewReuses); 3851 addMask(NewReuses, TE->ReuseShuffleIndices); 3852 TE->ReuseShuffleIndices.swap(NewReuses); 3853 } 3854 } 3855 } 3856 } 3857 3858 bool BoUpSLP::canReorderOperands( 3859 TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges, 3860 ArrayRef<TreeEntry *> ReorderableGathers, 3861 SmallVectorImpl<TreeEntry *> &GatherOps) { 3862 for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) { 3863 if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) { 3864 return OpData.first == I && 3865 OpData.second->State == TreeEntry::Vectorize; 3866 })) 3867 continue; 3868 if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) { 3869 // Do not reorder if operand node is used by many user nodes. 3870 if (any_of(TE->UserTreeIndices, 3871 [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; })) 3872 return false; 3873 // Add the node to the list of the ordered nodes with the identity 3874 // order. 3875 Edges.emplace_back(I, TE); 3876 // Add ScatterVectorize nodes to the list of operands, where just 3877 // reordering of the scalars is required. Similar to the gathers, so 3878 // simply add to the list of gathered ops. 3879 if (TE->State != TreeEntry::Vectorize) 3880 GatherOps.push_back(TE); 3881 continue; 3882 } 3883 ArrayRef<Value *> VL = UserTE->getOperand(I); 3884 TreeEntry *Gather = nullptr; 3885 if (count_if(ReorderableGathers, 3886 [VL, &Gather](TreeEntry *TE) { 3887 assert(TE->State != TreeEntry::Vectorize && 3888 "Only non-vectorized nodes are expected."); 3889 if (TE->isSame(VL)) { 3890 Gather = TE; 3891 return true; 3892 } 3893 return false; 3894 }) > 1 && 3895 !all_of(VL, isConstant)) 3896 return false; 3897 if (Gather) 3898 GatherOps.push_back(Gather); 3899 } 3900 return true; 3901 } 3902 3903 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) { 3904 SetVector<TreeEntry *> OrderedEntries; 3905 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3906 // Find all reorderable leaf nodes with the given VF. 3907 // Currently the are vectorized loads,extracts without alternate operands + 3908 // some gathering of extracts. 3909 SmallVector<TreeEntry *> NonVectorized; 3910 for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders, 3911 &NonVectorized]( 3912 const std::unique_ptr<TreeEntry> &TE) { 3913 if (TE->State != TreeEntry::Vectorize) 3914 NonVectorized.push_back(TE.get()); 3915 if (Optional<OrdersType> CurrentOrder = 3916 getReorderingData(*TE, /*TopToBottom=*/false)) { 3917 OrderedEntries.insert(TE.get()); 3918 if (TE->State != TreeEntry::Vectorize) 3919 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3920 } 3921 }); 3922 3923 // 1. Propagate order to the graph nodes, which use only reordered nodes. 3924 // I.e., if the node has operands, that are reordered, try to make at least 3925 // one operand order in the natural order and reorder others + reorder the 3926 // user node itself. 3927 SmallPtrSet<const TreeEntry *, 4> Visited; 3928 while (!OrderedEntries.empty()) { 3929 // 1. Filter out only reordered nodes. 3930 // 2. If the entry has multiple uses - skip it and jump to the next node. 3931 DenseMap<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users; 3932 SmallVector<TreeEntry *> Filtered; 3933 for (TreeEntry *TE : OrderedEntries) { 3934 if (!(TE->State == TreeEntry::Vectorize || 3935 (TE->State == TreeEntry::NeedToGather && 3936 GathersToOrders.count(TE))) || 3937 TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() || 3938 !all_of(drop_begin(TE->UserTreeIndices), 3939 [TE](const EdgeInfo &EI) { 3940 return EI.UserTE == TE->UserTreeIndices.front().UserTE; 3941 }) || 3942 !Visited.insert(TE).second) { 3943 Filtered.push_back(TE); 3944 continue; 3945 } 3946 // Build a map between user nodes and their operands order to speedup 3947 // search. The graph currently does not provide this dependency directly. 3948 for (EdgeInfo &EI : TE->UserTreeIndices) { 3949 TreeEntry *UserTE = EI.UserTE; 3950 auto It = Users.find(UserTE); 3951 if (It == Users.end()) 3952 It = Users.insert({UserTE, {}}).first; 3953 It->second.emplace_back(EI.EdgeIdx, TE); 3954 } 3955 } 3956 // Erase filtered entries. 3957 for_each(Filtered, 3958 [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); }); 3959 SmallVector< 3960 std::pair<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>>> 3961 UsersVec(Users.begin(), Users.end()); 3962 sort(UsersVec, [](const auto &Data1, const auto &Data2) { 3963 return Data1.first->Idx > Data2.first->Idx; 3964 }); 3965 for (auto &Data : UsersVec) { 3966 // Check that operands are used only in the User node. 3967 SmallVector<TreeEntry *> GatherOps; 3968 if (!canReorderOperands(Data.first, Data.second, NonVectorized, 3969 GatherOps)) { 3970 for_each(Data.second, 3971 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3972 OrderedEntries.remove(Op.second); 3973 }); 3974 continue; 3975 } 3976 // All operands are reordered and used only in this node - propagate the 3977 // most used order to the user node. 3978 MapVector<OrdersType, unsigned, 3979 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3980 OrdersUses; 3981 // Do the analysis for each tree entry only once, otherwise the order of 3982 // the same node my be considered several times, though might be not 3983 // profitable. 3984 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3985 SmallPtrSet<const TreeEntry *, 4> VisitedUsers; 3986 for (const auto &Op : Data.second) { 3987 TreeEntry *OpTE = Op.second; 3988 if (!VisitedOps.insert(OpTE).second) 3989 continue; 3990 if (!OpTE->ReuseShuffleIndices.empty() || 3991 (IgnoreReorder && OpTE == VectorizableTree.front().get())) 3992 continue; 3993 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3994 if (OpTE->State == TreeEntry::NeedToGather) 3995 return GathersToOrders.find(OpTE)->second; 3996 return OpTE->ReorderIndices; 3997 }(); 3998 unsigned NumOps = count_if( 3999 Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) { 4000 return P.second == OpTE; 4001 }); 4002 // Stores actually store the mask, not the order, need to invert. 4003 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 4004 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 4005 SmallVector<int> Mask; 4006 inversePermutation(Order, Mask); 4007 unsigned E = Order.size(); 4008 OrdersType CurrentOrder(E, E); 4009 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 4010 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 4011 }); 4012 fixupOrderingIndices(CurrentOrder); 4013 OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second += 4014 NumOps; 4015 } else { 4016 OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps; 4017 } 4018 auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0)); 4019 const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders]( 4020 const TreeEntry *TE) { 4021 if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() || 4022 (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) || 4023 (IgnoreReorder && TE->Idx == 0)) 4024 return true; 4025 if (TE->State == TreeEntry::NeedToGather) { 4026 auto It = GathersToOrders.find(TE); 4027 if (It != GathersToOrders.end()) 4028 return !It->second.empty(); 4029 return true; 4030 } 4031 return false; 4032 }; 4033 for (const EdgeInfo &EI : OpTE->UserTreeIndices) { 4034 TreeEntry *UserTE = EI.UserTE; 4035 if (!VisitedUsers.insert(UserTE).second) 4036 continue; 4037 // May reorder user node if it requires reordering, has reused 4038 // scalars, is an alternate op vectorize node or its op nodes require 4039 // reordering. 4040 if (AllowsReordering(UserTE)) 4041 continue; 4042 // Check if users allow reordering. 4043 // Currently look up just 1 level of operands to avoid increase of 4044 // the compile time. 4045 // Profitable to reorder if definitely more operands allow 4046 // reordering rather than those with natural order. 4047 ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE]; 4048 if (static_cast<unsigned>(count_if( 4049 Ops, [UserTE, &AllowsReordering]( 4050 const std::pair<unsigned, TreeEntry *> &Op) { 4051 return AllowsReordering(Op.second) && 4052 all_of(Op.second->UserTreeIndices, 4053 [UserTE](const EdgeInfo &EI) { 4054 return EI.UserTE == UserTE; 4055 }); 4056 })) <= Ops.size() / 2) 4057 ++Res.first->second; 4058 } 4059 } 4060 // If no orders - skip current nodes and jump to the next one, if any. 4061 if (OrdersUses.empty()) { 4062 for_each(Data.second, 4063 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 4064 OrderedEntries.remove(Op.second); 4065 }); 4066 continue; 4067 } 4068 // Choose the best order. 4069 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 4070 unsigned Cnt = OrdersUses.front().second; 4071 for (const auto &Pair : drop_begin(OrdersUses)) { 4072 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 4073 BestOrder = Pair.first; 4074 Cnt = Pair.second; 4075 } 4076 } 4077 // Set order of the user node (reordering of operands and user nodes). 4078 if (BestOrder.empty()) { 4079 for_each(Data.second, 4080 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 4081 OrderedEntries.remove(Op.second); 4082 }); 4083 continue; 4084 } 4085 // Erase operands from OrderedEntries list and adjust their orders. 4086 VisitedOps.clear(); 4087 SmallVector<int> Mask; 4088 inversePermutation(BestOrder, Mask); 4089 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 4090 unsigned E = BestOrder.size(); 4091 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 4092 return I < E ? static_cast<int>(I) : UndefMaskElem; 4093 }); 4094 for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) { 4095 TreeEntry *TE = Op.second; 4096 OrderedEntries.remove(TE); 4097 if (!VisitedOps.insert(TE).second) 4098 continue; 4099 if (TE->ReuseShuffleIndices.size() == BestOrder.size()) { 4100 // Just reorder reuses indices. 4101 reorderReuses(TE->ReuseShuffleIndices, Mask); 4102 continue; 4103 } 4104 // Gathers are processed separately. 4105 if (TE->State != TreeEntry::Vectorize) 4106 continue; 4107 assert((BestOrder.size() == TE->ReorderIndices.size() || 4108 TE->ReorderIndices.empty()) && 4109 "Non-matching sizes of user/operand entries."); 4110 reorderOrder(TE->ReorderIndices, Mask); 4111 } 4112 // For gathers just need to reorder its scalars. 4113 for (TreeEntry *Gather : GatherOps) { 4114 assert(Gather->ReorderIndices.empty() && 4115 "Unexpected reordering of gathers."); 4116 if (!Gather->ReuseShuffleIndices.empty()) { 4117 // Just reorder reuses indices. 4118 reorderReuses(Gather->ReuseShuffleIndices, Mask); 4119 continue; 4120 } 4121 reorderScalars(Gather->Scalars, Mask); 4122 OrderedEntries.remove(Gather); 4123 } 4124 // Reorder operands of the user node and set the ordering for the user 4125 // node itself. 4126 if (Data.first->State != TreeEntry::Vectorize || 4127 !isa<ExtractElementInst, ExtractValueInst, LoadInst>( 4128 Data.first->getMainOp()) || 4129 Data.first->isAltShuffle()) 4130 Data.first->reorderOperands(Mask); 4131 if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) || 4132 Data.first->isAltShuffle()) { 4133 reorderScalars(Data.first->Scalars, Mask); 4134 reorderOrder(Data.first->ReorderIndices, MaskOrder); 4135 if (Data.first->ReuseShuffleIndices.empty() && 4136 !Data.first->ReorderIndices.empty() && 4137 !Data.first->isAltShuffle()) { 4138 // Insert user node to the list to try to sink reordering deeper in 4139 // the graph. 4140 OrderedEntries.insert(Data.first); 4141 } 4142 } else { 4143 reorderOrder(Data.first->ReorderIndices, Mask); 4144 } 4145 } 4146 } 4147 // If the reordering is unnecessary, just remove the reorder. 4148 if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() && 4149 VectorizableTree.front()->ReuseShuffleIndices.empty()) 4150 VectorizableTree.front()->ReorderIndices.clear(); 4151 } 4152 4153 void BoUpSLP::buildExternalUses( 4154 const ExtraValueToDebugLocsMap &ExternallyUsedValues) { 4155 // Collect the values that we need to extract from the tree. 4156 for (auto &TEPtr : VectorizableTree) { 4157 TreeEntry *Entry = TEPtr.get(); 4158 4159 // No need to handle users of gathered values. 4160 if (Entry->State == TreeEntry::NeedToGather) 4161 continue; 4162 4163 // For each lane: 4164 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 4165 Value *Scalar = Entry->Scalars[Lane]; 4166 int FoundLane = Entry->findLaneForValue(Scalar); 4167 4168 // Check if the scalar is externally used as an extra arg. 4169 auto ExtI = ExternallyUsedValues.find(Scalar); 4170 if (ExtI != ExternallyUsedValues.end()) { 4171 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " 4172 << Lane << " from " << *Scalar << ".\n"); 4173 ExternalUses.emplace_back(Scalar, nullptr, FoundLane); 4174 } 4175 for (User *U : Scalar->users()) { 4176 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n"); 4177 4178 Instruction *UserInst = dyn_cast<Instruction>(U); 4179 if (!UserInst) 4180 continue; 4181 4182 if (isDeleted(UserInst)) 4183 continue; 4184 4185 // Skip in-tree scalars that become vectors 4186 if (TreeEntry *UseEntry = getTreeEntry(U)) { 4187 Value *UseScalar = UseEntry->Scalars[0]; 4188 // Some in-tree scalars will remain as scalar in vectorized 4189 // instructions. If that is the case, the one in Lane 0 will 4190 // be used. 4191 if (UseScalar != U || 4192 UseEntry->State == TreeEntry::ScatterVectorize || 4193 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) { 4194 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U 4195 << ".\n"); 4196 assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state"); 4197 continue; 4198 } 4199 } 4200 4201 // Ignore users in the user ignore list. 4202 if (UserIgnoreList && UserIgnoreList->contains(UserInst)) 4203 continue; 4204 4205 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " 4206 << Lane << " from " << *Scalar << ".\n"); 4207 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane)); 4208 } 4209 } 4210 } 4211 } 4212 4213 DenseMap<Value *, SmallVector<StoreInst *, 4>> 4214 BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const { 4215 DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap; 4216 for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) { 4217 Value *V = TE->Scalars[Lane]; 4218 // To save compilation time we don't visit if we have too many users. 4219 static constexpr unsigned UsersLimit = 4; 4220 if (V->hasNUsesOrMore(UsersLimit)) 4221 break; 4222 4223 // Collect stores per pointer object. 4224 for (User *U : V->users()) { 4225 auto *SI = dyn_cast<StoreInst>(U); 4226 if (SI == nullptr || !SI->isSimple() || 4227 !isValidElementType(SI->getValueOperand()->getType())) 4228 continue; 4229 // Skip entry if already 4230 if (getTreeEntry(U)) 4231 continue; 4232 4233 Value *Ptr = getUnderlyingObject(SI->getPointerOperand()); 4234 auto &StoresVec = PtrToStoresMap[Ptr]; 4235 // For now just keep one store per pointer object per lane. 4236 // TODO: Extend this to support multiple stores per pointer per lane 4237 if (StoresVec.size() > Lane) 4238 continue; 4239 // Skip if in different BBs. 4240 if (!StoresVec.empty() && 4241 SI->getParent() != StoresVec.back()->getParent()) 4242 continue; 4243 // Make sure that the stores are of the same type. 4244 if (!StoresVec.empty() && 4245 SI->getValueOperand()->getType() != 4246 StoresVec.back()->getValueOperand()->getType()) 4247 continue; 4248 StoresVec.push_back(SI); 4249 } 4250 } 4251 return PtrToStoresMap; 4252 } 4253 4254 bool BoUpSLP::CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec, 4255 OrdersType &ReorderIndices) const { 4256 // We check whether the stores in StoreVec can form a vector by sorting them 4257 // and checking whether they are consecutive. 4258 4259 // To avoid calling getPointersDiff() while sorting we create a vector of 4260 // pairs {store, offset from first} and sort this instead. 4261 SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size()); 4262 StoreInst *S0 = StoresVec[0]; 4263 StoreOffsetVec[0] = {S0, 0}; 4264 Type *S0Ty = S0->getValueOperand()->getType(); 4265 Value *S0Ptr = S0->getPointerOperand(); 4266 for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) { 4267 StoreInst *SI = StoresVec[Idx]; 4268 Optional<int> Diff = 4269 getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(), 4270 SI->getPointerOperand(), *DL, *SE, 4271 /*StrictCheck=*/true); 4272 // We failed to compare the pointers so just abandon this StoresVec. 4273 if (!Diff) 4274 return false; 4275 StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff}; 4276 } 4277 4278 // Sort the vector based on the pointers. We create a copy because we may 4279 // need the original later for calculating the reorder (shuffle) indices. 4280 stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1, 4281 const std::pair<StoreInst *, int> &Pair2) { 4282 int Offset1 = Pair1.second; 4283 int Offset2 = Pair2.second; 4284 return Offset1 < Offset2; 4285 }); 4286 4287 // Check if the stores are consecutive by checking if their difference is 1. 4288 for (unsigned Idx : seq<unsigned>(1, StoreOffsetVec.size())) 4289 if (StoreOffsetVec[Idx].second != StoreOffsetVec[Idx-1].second + 1) 4290 return false; 4291 4292 // Calculate the shuffle indices according to their offset against the sorted 4293 // StoreOffsetVec. 4294 ReorderIndices.reserve(StoresVec.size()); 4295 for (StoreInst *SI : StoresVec) { 4296 unsigned Idx = find_if(StoreOffsetVec, 4297 [SI](const std::pair<StoreInst *, int> &Pair) { 4298 return Pair.first == SI; 4299 }) - 4300 StoreOffsetVec.begin(); 4301 ReorderIndices.push_back(Idx); 4302 } 4303 // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in 4304 // reorderTopToBottom() and reorderBottomToTop(), so we are following the 4305 // same convention here. 4306 auto IsIdentityOrder = [](const OrdersType &Order) { 4307 for (unsigned Idx : seq<unsigned>(0, Order.size())) 4308 if (Idx != Order[Idx]) 4309 return false; 4310 return true; 4311 }; 4312 if (IsIdentityOrder(ReorderIndices)) 4313 ReorderIndices.clear(); 4314 4315 return true; 4316 } 4317 4318 #ifndef NDEBUG 4319 LLVM_DUMP_METHOD static void dumpOrder(const BoUpSLP::OrdersType &Order) { 4320 for (unsigned Idx : Order) 4321 dbgs() << Idx << ", "; 4322 dbgs() << "\n"; 4323 } 4324 #endif 4325 4326 SmallVector<BoUpSLP::OrdersType, 1> 4327 BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const { 4328 unsigned NumLanes = TE->Scalars.size(); 4329 4330 DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap = 4331 collectUserStores(TE); 4332 4333 // Holds the reorder indices for each candidate store vector that is a user of 4334 // the current TreeEntry. 4335 SmallVector<OrdersType, 1> ExternalReorderIndices; 4336 4337 // Now inspect the stores collected per pointer and look for vectorization 4338 // candidates. For each candidate calculate the reorder index vector and push 4339 // it into `ExternalReorderIndices` 4340 for (const auto &Pair : PtrToStoresMap) { 4341 auto &StoresVec = Pair.second; 4342 // If we have fewer than NumLanes stores, then we can't form a vector. 4343 if (StoresVec.size() != NumLanes) 4344 continue; 4345 4346 // If the stores are not consecutive then abandon this StoresVec. 4347 OrdersType ReorderIndices; 4348 if (!CanFormVector(StoresVec, ReorderIndices)) 4349 continue; 4350 4351 // We now know that the scalars in StoresVec can form a vector instruction, 4352 // so set the reorder indices. 4353 ExternalReorderIndices.push_back(ReorderIndices); 4354 } 4355 return ExternalReorderIndices; 4356 } 4357 4358 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, 4359 const SmallDenseSet<Value *> &UserIgnoreLst) { 4360 deleteTree(); 4361 UserIgnoreList = &UserIgnoreLst; 4362 if (!allSameType(Roots)) 4363 return; 4364 buildTree_rec(Roots, 0, EdgeInfo()); 4365 } 4366 4367 void BoUpSLP::buildTree(ArrayRef<Value *> Roots) { 4368 deleteTree(); 4369 if (!allSameType(Roots)) 4370 return; 4371 buildTree_rec(Roots, 0, EdgeInfo()); 4372 } 4373 4374 /// \return true if the specified list of values has only one instruction that 4375 /// requires scheduling, false otherwise. 4376 #ifndef NDEBUG 4377 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) { 4378 Value *NeedsScheduling = nullptr; 4379 for (Value *V : VL) { 4380 if (doesNotNeedToBeScheduled(V)) 4381 continue; 4382 if (!NeedsScheduling) { 4383 NeedsScheduling = V; 4384 continue; 4385 } 4386 return false; 4387 } 4388 return NeedsScheduling; 4389 } 4390 #endif 4391 4392 /// Generates key/subkey pair for the given value to provide effective sorting 4393 /// of the values and better detection of the vectorizable values sequences. The 4394 /// keys/subkeys can be used for better sorting of the values themselves (keys) 4395 /// and in values subgroups (subkeys). 4396 static std::pair<size_t, size_t> generateKeySubkey( 4397 Value *V, const TargetLibraryInfo *TLI, 4398 function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator, 4399 bool AllowAlternate) { 4400 hash_code Key = hash_value(V->getValueID() + 2); 4401 hash_code SubKey = hash_value(0); 4402 // Sort the loads by the distance between the pointers. 4403 if (auto *LI = dyn_cast<LoadInst>(V)) { 4404 Key = hash_combine(hash_value(Instruction::Load), Key); 4405 if (LI->isSimple()) 4406 SubKey = hash_value(LoadsSubkeyGenerator(Key, LI)); 4407 else 4408 SubKey = hash_value(LI); 4409 } else if (isVectorLikeInstWithConstOps(V)) { 4410 // Sort extracts by the vector operands. 4411 if (isa<ExtractElementInst, UndefValue>(V)) 4412 Key = hash_value(Value::UndefValueVal + 1); 4413 if (auto *EI = dyn_cast<ExtractElementInst>(V)) { 4414 if (!isUndefVector(EI->getVectorOperand()) && 4415 !isa<UndefValue>(EI->getIndexOperand())) 4416 SubKey = hash_value(EI->getVectorOperand()); 4417 } 4418 } else if (auto *I = dyn_cast<Instruction>(V)) { 4419 // Sort other instructions just by the opcodes except for CMPInst. 4420 // For CMP also sort by the predicate kind. 4421 if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) && 4422 isValidForAlternation(I->getOpcode())) { 4423 if (AllowAlternate) 4424 Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0); 4425 else 4426 Key = hash_combine(hash_value(I->getOpcode()), Key); 4427 SubKey = hash_combine( 4428 hash_value(I->getOpcode()), hash_value(I->getType()), 4429 hash_value(isa<BinaryOperator>(I) 4430 ? I->getType() 4431 : cast<CastInst>(I)->getOperand(0)->getType())); 4432 // For casts, look through the only operand to improve compile time. 4433 if (isa<CastInst>(I)) { 4434 std::pair<size_t, size_t> OpVals = 4435 generateKeySubkey(I->getOperand(0), TLI, LoadsSubkeyGenerator, 4436 /*=AllowAlternate*/ true); 4437 Key = hash_combine(OpVals.first, Key); 4438 SubKey = hash_combine(OpVals.first, SubKey); 4439 } 4440 } else if (auto *CI = dyn_cast<CmpInst>(I)) { 4441 CmpInst::Predicate Pred = CI->getPredicate(); 4442 if (CI->isCommutative()) 4443 Pred = std::min(Pred, CmpInst::getInversePredicate(Pred)); 4444 CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred); 4445 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred), 4446 hash_value(SwapPred), 4447 hash_value(CI->getOperand(0)->getType())); 4448 } else if (auto *Call = dyn_cast<CallInst>(I)) { 4449 Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI); 4450 if (isTriviallyVectorizable(ID)) { 4451 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID)); 4452 } else if (!VFDatabase(*Call).getMappings(*Call).empty()) { 4453 SubKey = hash_combine(hash_value(I->getOpcode()), 4454 hash_value(Call->getCalledFunction())); 4455 } else { 4456 Key = hash_combine(hash_value(Call), Key); 4457 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call)); 4458 } 4459 for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos()) 4460 SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End), 4461 hash_value(Op.Tag), SubKey); 4462 } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) { 4463 if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1))) 4464 SubKey = hash_value(Gep->getPointerOperand()); 4465 else 4466 SubKey = hash_value(Gep); 4467 } else if (BinaryOperator::isIntDivRem(I->getOpcode()) && 4468 !isa<ConstantInt>(I->getOperand(1))) { 4469 // Do not try to vectorize instructions with potentially high cost. 4470 SubKey = hash_value(I); 4471 } else { 4472 SubKey = hash_value(I->getOpcode()); 4473 } 4474 Key = hash_combine(hash_value(I->getParent()), Key); 4475 } 4476 return std::make_pair(Key, SubKey); 4477 } 4478 4479 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth, 4480 const EdgeInfo &UserTreeIdx) { 4481 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!"); 4482 4483 SmallVector<int> ReuseShuffleIndicies; 4484 SmallVector<Value *> UniqueValues; 4485 auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues, 4486 &UserTreeIdx, 4487 this](const InstructionsState &S) { 4488 // Check that every instruction appears once in this bundle. 4489 DenseMap<Value *, unsigned> UniquePositions; 4490 for (Value *V : VL) { 4491 if (isConstant(V)) { 4492 ReuseShuffleIndicies.emplace_back( 4493 isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size()); 4494 UniqueValues.emplace_back(V); 4495 continue; 4496 } 4497 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 4498 ReuseShuffleIndicies.emplace_back(Res.first->second); 4499 if (Res.second) 4500 UniqueValues.emplace_back(V); 4501 } 4502 size_t NumUniqueScalarValues = UniqueValues.size(); 4503 if (NumUniqueScalarValues == VL.size()) { 4504 ReuseShuffleIndicies.clear(); 4505 } else { 4506 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n"); 4507 if (NumUniqueScalarValues <= 1 || 4508 (UniquePositions.size() == 1 && all_of(UniqueValues, 4509 [](Value *V) { 4510 return isa<UndefValue>(V) || 4511 !isConstant(V); 4512 })) || 4513 !llvm::isPowerOf2_32(NumUniqueScalarValues)) { 4514 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); 4515 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4516 return false; 4517 } 4518 VL = UniqueValues; 4519 } 4520 return true; 4521 }; 4522 4523 InstructionsState S = getSameOpcode(VL); 4524 if (Depth == RecursionMaxDepth) { 4525 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); 4526 if (TryToFindDuplicates(S)) 4527 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4528 ReuseShuffleIndicies); 4529 return; 4530 } 4531 4532 // Don't handle scalable vectors 4533 if (S.getOpcode() == Instruction::ExtractElement && 4534 isa<ScalableVectorType>( 4535 cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) { 4536 LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n"); 4537 if (TryToFindDuplicates(S)) 4538 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4539 ReuseShuffleIndicies); 4540 return; 4541 } 4542 4543 // Don't handle vectors. 4544 if (S.OpValue->getType()->isVectorTy() && 4545 !isa<InsertElementInst>(S.OpValue)) { 4546 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); 4547 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4548 return; 4549 } 4550 4551 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue)) 4552 if (SI->getValueOperand()->getType()->isVectorTy()) { 4553 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); 4554 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4555 return; 4556 } 4557 4558 // If all of the operands are identical or constant we have a simple solution. 4559 // If we deal with insert/extract instructions, they all must have constant 4560 // indices, otherwise we should gather them, not try to vectorize. 4561 // If alternate op node with 2 elements with gathered operands - do not 4562 // vectorize. 4563 auto &&NotProfitableForVectorization = [&S, this, 4564 Depth](ArrayRef<Value *> VL) { 4565 if (!S.getOpcode() || !S.isAltShuffle() || VL.size() > 2) 4566 return false; 4567 if (VectorizableTree.size() < MinTreeSize) 4568 return false; 4569 if (Depth >= RecursionMaxDepth - 1) 4570 return true; 4571 // Check if all operands are extracts, part of vector node or can build a 4572 // regular vectorize node. 4573 SmallVector<unsigned, 2> InstsCount(VL.size(), 0); 4574 for (Value *V : VL) { 4575 auto *I = cast<Instruction>(V); 4576 InstsCount.push_back(count_if(I->operand_values(), [](Value *Op) { 4577 return isa<Instruction>(Op) || isVectorLikeInstWithConstOps(Op); 4578 })); 4579 } 4580 bool IsCommutative = isCommutative(S.MainOp) || isCommutative(S.AltOp); 4581 if ((IsCommutative && 4582 std::accumulate(InstsCount.begin(), InstsCount.end(), 0) < 2) || 4583 (!IsCommutative && 4584 all_of(InstsCount, [](unsigned ICnt) { return ICnt < 2; }))) 4585 return true; 4586 assert(VL.size() == 2 && "Expected only 2 alternate op instructions."); 4587 SmallVector<SmallVector<std::pair<Value *, Value *>>> Candidates; 4588 auto *I1 = cast<Instruction>(VL.front()); 4589 auto *I2 = cast<Instruction>(VL.back()); 4590 for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op) 4591 Candidates.emplace_back().emplace_back(I1->getOperand(Op), 4592 I2->getOperand(Op)); 4593 if (count_if( 4594 Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) { 4595 return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat); 4596 }) >= S.MainOp->getNumOperands() / 2) 4597 return false; 4598 if (S.MainOp->getNumOperands() > 2) 4599 return true; 4600 if (IsCommutative) { 4601 // Check permuted operands. 4602 Candidates.clear(); 4603 for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op) 4604 Candidates.emplace_back().emplace_back(I1->getOperand(Op), 4605 I2->getOperand((Op + 1) % E)); 4606 if (any_of( 4607 Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) { 4608 return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat); 4609 })) 4610 return false; 4611 } 4612 return true; 4613 }; 4614 if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() || 4615 (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) && 4616 !all_of(VL, isVectorLikeInstWithConstOps)) || 4617 NotProfitableForVectorization(VL)) { 4618 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O, small shuffle. \n"); 4619 if (TryToFindDuplicates(S)) 4620 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4621 ReuseShuffleIndicies); 4622 return; 4623 } 4624 4625 // We now know that this is a vector of instructions of the same type from 4626 // the same block. 4627 4628 // Don't vectorize ephemeral values. 4629 if (!EphValues.empty()) { 4630 for (Value *V : VL) { 4631 if (EphValues.count(V)) { 4632 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 4633 << ") is ephemeral.\n"); 4634 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4635 return; 4636 } 4637 } 4638 } 4639 4640 // Check if this is a duplicate of another entry. 4641 if (TreeEntry *E = getTreeEntry(S.OpValue)) { 4642 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n"); 4643 if (!E->isSame(VL)) { 4644 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); 4645 if (TryToFindDuplicates(S)) 4646 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4647 ReuseShuffleIndicies); 4648 return; 4649 } 4650 // Record the reuse of the tree node. FIXME, currently this is only used to 4651 // properly draw the graph rather than for the actual vectorization. 4652 E->UserTreeIndices.push_back(UserTreeIdx); 4653 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue 4654 << ".\n"); 4655 return; 4656 } 4657 4658 // Check that none of the instructions in the bundle are already in the tree. 4659 for (Value *V : VL) { 4660 auto *I = dyn_cast<Instruction>(V); 4661 if (!I) 4662 continue; 4663 if (getTreeEntry(I)) { 4664 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 4665 << ") is already in tree.\n"); 4666 if (TryToFindDuplicates(S)) 4667 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4668 ReuseShuffleIndicies); 4669 return; 4670 } 4671 } 4672 4673 // The reduction nodes (stored in UserIgnoreList) also should stay scalar. 4674 if (UserIgnoreList && !UserIgnoreList->empty()) { 4675 for (Value *V : VL) { 4676 if (UserIgnoreList && UserIgnoreList->contains(V)) { 4677 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n"); 4678 if (TryToFindDuplicates(S)) 4679 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4680 ReuseShuffleIndicies); 4681 return; 4682 } 4683 } 4684 } 4685 4686 // Check that all of the users of the scalars that we want to vectorize are 4687 // schedulable. 4688 auto *VL0 = cast<Instruction>(S.OpValue); 4689 BasicBlock *BB = VL0->getParent(); 4690 4691 if (!DT->isReachableFromEntry(BB)) { 4692 // Don't go into unreachable blocks. They may contain instructions with 4693 // dependency cycles which confuse the final scheduling. 4694 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n"); 4695 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4696 return; 4697 } 4698 4699 // Check that every instruction appears once in this bundle. 4700 if (!TryToFindDuplicates(S)) 4701 return; 4702 4703 auto &BSRef = BlocksSchedules[BB]; 4704 if (!BSRef) 4705 BSRef = std::make_unique<BlockScheduling>(BB); 4706 4707 BlockScheduling &BS = *BSRef; 4708 4709 Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S); 4710 #ifdef EXPENSIVE_CHECKS 4711 // Make sure we didn't break any internal invariants 4712 BS.verify(); 4713 #endif 4714 if (!Bundle) { 4715 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n"); 4716 assert((!BS.getScheduleData(VL0) || 4717 !BS.getScheduleData(VL0)->isPartOfBundle()) && 4718 "tryScheduleBundle should cancelScheduling on failure"); 4719 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4720 ReuseShuffleIndicies); 4721 return; 4722 } 4723 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); 4724 4725 unsigned ShuffleOrOp = S.isAltShuffle() ? 4726 (unsigned) Instruction::ShuffleVector : S.getOpcode(); 4727 switch (ShuffleOrOp) { 4728 case Instruction::PHI: { 4729 auto *PH = cast<PHINode>(VL0); 4730 4731 // Check for terminator values (e.g. invoke). 4732 for (Value *V : VL) 4733 for (Value *Incoming : cast<PHINode>(V)->incoming_values()) { 4734 Instruction *Term = dyn_cast<Instruction>(Incoming); 4735 if (Term && Term->isTerminator()) { 4736 LLVM_DEBUG(dbgs() 4737 << "SLP: Need to swizzle PHINodes (terminator use).\n"); 4738 BS.cancelScheduling(VL, VL0); 4739 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4740 ReuseShuffleIndicies); 4741 return; 4742 } 4743 } 4744 4745 TreeEntry *TE = 4746 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies); 4747 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); 4748 4749 // Keeps the reordered operands to avoid code duplication. 4750 SmallVector<ValueList, 2> OperandsVec; 4751 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 4752 if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) { 4753 ValueList Operands(VL.size(), PoisonValue::get(PH->getType())); 4754 TE->setOperand(I, Operands); 4755 OperandsVec.push_back(Operands); 4756 continue; 4757 } 4758 ValueList Operands; 4759 // Prepare the operand vector. 4760 for (Value *V : VL) 4761 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock( 4762 PH->getIncomingBlock(I))); 4763 TE->setOperand(I, Operands); 4764 OperandsVec.push_back(Operands); 4765 } 4766 for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx) 4767 buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx}); 4768 return; 4769 } 4770 case Instruction::ExtractValue: 4771 case Instruction::ExtractElement: { 4772 OrdersType CurrentOrder; 4773 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder); 4774 if (Reuse) { 4775 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n"); 4776 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4777 ReuseShuffleIndicies); 4778 // This is a special case, as it does not gather, but at the same time 4779 // we are not extending buildTree_rec() towards the operands. 4780 ValueList Op0; 4781 Op0.assign(VL.size(), VL0->getOperand(0)); 4782 VectorizableTree.back()->setOperand(0, Op0); 4783 return; 4784 } 4785 if (!CurrentOrder.empty()) { 4786 LLVM_DEBUG({ 4787 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " 4788 "with order"; 4789 for (unsigned Idx : CurrentOrder) 4790 dbgs() << " " << Idx; 4791 dbgs() << "\n"; 4792 }); 4793 fixupOrderingIndices(CurrentOrder); 4794 // Insert new order with initial value 0, if it does not exist, 4795 // otherwise return the iterator to the existing one. 4796 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4797 ReuseShuffleIndicies, CurrentOrder); 4798 // This is a special case, as it does not gather, but at the same time 4799 // we are not extending buildTree_rec() towards the operands. 4800 ValueList Op0; 4801 Op0.assign(VL.size(), VL0->getOperand(0)); 4802 VectorizableTree.back()->setOperand(0, Op0); 4803 return; 4804 } 4805 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n"); 4806 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4807 ReuseShuffleIndicies); 4808 BS.cancelScheduling(VL, VL0); 4809 return; 4810 } 4811 case Instruction::InsertElement: { 4812 assert(ReuseShuffleIndicies.empty() && "All inserts should be unique"); 4813 4814 // Check that we have a buildvector and not a shuffle of 2 or more 4815 // different vectors. 4816 ValueSet SourceVectors; 4817 for (Value *V : VL) { 4818 SourceVectors.insert(cast<Instruction>(V)->getOperand(0)); 4819 assert(getInsertIndex(V) != None && "Non-constant or undef index?"); 4820 } 4821 4822 if (count_if(VL, [&SourceVectors](Value *V) { 4823 return !SourceVectors.contains(V); 4824 }) >= 2) { 4825 // Found 2nd source vector - cancel. 4826 LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with " 4827 "different source vectors.\n"); 4828 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4829 BS.cancelScheduling(VL, VL0); 4830 return; 4831 } 4832 4833 auto OrdCompare = [](const std::pair<int, int> &P1, 4834 const std::pair<int, int> &P2) { 4835 return P1.first > P2.first; 4836 }; 4837 PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>, 4838 decltype(OrdCompare)> 4839 Indices(OrdCompare); 4840 for (int I = 0, E = VL.size(); I < E; ++I) { 4841 unsigned Idx = *getInsertIndex(VL[I]); 4842 Indices.emplace(Idx, I); 4843 } 4844 OrdersType CurrentOrder(VL.size(), VL.size()); 4845 bool IsIdentity = true; 4846 for (int I = 0, E = VL.size(); I < E; ++I) { 4847 CurrentOrder[Indices.top().second] = I; 4848 IsIdentity &= Indices.top().second == I; 4849 Indices.pop(); 4850 } 4851 if (IsIdentity) 4852 CurrentOrder.clear(); 4853 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4854 None, CurrentOrder); 4855 LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n"); 4856 4857 constexpr int NumOps = 2; 4858 ValueList VectorOperands[NumOps]; 4859 for (int I = 0; I < NumOps; ++I) { 4860 for (Value *V : VL) 4861 VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I)); 4862 4863 TE->setOperand(I, VectorOperands[I]); 4864 } 4865 buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1}); 4866 return; 4867 } 4868 case Instruction::Load: { 4869 // Check that a vectorized load would load the same memory as a scalar 4870 // load. For example, we don't want to vectorize loads that are smaller 4871 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 4872 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 4873 // from such a struct, we read/write packed bits disagreeing with the 4874 // unvectorized version. 4875 SmallVector<Value *> PointerOps; 4876 OrdersType CurrentOrder; 4877 TreeEntry *TE = nullptr; 4878 switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder, 4879 PointerOps)) { 4880 case LoadsState::Vectorize: 4881 if (CurrentOrder.empty()) { 4882 // Original loads are consecutive and does not require reordering. 4883 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4884 ReuseShuffleIndicies); 4885 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n"); 4886 } else { 4887 fixupOrderingIndices(CurrentOrder); 4888 // Need to reorder. 4889 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4890 ReuseShuffleIndicies, CurrentOrder); 4891 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n"); 4892 } 4893 TE->setOperandsInOrder(); 4894 break; 4895 case LoadsState::ScatterVectorize: 4896 // Vectorizing non-consecutive loads with `llvm.masked.gather`. 4897 TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S, 4898 UserTreeIdx, ReuseShuffleIndicies); 4899 TE->setOperandsInOrder(); 4900 buildTree_rec(PointerOps, Depth + 1, {TE, 0}); 4901 LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n"); 4902 break; 4903 case LoadsState::Gather: 4904 BS.cancelScheduling(VL, VL0); 4905 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4906 ReuseShuffleIndicies); 4907 #ifndef NDEBUG 4908 Type *ScalarTy = VL0->getType(); 4909 if (DL->getTypeSizeInBits(ScalarTy) != 4910 DL->getTypeAllocSizeInBits(ScalarTy)) 4911 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n"); 4912 else if (any_of(VL, [](Value *V) { 4913 return !cast<LoadInst>(V)->isSimple(); 4914 })) 4915 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n"); 4916 else 4917 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n"); 4918 #endif // NDEBUG 4919 break; 4920 } 4921 return; 4922 } 4923 case Instruction::ZExt: 4924 case Instruction::SExt: 4925 case Instruction::FPToUI: 4926 case Instruction::FPToSI: 4927 case Instruction::FPExt: 4928 case Instruction::PtrToInt: 4929 case Instruction::IntToPtr: 4930 case Instruction::SIToFP: 4931 case Instruction::UIToFP: 4932 case Instruction::Trunc: 4933 case Instruction::FPTrunc: 4934 case Instruction::BitCast: { 4935 Type *SrcTy = VL0->getOperand(0)->getType(); 4936 for (Value *V : VL) { 4937 Type *Ty = cast<Instruction>(V)->getOperand(0)->getType(); 4938 if (Ty != SrcTy || !isValidElementType(Ty)) { 4939 BS.cancelScheduling(VL, VL0); 4940 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4941 ReuseShuffleIndicies); 4942 LLVM_DEBUG(dbgs() 4943 << "SLP: Gathering casts with different src types.\n"); 4944 return; 4945 } 4946 } 4947 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4948 ReuseShuffleIndicies); 4949 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n"); 4950 4951 TE->setOperandsInOrder(); 4952 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4953 ValueList Operands; 4954 // Prepare the operand vector. 4955 for (Value *V : VL) 4956 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4957 4958 buildTree_rec(Operands, Depth + 1, {TE, i}); 4959 } 4960 return; 4961 } 4962 case Instruction::ICmp: 4963 case Instruction::FCmp: { 4964 // Check that all of the compares have the same predicate. 4965 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 4966 CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0); 4967 Type *ComparedTy = VL0->getOperand(0)->getType(); 4968 for (Value *V : VL) { 4969 CmpInst *Cmp = cast<CmpInst>(V); 4970 if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) || 4971 Cmp->getOperand(0)->getType() != ComparedTy) { 4972 BS.cancelScheduling(VL, VL0); 4973 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4974 ReuseShuffleIndicies); 4975 LLVM_DEBUG(dbgs() 4976 << "SLP: Gathering cmp with different predicate.\n"); 4977 return; 4978 } 4979 } 4980 4981 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4982 ReuseShuffleIndicies); 4983 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n"); 4984 4985 ValueList Left, Right; 4986 if (cast<CmpInst>(VL0)->isCommutative()) { 4987 // Commutative predicate - collect + sort operands of the instructions 4988 // so that each side is more likely to have the same opcode. 4989 assert(P0 == SwapP0 && "Commutative Predicate mismatch"); 4990 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4991 } else { 4992 // Collect operands - commute if it uses the swapped predicate. 4993 for (Value *V : VL) { 4994 auto *Cmp = cast<CmpInst>(V); 4995 Value *LHS = Cmp->getOperand(0); 4996 Value *RHS = Cmp->getOperand(1); 4997 if (Cmp->getPredicate() != P0) 4998 std::swap(LHS, RHS); 4999 Left.push_back(LHS); 5000 Right.push_back(RHS); 5001 } 5002 } 5003 TE->setOperand(0, Left); 5004 TE->setOperand(1, Right); 5005 buildTree_rec(Left, Depth + 1, {TE, 0}); 5006 buildTree_rec(Right, Depth + 1, {TE, 1}); 5007 return; 5008 } 5009 case Instruction::Select: 5010 case Instruction::FNeg: 5011 case Instruction::Add: 5012 case Instruction::FAdd: 5013 case Instruction::Sub: 5014 case Instruction::FSub: 5015 case Instruction::Mul: 5016 case Instruction::FMul: 5017 case Instruction::UDiv: 5018 case Instruction::SDiv: 5019 case Instruction::FDiv: 5020 case Instruction::URem: 5021 case Instruction::SRem: 5022 case Instruction::FRem: 5023 case Instruction::Shl: 5024 case Instruction::LShr: 5025 case Instruction::AShr: 5026 case Instruction::And: 5027 case Instruction::Or: 5028 case Instruction::Xor: { 5029 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5030 ReuseShuffleIndicies); 5031 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n"); 5032 5033 // Sort operands of the instructions so that each side is more likely to 5034 // have the same opcode. 5035 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) { 5036 ValueList Left, Right; 5037 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 5038 TE->setOperand(0, Left); 5039 TE->setOperand(1, Right); 5040 buildTree_rec(Left, Depth + 1, {TE, 0}); 5041 buildTree_rec(Right, Depth + 1, {TE, 1}); 5042 return; 5043 } 5044 5045 TE->setOperandsInOrder(); 5046 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 5047 ValueList Operands; 5048 // Prepare the operand vector. 5049 for (Value *V : VL) 5050 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 5051 5052 buildTree_rec(Operands, Depth + 1, {TE, i}); 5053 } 5054 return; 5055 } 5056 case Instruction::GetElementPtr: { 5057 // We don't combine GEPs with complicated (nested) indexing. 5058 for (Value *V : VL) { 5059 if (cast<Instruction>(V)->getNumOperands() != 2) { 5060 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"); 5061 BS.cancelScheduling(VL, VL0); 5062 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5063 ReuseShuffleIndicies); 5064 return; 5065 } 5066 } 5067 5068 // We can't combine several GEPs into one vector if they operate on 5069 // different types. 5070 Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType(); 5071 for (Value *V : VL) { 5072 Type *CurTy = cast<GEPOperator>(V)->getSourceElementType(); 5073 if (Ty0 != CurTy) { 5074 LLVM_DEBUG(dbgs() 5075 << "SLP: not-vectorizable GEP (different types).\n"); 5076 BS.cancelScheduling(VL, VL0); 5077 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5078 ReuseShuffleIndicies); 5079 return; 5080 } 5081 } 5082 5083 // We don't combine GEPs with non-constant indexes. 5084 Type *Ty1 = VL0->getOperand(1)->getType(); 5085 for (Value *V : VL) { 5086 auto Op = cast<Instruction>(V)->getOperand(1); 5087 if (!isa<ConstantInt>(Op) || 5088 (Op->getType() != Ty1 && 5089 Op->getType()->getScalarSizeInBits() > 5090 DL->getIndexSizeInBits( 5091 V->getType()->getPointerAddressSpace()))) { 5092 LLVM_DEBUG(dbgs() 5093 << "SLP: not-vectorizable GEP (non-constant indexes).\n"); 5094 BS.cancelScheduling(VL, VL0); 5095 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5096 ReuseShuffleIndicies); 5097 return; 5098 } 5099 } 5100 5101 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5102 ReuseShuffleIndicies); 5103 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n"); 5104 SmallVector<ValueList, 2> Operands(2); 5105 // Prepare the operand vector for pointer operands. 5106 for (Value *V : VL) 5107 Operands.front().push_back( 5108 cast<GetElementPtrInst>(V)->getPointerOperand()); 5109 TE->setOperand(0, Operands.front()); 5110 // Need to cast all indices to the same type before vectorization to 5111 // avoid crash. 5112 // Required to be able to find correct matches between different gather 5113 // nodes and reuse the vectorized values rather than trying to gather them 5114 // again. 5115 int IndexIdx = 1; 5116 Type *VL0Ty = VL0->getOperand(IndexIdx)->getType(); 5117 Type *Ty = all_of(VL, 5118 [VL0Ty, IndexIdx](Value *V) { 5119 return VL0Ty == cast<GetElementPtrInst>(V) 5120 ->getOperand(IndexIdx) 5121 ->getType(); 5122 }) 5123 ? VL0Ty 5124 : DL->getIndexType(cast<GetElementPtrInst>(VL0) 5125 ->getPointerOperandType() 5126 ->getScalarType()); 5127 // Prepare the operand vector. 5128 for (Value *V : VL) { 5129 auto *Op = cast<Instruction>(V)->getOperand(IndexIdx); 5130 auto *CI = cast<ConstantInt>(Op); 5131 Operands.back().push_back(ConstantExpr::getIntegerCast( 5132 CI, Ty, CI->getValue().isSignBitSet())); 5133 } 5134 TE->setOperand(IndexIdx, Operands.back()); 5135 5136 for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I) 5137 buildTree_rec(Operands[I], Depth + 1, {TE, I}); 5138 return; 5139 } 5140 case Instruction::Store: { 5141 // Check if the stores are consecutive or if we need to swizzle them. 5142 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType(); 5143 // Avoid types that are padded when being allocated as scalars, while 5144 // being packed together in a vector (such as i1). 5145 if (DL->getTypeSizeInBits(ScalarTy) != 5146 DL->getTypeAllocSizeInBits(ScalarTy)) { 5147 BS.cancelScheduling(VL, VL0); 5148 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5149 ReuseShuffleIndicies); 5150 LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n"); 5151 return; 5152 } 5153 // Make sure all stores in the bundle are simple - we can't vectorize 5154 // atomic or volatile stores. 5155 SmallVector<Value *, 4> PointerOps(VL.size()); 5156 ValueList Operands(VL.size()); 5157 auto POIter = PointerOps.begin(); 5158 auto OIter = Operands.begin(); 5159 for (Value *V : VL) { 5160 auto *SI = cast<StoreInst>(V); 5161 if (!SI->isSimple()) { 5162 BS.cancelScheduling(VL, VL0); 5163 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5164 ReuseShuffleIndicies); 5165 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n"); 5166 return; 5167 } 5168 *POIter = SI->getPointerOperand(); 5169 *OIter = SI->getValueOperand(); 5170 ++POIter; 5171 ++OIter; 5172 } 5173 5174 OrdersType CurrentOrder; 5175 // Check the order of pointer operands. 5176 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) { 5177 Value *Ptr0; 5178 Value *PtrN; 5179 if (CurrentOrder.empty()) { 5180 Ptr0 = PointerOps.front(); 5181 PtrN = PointerOps.back(); 5182 } else { 5183 Ptr0 = PointerOps[CurrentOrder.front()]; 5184 PtrN = PointerOps[CurrentOrder.back()]; 5185 } 5186 Optional<int> Dist = 5187 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE); 5188 // Check that the sorted pointer operands are consecutive. 5189 if (static_cast<unsigned>(*Dist) == VL.size() - 1) { 5190 if (CurrentOrder.empty()) { 5191 // Original stores are consecutive and does not require reordering. 5192 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, 5193 UserTreeIdx, ReuseShuffleIndicies); 5194 TE->setOperandsInOrder(); 5195 buildTree_rec(Operands, Depth + 1, {TE, 0}); 5196 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n"); 5197 } else { 5198 fixupOrderingIndices(CurrentOrder); 5199 TreeEntry *TE = 5200 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5201 ReuseShuffleIndicies, CurrentOrder); 5202 TE->setOperandsInOrder(); 5203 buildTree_rec(Operands, Depth + 1, {TE, 0}); 5204 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n"); 5205 } 5206 return; 5207 } 5208 } 5209 5210 BS.cancelScheduling(VL, VL0); 5211 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5212 ReuseShuffleIndicies); 5213 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n"); 5214 return; 5215 } 5216 case Instruction::Call: { 5217 // Check if the calls are all to the same vectorizable intrinsic or 5218 // library function. 5219 CallInst *CI = cast<CallInst>(VL0); 5220 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 5221 5222 VFShape Shape = VFShape::get( 5223 *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())), 5224 false /*HasGlobalPred*/); 5225 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 5226 5227 if (!VecFunc && !isTriviallyVectorizable(ID)) { 5228 BS.cancelScheduling(VL, VL0); 5229 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5230 ReuseShuffleIndicies); 5231 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n"); 5232 return; 5233 } 5234 Function *F = CI->getCalledFunction(); 5235 unsigned NumArgs = CI->arg_size(); 5236 SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr); 5237 for (unsigned j = 0; j != NumArgs; ++j) 5238 if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) 5239 ScalarArgs[j] = CI->getArgOperand(j); 5240 for (Value *V : VL) { 5241 CallInst *CI2 = dyn_cast<CallInst>(V); 5242 if (!CI2 || CI2->getCalledFunction() != F || 5243 getVectorIntrinsicIDForCall(CI2, TLI) != ID || 5244 (VecFunc && 5245 VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) || 5246 !CI->hasIdenticalOperandBundleSchema(*CI2)) { 5247 BS.cancelScheduling(VL, VL0); 5248 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5249 ReuseShuffleIndicies); 5250 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V 5251 << "\n"); 5252 return; 5253 } 5254 // Some intrinsics have scalar arguments and should be same in order for 5255 // them to be vectorized. 5256 for (unsigned j = 0; j != NumArgs; ++j) { 5257 if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) { 5258 Value *A1J = CI2->getArgOperand(j); 5259 if (ScalarArgs[j] != A1J) { 5260 BS.cancelScheduling(VL, VL0); 5261 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5262 ReuseShuffleIndicies); 5263 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI 5264 << " argument " << ScalarArgs[j] << "!=" << A1J 5265 << "\n"); 5266 return; 5267 } 5268 } 5269 } 5270 // Verify that the bundle operands are identical between the two calls. 5271 if (CI->hasOperandBundles() && 5272 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(), 5273 CI->op_begin() + CI->getBundleOperandsEndIndex(), 5274 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) { 5275 BS.cancelScheduling(VL, VL0); 5276 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5277 ReuseShuffleIndicies); 5278 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" 5279 << *CI << "!=" << *V << '\n'); 5280 return; 5281 } 5282 } 5283 5284 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5285 ReuseShuffleIndicies); 5286 TE->setOperandsInOrder(); 5287 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 5288 // For scalar operands no need to to create an entry since no need to 5289 // vectorize it. 5290 if (isVectorIntrinsicWithScalarOpAtArg(ID, i)) 5291 continue; 5292 ValueList Operands; 5293 // Prepare the operand vector. 5294 for (Value *V : VL) { 5295 auto *CI2 = cast<CallInst>(V); 5296 Operands.push_back(CI2->getArgOperand(i)); 5297 } 5298 buildTree_rec(Operands, Depth + 1, {TE, i}); 5299 } 5300 return; 5301 } 5302 case Instruction::ShuffleVector: { 5303 // If this is not an alternate sequence of opcode like add-sub 5304 // then do not vectorize this instruction. 5305 if (!S.isAltShuffle()) { 5306 BS.cancelScheduling(VL, VL0); 5307 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5308 ReuseShuffleIndicies); 5309 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n"); 5310 return; 5311 } 5312 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5313 ReuseShuffleIndicies); 5314 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n"); 5315 5316 // Reorder operands if reordering would enable vectorization. 5317 auto *CI = dyn_cast<CmpInst>(VL0); 5318 if (isa<BinaryOperator>(VL0) || CI) { 5319 ValueList Left, Right; 5320 if (!CI || all_of(VL, [](Value *V) { 5321 return cast<CmpInst>(V)->isCommutative(); 5322 })) { 5323 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 5324 } else { 5325 CmpInst::Predicate P0 = CI->getPredicate(); 5326 CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate(); 5327 assert(P0 != AltP0 && 5328 "Expected different main/alternate predicates."); 5329 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 5330 Value *BaseOp0 = VL0->getOperand(0); 5331 Value *BaseOp1 = VL0->getOperand(1); 5332 // Collect operands - commute if it uses the swapped predicate or 5333 // alternate operation. 5334 for (Value *V : VL) { 5335 auto *Cmp = cast<CmpInst>(V); 5336 Value *LHS = Cmp->getOperand(0); 5337 Value *RHS = Cmp->getOperand(1); 5338 CmpInst::Predicate CurrentPred = Cmp->getPredicate(); 5339 if (P0 == AltP0Swapped) { 5340 if (CI != Cmp && S.AltOp != Cmp && 5341 ((P0 == CurrentPred && 5342 !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) || 5343 (AltP0 == CurrentPred && 5344 areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)))) 5345 std::swap(LHS, RHS); 5346 } else if (P0 != CurrentPred && AltP0 != CurrentPred) { 5347 std::swap(LHS, RHS); 5348 } 5349 Left.push_back(LHS); 5350 Right.push_back(RHS); 5351 } 5352 } 5353 TE->setOperand(0, Left); 5354 TE->setOperand(1, Right); 5355 buildTree_rec(Left, Depth + 1, {TE, 0}); 5356 buildTree_rec(Right, Depth + 1, {TE, 1}); 5357 return; 5358 } 5359 5360 TE->setOperandsInOrder(); 5361 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 5362 ValueList Operands; 5363 // Prepare the operand vector. 5364 for (Value *V : VL) 5365 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 5366 5367 buildTree_rec(Operands, Depth + 1, {TE, i}); 5368 } 5369 return; 5370 } 5371 default: 5372 BS.cancelScheduling(VL, VL0); 5373 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5374 ReuseShuffleIndicies); 5375 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); 5376 return; 5377 } 5378 } 5379 5380 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const { 5381 unsigned N = 1; 5382 Type *EltTy = T; 5383 5384 while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) || 5385 isa<VectorType>(EltTy)) { 5386 if (auto *ST = dyn_cast<StructType>(EltTy)) { 5387 // Check that struct is homogeneous. 5388 for (const auto *Ty : ST->elements()) 5389 if (Ty != *ST->element_begin()) 5390 return 0; 5391 N *= ST->getNumElements(); 5392 EltTy = *ST->element_begin(); 5393 } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) { 5394 N *= AT->getNumElements(); 5395 EltTy = AT->getElementType(); 5396 } else { 5397 auto *VT = cast<FixedVectorType>(EltTy); 5398 N *= VT->getNumElements(); 5399 EltTy = VT->getElementType(); 5400 } 5401 } 5402 5403 if (!isValidElementType(EltTy)) 5404 return 0; 5405 uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N)); 5406 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T)) 5407 return 0; 5408 return N; 5409 } 5410 5411 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 5412 SmallVectorImpl<unsigned> &CurrentOrder) const { 5413 const auto *It = find_if(VL, [](Value *V) { 5414 return isa<ExtractElementInst, ExtractValueInst>(V); 5415 }); 5416 assert(It != VL.end() && "Expected at least one extract instruction."); 5417 auto *E0 = cast<Instruction>(*It); 5418 assert(all_of(VL, 5419 [](Value *V) { 5420 return isa<UndefValue, ExtractElementInst, ExtractValueInst>( 5421 V); 5422 }) && 5423 "Invalid opcode"); 5424 // Check if all of the extracts come from the same vector and from the 5425 // correct offset. 5426 Value *Vec = E0->getOperand(0); 5427 5428 CurrentOrder.clear(); 5429 5430 // We have to extract from a vector/aggregate with the same number of elements. 5431 unsigned NElts; 5432 if (E0->getOpcode() == Instruction::ExtractValue) { 5433 const DataLayout &DL = E0->getModule()->getDataLayout(); 5434 NElts = canMapToVector(Vec->getType(), DL); 5435 if (!NElts) 5436 return false; 5437 // Check if load can be rewritten as load of vector. 5438 LoadInst *LI = dyn_cast<LoadInst>(Vec); 5439 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size())) 5440 return false; 5441 } else { 5442 NElts = cast<FixedVectorType>(Vec->getType())->getNumElements(); 5443 } 5444 5445 if (NElts != VL.size()) 5446 return false; 5447 5448 // Check that all of the indices extract from the correct offset. 5449 bool ShouldKeepOrder = true; 5450 unsigned E = VL.size(); 5451 // Assign to all items the initial value E + 1 so we can check if the extract 5452 // instruction index was used already. 5453 // Also, later we can check that all the indices are used and we have a 5454 // consecutive access in the extract instructions, by checking that no 5455 // element of CurrentOrder still has value E + 1. 5456 CurrentOrder.assign(E, E); 5457 unsigned I = 0; 5458 for (; I < E; ++I) { 5459 auto *Inst = dyn_cast<Instruction>(VL[I]); 5460 if (!Inst) 5461 continue; 5462 if (Inst->getOperand(0) != Vec) 5463 break; 5464 if (auto *EE = dyn_cast<ExtractElementInst>(Inst)) 5465 if (isa<UndefValue>(EE->getIndexOperand())) 5466 continue; 5467 Optional<unsigned> Idx = getExtractIndex(Inst); 5468 if (!Idx) 5469 break; 5470 const unsigned ExtIdx = *Idx; 5471 if (ExtIdx != I) { 5472 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E) 5473 break; 5474 ShouldKeepOrder = false; 5475 CurrentOrder[ExtIdx] = I; 5476 } else { 5477 if (CurrentOrder[I] != E) 5478 break; 5479 CurrentOrder[I] = I; 5480 } 5481 } 5482 if (I < E) { 5483 CurrentOrder.clear(); 5484 return false; 5485 } 5486 if (ShouldKeepOrder) 5487 CurrentOrder.clear(); 5488 5489 return ShouldKeepOrder; 5490 } 5491 5492 bool BoUpSLP::areAllUsersVectorized(Instruction *I, 5493 ArrayRef<Value *> VectorizedVals) const { 5494 return (I->hasOneUse() && is_contained(VectorizedVals, I)) || 5495 all_of(I->users(), [this](User *U) { 5496 return ScalarToTreeEntry.count(U) > 0 || 5497 isVectorLikeInstWithConstOps(U) || 5498 (isa<ExtractElementInst>(U) && MustGather.contains(U)); 5499 }); 5500 } 5501 5502 static std::pair<InstructionCost, InstructionCost> 5503 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy, 5504 TargetTransformInfo *TTI, TargetLibraryInfo *TLI) { 5505 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 5506 5507 // Calculate the cost of the scalar and vector calls. 5508 SmallVector<Type *, 4> VecTys; 5509 for (Use &Arg : CI->args()) 5510 VecTys.push_back( 5511 FixedVectorType::get(Arg->getType(), VecTy->getNumElements())); 5512 FastMathFlags FMF; 5513 if (auto *FPCI = dyn_cast<FPMathOperator>(CI)) 5514 FMF = FPCI->getFastMathFlags(); 5515 SmallVector<const Value *> Arguments(CI->args()); 5516 IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF, 5517 dyn_cast<IntrinsicInst>(CI)); 5518 auto IntrinsicCost = 5519 TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput); 5520 5521 auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 5522 VecTy->getNumElements())), 5523 false /*HasGlobalPred*/); 5524 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 5525 auto LibCost = IntrinsicCost; 5526 if (!CI->isNoBuiltin() && VecFunc) { 5527 // Calculate the cost of the vector library call. 5528 // If the corresponding vector call is cheaper, return its cost. 5529 LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys, 5530 TTI::TCK_RecipThroughput); 5531 } 5532 return {IntrinsicCost, LibCost}; 5533 } 5534 5535 /// Compute the cost of creating a vector of type \p VecTy containing the 5536 /// extracted values from \p VL. 5537 static InstructionCost 5538 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy, 5539 TargetTransformInfo::ShuffleKind ShuffleKind, 5540 ArrayRef<int> Mask, TargetTransformInfo &TTI) { 5541 unsigned NumOfParts = TTI.getNumberOfParts(VecTy); 5542 5543 if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts || 5544 VecTy->getNumElements() < NumOfParts) 5545 return TTI.getShuffleCost(ShuffleKind, VecTy, Mask); 5546 5547 bool AllConsecutive = true; 5548 unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts; 5549 unsigned Idx = -1; 5550 InstructionCost Cost = 0; 5551 5552 // Process extracts in blocks of EltsPerVector to check if the source vector 5553 // operand can be re-used directly. If not, add the cost of creating a shuffle 5554 // to extract the values into a vector register. 5555 SmallVector<int> RegMask(EltsPerVector, UndefMaskElem); 5556 for (auto *V : VL) { 5557 ++Idx; 5558 5559 // Reached the start of a new vector registers. 5560 if (Idx % EltsPerVector == 0) { 5561 RegMask.assign(EltsPerVector, UndefMaskElem); 5562 AllConsecutive = true; 5563 continue; 5564 } 5565 5566 // Need to exclude undefs from analysis. 5567 if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem) 5568 continue; 5569 5570 // Check all extracts for a vector register on the target directly 5571 // extract values in order. 5572 unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V)); 5573 if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) { 5574 unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1])); 5575 AllConsecutive &= PrevIdx + 1 == CurrentIdx && 5576 CurrentIdx % EltsPerVector == Idx % EltsPerVector; 5577 RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector; 5578 } 5579 5580 if (AllConsecutive) 5581 continue; 5582 5583 // Skip all indices, except for the last index per vector block. 5584 if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size()) 5585 continue; 5586 5587 // If we have a series of extracts which are not consecutive and hence 5588 // cannot re-use the source vector register directly, compute the shuffle 5589 // cost to extract the vector with EltsPerVector elements. 5590 Cost += TTI.getShuffleCost( 5591 TargetTransformInfo::SK_PermuteSingleSrc, 5592 FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask); 5593 } 5594 return Cost; 5595 } 5596 5597 /// Build shuffle mask for shuffle graph entries and lists of main and alternate 5598 /// operations operands. 5599 static void 5600 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices, 5601 ArrayRef<int> ReusesIndices, 5602 const function_ref<bool(Instruction *)> IsAltOp, 5603 SmallVectorImpl<int> &Mask, 5604 SmallVectorImpl<Value *> *OpScalars = nullptr, 5605 SmallVectorImpl<Value *> *AltScalars = nullptr) { 5606 unsigned Sz = VL.size(); 5607 Mask.assign(Sz, UndefMaskElem); 5608 SmallVector<int> OrderMask; 5609 if (!ReorderIndices.empty()) 5610 inversePermutation(ReorderIndices, OrderMask); 5611 for (unsigned I = 0; I < Sz; ++I) { 5612 unsigned Idx = I; 5613 if (!ReorderIndices.empty()) 5614 Idx = OrderMask[I]; 5615 auto *OpInst = cast<Instruction>(VL[Idx]); 5616 if (IsAltOp(OpInst)) { 5617 Mask[I] = Sz + Idx; 5618 if (AltScalars) 5619 AltScalars->push_back(OpInst); 5620 } else { 5621 Mask[I] = Idx; 5622 if (OpScalars) 5623 OpScalars->push_back(OpInst); 5624 } 5625 } 5626 if (!ReusesIndices.empty()) { 5627 SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem); 5628 transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) { 5629 return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem; 5630 }); 5631 Mask.swap(NewMask); 5632 } 5633 } 5634 5635 /// Checks if the specified instruction \p I is an alternate operation for the 5636 /// given \p MainOp and \p AltOp instructions. 5637 static bool isAlternateInstruction(const Instruction *I, 5638 const Instruction *MainOp, 5639 const Instruction *AltOp) { 5640 if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) { 5641 auto *AltCI0 = cast<CmpInst>(AltOp); 5642 auto *CI = cast<CmpInst>(I); 5643 CmpInst::Predicate P0 = CI0->getPredicate(); 5644 CmpInst::Predicate AltP0 = AltCI0->getPredicate(); 5645 assert(P0 != AltP0 && "Expected different main/alternate predicates."); 5646 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 5647 CmpInst::Predicate CurrentPred = CI->getPredicate(); 5648 if (P0 == AltP0Swapped) 5649 return I == AltCI0 || 5650 (I != MainOp && 5651 !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1), 5652 CI->getOperand(0), CI->getOperand(1))); 5653 return AltP0 == CurrentPred || AltP0Swapped == CurrentPred; 5654 } 5655 return I->getOpcode() == AltOp->getOpcode(); 5656 } 5657 5658 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E, 5659 ArrayRef<Value *> VectorizedVals) { 5660 ArrayRef<Value*> VL = E->Scalars; 5661 5662 Type *ScalarTy = VL[0]->getType(); 5663 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 5664 ScalarTy = SI->getValueOperand()->getType(); 5665 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0])) 5666 ScalarTy = CI->getOperand(0)->getType(); 5667 else if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 5668 ScalarTy = IE->getOperand(1)->getType(); 5669 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 5670 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 5671 5672 // If we have computed a smaller type for the expression, update VecTy so 5673 // that the costs will be accurate. 5674 if (MinBWs.count(VL[0])) 5675 VecTy = FixedVectorType::get( 5676 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size()); 5677 unsigned EntryVF = E->getVectorFactor(); 5678 auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF); 5679 5680 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 5681 // FIXME: it tries to fix a problem with MSVC buildbots. 5682 TargetTransformInfo &TTIRef = *TTI; 5683 auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy, 5684 VectorizedVals, E](InstructionCost &Cost) { 5685 DenseMap<Value *, int> ExtractVectorsTys; 5686 SmallPtrSet<Value *, 4> CheckedExtracts; 5687 for (auto *V : VL) { 5688 if (isa<UndefValue>(V)) 5689 continue; 5690 // If all users of instruction are going to be vectorized and this 5691 // instruction itself is not going to be vectorized, consider this 5692 // instruction as dead and remove its cost from the final cost of the 5693 // vectorized tree. 5694 // Also, avoid adjusting the cost for extractelements with multiple uses 5695 // in different graph entries. 5696 const TreeEntry *VE = getTreeEntry(V); 5697 if (!CheckedExtracts.insert(V).second || 5698 !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) || 5699 (VE && VE != E)) 5700 continue; 5701 auto *EE = cast<ExtractElementInst>(V); 5702 Optional<unsigned> EEIdx = getExtractIndex(EE); 5703 if (!EEIdx) 5704 continue; 5705 unsigned Idx = *EEIdx; 5706 if (TTIRef.getNumberOfParts(VecTy) != 5707 TTIRef.getNumberOfParts(EE->getVectorOperandType())) { 5708 auto It = 5709 ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first; 5710 It->getSecond() = std::min<int>(It->second, Idx); 5711 } 5712 // Take credit for instruction that will become dead. 5713 if (EE->hasOneUse()) { 5714 Instruction *Ext = EE->user_back(); 5715 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 5716 all_of(Ext->users(), 5717 [](User *U) { return isa<GetElementPtrInst>(U); })) { 5718 // Use getExtractWithExtendCost() to calculate the cost of 5719 // extractelement/ext pair. 5720 Cost -= 5721 TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(), 5722 EE->getVectorOperandType(), Idx); 5723 // Add back the cost of s|zext which is subtracted separately. 5724 Cost += TTIRef.getCastInstrCost( 5725 Ext->getOpcode(), Ext->getType(), EE->getType(), 5726 TTI::getCastContextHint(Ext), CostKind, Ext); 5727 continue; 5728 } 5729 } 5730 Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement, 5731 EE->getVectorOperandType(), Idx); 5732 } 5733 // Add a cost for subvector extracts/inserts if required. 5734 for (const auto &Data : ExtractVectorsTys) { 5735 auto *EEVTy = cast<FixedVectorType>(Data.first->getType()); 5736 unsigned NumElts = VecTy->getNumElements(); 5737 if (Data.second % NumElts == 0) 5738 continue; 5739 if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) { 5740 unsigned Idx = (Data.second / NumElts) * NumElts; 5741 unsigned EENumElts = EEVTy->getNumElements(); 5742 if (Idx + NumElts <= EENumElts) { 5743 Cost += 5744 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 5745 EEVTy, None, Idx, VecTy); 5746 } else { 5747 // Need to round up the subvector type vectorization factor to avoid a 5748 // crash in cost model functions. Make SubVT so that Idx + VF of SubVT 5749 // <= EENumElts. 5750 auto *SubVT = 5751 FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx); 5752 Cost += 5753 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 5754 EEVTy, None, Idx, SubVT); 5755 } 5756 } else { 5757 Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector, 5758 VecTy, None, 0, EEVTy); 5759 } 5760 } 5761 }; 5762 if (E->State == TreeEntry::NeedToGather) { 5763 if (allConstant(VL)) 5764 return 0; 5765 if (isa<InsertElementInst>(VL[0])) 5766 return InstructionCost::getInvalid(); 5767 SmallVector<int> Mask; 5768 SmallVector<const TreeEntry *> Entries; 5769 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 5770 isGatherShuffledEntry(E, Mask, Entries); 5771 if (Shuffle.hasValue()) { 5772 InstructionCost GatherCost = 0; 5773 if (ShuffleVectorInst::isIdentityMask(Mask)) { 5774 // Perfect match in the graph, will reuse the previously vectorized 5775 // node. Cost is 0. 5776 LLVM_DEBUG( 5777 dbgs() 5778 << "SLP: perfect diamond match for gather bundle that starts with " 5779 << *VL.front() << ".\n"); 5780 if (NeedToShuffleReuses) 5781 GatherCost = 5782 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 5783 FinalVecTy, E->ReuseShuffleIndices); 5784 } else { 5785 LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size() 5786 << " entries for bundle that starts with " 5787 << *VL.front() << ".\n"); 5788 // Detected that instead of gather we can emit a shuffle of single/two 5789 // previously vectorized nodes. Add the cost of the permutation rather 5790 // than gather. 5791 ::addMask(Mask, E->ReuseShuffleIndices); 5792 GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask); 5793 } 5794 return GatherCost; 5795 } 5796 if ((E->getOpcode() == Instruction::ExtractElement || 5797 all_of(E->Scalars, 5798 [](Value *V) { 5799 return isa<ExtractElementInst, UndefValue>(V); 5800 })) && 5801 allSameType(VL)) { 5802 // Check that gather of extractelements can be represented as just a 5803 // shuffle of a single/two vectors the scalars are extracted from. 5804 SmallVector<int> Mask; 5805 Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = 5806 isFixedVectorShuffle(VL, Mask); 5807 if (ShuffleKind.hasValue()) { 5808 // Found the bunch of extractelement instructions that must be gathered 5809 // into a vector and can be represented as a permutation elements in a 5810 // single input vector or of 2 input vectors. 5811 InstructionCost Cost = 5812 computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI); 5813 AdjustExtractsCost(Cost); 5814 if (NeedToShuffleReuses) 5815 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 5816 FinalVecTy, E->ReuseShuffleIndices); 5817 return Cost; 5818 } 5819 } 5820 if (isSplat(VL)) { 5821 // Found the broadcasting of the single scalar, calculate the cost as the 5822 // broadcast. 5823 assert(VecTy == FinalVecTy && 5824 "No reused scalars expected for broadcast."); 5825 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 5826 /*Mask=*/None, /*Index=*/0, 5827 /*SubTp=*/nullptr, /*Args=*/VL[0]); 5828 } 5829 InstructionCost ReuseShuffleCost = 0; 5830 if (NeedToShuffleReuses) 5831 ReuseShuffleCost = TTI->getShuffleCost( 5832 TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices); 5833 // Improve gather cost for gather of loads, if we can group some of the 5834 // loads into vector loads. 5835 if (VL.size() > 2 && E->getOpcode() == Instruction::Load && 5836 !E->isAltShuffle()) { 5837 BoUpSLP::ValueSet VectorizedLoads; 5838 unsigned StartIdx = 0; 5839 unsigned VF = VL.size() / 2; 5840 unsigned VectorizedCnt = 0; 5841 unsigned ScatterVectorizeCnt = 0; 5842 const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType()); 5843 for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) { 5844 for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End; 5845 Cnt += VF) { 5846 ArrayRef<Value *> Slice = VL.slice(Cnt, VF); 5847 if (!VectorizedLoads.count(Slice.front()) && 5848 !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) { 5849 SmallVector<Value *> PointerOps; 5850 OrdersType CurrentOrder; 5851 LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL, 5852 *SE, CurrentOrder, PointerOps); 5853 switch (LS) { 5854 case LoadsState::Vectorize: 5855 case LoadsState::ScatterVectorize: 5856 // Mark the vectorized loads so that we don't vectorize them 5857 // again. 5858 if (LS == LoadsState::Vectorize) 5859 ++VectorizedCnt; 5860 else 5861 ++ScatterVectorizeCnt; 5862 VectorizedLoads.insert(Slice.begin(), Slice.end()); 5863 // If we vectorized initial block, no need to try to vectorize it 5864 // again. 5865 if (Cnt == StartIdx) 5866 StartIdx += VF; 5867 break; 5868 case LoadsState::Gather: 5869 break; 5870 } 5871 } 5872 } 5873 // Check if the whole array was vectorized already - exit. 5874 if (StartIdx >= VL.size()) 5875 break; 5876 // Found vectorizable parts - exit. 5877 if (!VectorizedLoads.empty()) 5878 break; 5879 } 5880 if (!VectorizedLoads.empty()) { 5881 InstructionCost GatherCost = 0; 5882 unsigned NumParts = TTI->getNumberOfParts(VecTy); 5883 bool NeedInsertSubvectorAnalysis = 5884 !NumParts || (VL.size() / VF) > NumParts; 5885 // Get the cost for gathered loads. 5886 for (unsigned I = 0, End = VL.size(); I < End; I += VF) { 5887 if (VectorizedLoads.contains(VL[I])) 5888 continue; 5889 GatherCost += getGatherCost(VL.slice(I, VF)); 5890 } 5891 // The cost for vectorized loads. 5892 InstructionCost ScalarsCost = 0; 5893 for (Value *V : VectorizedLoads) { 5894 auto *LI = cast<LoadInst>(V); 5895 ScalarsCost += TTI->getMemoryOpCost( 5896 Instruction::Load, LI->getType(), LI->getAlign(), 5897 LI->getPointerAddressSpace(), CostKind, LI); 5898 } 5899 auto *LI = cast<LoadInst>(E->getMainOp()); 5900 auto *LoadTy = FixedVectorType::get(LI->getType(), VF); 5901 Align Alignment = LI->getAlign(); 5902 GatherCost += 5903 VectorizedCnt * 5904 TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment, 5905 LI->getPointerAddressSpace(), CostKind, LI); 5906 GatherCost += ScatterVectorizeCnt * 5907 TTI->getGatherScatterOpCost( 5908 Instruction::Load, LoadTy, LI->getPointerOperand(), 5909 /*VariableMask=*/false, Alignment, CostKind, LI); 5910 if (NeedInsertSubvectorAnalysis) { 5911 // Add the cost for the subvectors insert. 5912 for (int I = VF, E = VL.size(); I < E; I += VF) 5913 GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy, 5914 None, I, LoadTy); 5915 } 5916 return ReuseShuffleCost + GatherCost - ScalarsCost; 5917 } 5918 } 5919 return ReuseShuffleCost + getGatherCost(VL); 5920 } 5921 InstructionCost CommonCost = 0; 5922 SmallVector<int> Mask; 5923 if (!E->ReorderIndices.empty()) { 5924 SmallVector<int> NewMask; 5925 if (E->getOpcode() == Instruction::Store) { 5926 // For stores the order is actually a mask. 5927 NewMask.resize(E->ReorderIndices.size()); 5928 copy(E->ReorderIndices, NewMask.begin()); 5929 } else { 5930 inversePermutation(E->ReorderIndices, NewMask); 5931 } 5932 ::addMask(Mask, NewMask); 5933 } 5934 if (NeedToShuffleReuses) 5935 ::addMask(Mask, E->ReuseShuffleIndices); 5936 if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask)) 5937 CommonCost = 5938 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask); 5939 assert((E->State == TreeEntry::Vectorize || 5940 E->State == TreeEntry::ScatterVectorize) && 5941 "Unhandled state"); 5942 assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL"); 5943 Instruction *VL0 = E->getMainOp(); 5944 unsigned ShuffleOrOp = 5945 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 5946 switch (ShuffleOrOp) { 5947 case Instruction::PHI: 5948 return 0; 5949 5950 case Instruction::ExtractValue: 5951 case Instruction::ExtractElement: { 5952 // The common cost of removal ExtractElement/ExtractValue instructions + 5953 // the cost of shuffles, if required to resuffle the original vector. 5954 if (NeedToShuffleReuses) { 5955 unsigned Idx = 0; 5956 for (unsigned I : E->ReuseShuffleIndices) { 5957 if (ShuffleOrOp == Instruction::ExtractElement) { 5958 auto *EE = cast<ExtractElementInst>(VL[I]); 5959 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 5960 EE->getVectorOperandType(), 5961 *getExtractIndex(EE)); 5962 } else { 5963 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 5964 VecTy, Idx); 5965 ++Idx; 5966 } 5967 } 5968 Idx = EntryVF; 5969 for (Value *V : VL) { 5970 if (ShuffleOrOp == Instruction::ExtractElement) { 5971 auto *EE = cast<ExtractElementInst>(V); 5972 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 5973 EE->getVectorOperandType(), 5974 *getExtractIndex(EE)); 5975 } else { 5976 --Idx; 5977 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 5978 VecTy, Idx); 5979 } 5980 } 5981 } 5982 if (ShuffleOrOp == Instruction::ExtractValue) { 5983 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 5984 auto *EI = cast<Instruction>(VL[I]); 5985 // Take credit for instruction that will become dead. 5986 if (EI->hasOneUse()) { 5987 Instruction *Ext = EI->user_back(); 5988 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 5989 all_of(Ext->users(), 5990 [](User *U) { return isa<GetElementPtrInst>(U); })) { 5991 // Use getExtractWithExtendCost() to calculate the cost of 5992 // extractelement/ext pair. 5993 CommonCost -= TTI->getExtractWithExtendCost( 5994 Ext->getOpcode(), Ext->getType(), VecTy, I); 5995 // Add back the cost of s|zext which is subtracted separately. 5996 CommonCost += TTI->getCastInstrCost( 5997 Ext->getOpcode(), Ext->getType(), EI->getType(), 5998 TTI::getCastContextHint(Ext), CostKind, Ext); 5999 continue; 6000 } 6001 } 6002 CommonCost -= 6003 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I); 6004 } 6005 } else { 6006 AdjustExtractsCost(CommonCost); 6007 } 6008 return CommonCost; 6009 } 6010 case Instruction::InsertElement: { 6011 assert(E->ReuseShuffleIndices.empty() && 6012 "Unique insertelements only are expected."); 6013 auto *SrcVecTy = cast<FixedVectorType>(VL0->getType()); 6014 unsigned const NumElts = SrcVecTy->getNumElements(); 6015 unsigned const NumScalars = VL.size(); 6016 6017 unsigned NumOfParts = TTI->getNumberOfParts(SrcVecTy); 6018 6019 unsigned OffsetBeg = *getInsertIndex(VL.front()); 6020 unsigned OffsetEnd = OffsetBeg; 6021 for (Value *V : VL.drop_front()) { 6022 unsigned Idx = *getInsertIndex(V); 6023 if (OffsetBeg > Idx) 6024 OffsetBeg = Idx; 6025 else if (OffsetEnd < Idx) 6026 OffsetEnd = Idx; 6027 } 6028 unsigned VecScalarsSz = PowerOf2Ceil(NumElts); 6029 if (NumOfParts > 0) 6030 VecScalarsSz = PowerOf2Ceil((NumElts + NumOfParts - 1) / NumOfParts); 6031 unsigned VecSz = 6032 (1 + OffsetEnd / VecScalarsSz - OffsetBeg / VecScalarsSz) * 6033 VecScalarsSz; 6034 unsigned Offset = VecScalarsSz * (OffsetBeg / VecScalarsSz); 6035 unsigned InsertVecSz = std::min<unsigned>( 6036 PowerOf2Ceil(OffsetEnd - OffsetBeg + 1), 6037 ((OffsetEnd - OffsetBeg + VecScalarsSz) / VecScalarsSz) * 6038 VecScalarsSz); 6039 6040 APInt DemandedElts = APInt::getZero(NumElts); 6041 // TODO: Add support for Instruction::InsertValue. 6042 SmallVector<int> Mask; 6043 if (!E->ReorderIndices.empty()) { 6044 inversePermutation(E->ReorderIndices, Mask); 6045 Mask.append(InsertVecSz - Mask.size(), UndefMaskElem); 6046 } else { 6047 Mask.assign(VecSz, UndefMaskElem); 6048 std::iota(Mask.begin(), std::next(Mask.begin(), InsertVecSz), 0); 6049 } 6050 bool IsIdentity = true; 6051 SmallVector<int> PrevMask(InsertVecSz, UndefMaskElem); 6052 Mask.swap(PrevMask); 6053 for (unsigned I = 0; I < NumScalars; ++I) { 6054 unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]); 6055 DemandedElts.setBit(InsertIdx); 6056 IsIdentity &= InsertIdx - OffsetBeg == I; 6057 Mask[InsertIdx - OffsetBeg] = I; 6058 } 6059 assert(Offset < NumElts && "Failed to find vector index offset"); 6060 6061 InstructionCost Cost = 0; 6062 Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts, 6063 /*Insert*/ true, /*Extract*/ false); 6064 6065 // First cost - resize to actual vector size if not identity shuffle or 6066 // need to shift the vector. 6067 // Do not calculate the cost if the actual size is the register size and 6068 // we can merge this shuffle with the following SK_Select. 6069 auto *InsertVecTy = 6070 FixedVectorType::get(SrcVecTy->getElementType(), InsertVecSz); 6071 if (!IsIdentity) 6072 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 6073 InsertVecTy, Mask); 6074 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 6075 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); 6076 })); 6077 // Second cost - permutation with subvector, if some elements are from the 6078 // initial vector or inserting a subvector. 6079 // TODO: Implement the analysis of the FirstInsert->getOperand(0) 6080 // subvector of ActualVecTy. 6081 if (!isUndefVector(FirstInsert->getOperand(0)) && NumScalars != NumElts && 6082 (Offset != OffsetBeg || (OffsetEnd + 1) % VecScalarsSz != 0)) { 6083 if (InsertVecSz != VecSz) { 6084 auto *ActualVecTy = 6085 FixedVectorType::get(SrcVecTy->getElementType(), VecSz); 6086 Cost += TTI->getShuffleCost(TTI::SK_InsertSubvector, ActualVecTy, 6087 None, OffsetBeg - Offset, InsertVecTy); 6088 } else { 6089 for (unsigned I = 0, End = OffsetBeg - Offset; I < End; ++I) 6090 Mask[I] = I; 6091 for (unsigned I = OffsetBeg - Offset, End = OffsetEnd - Offset; 6092 I <= End; ++I) 6093 if (Mask[I] != UndefMaskElem) 6094 Mask[I] = I + VecSz; 6095 for (unsigned I = OffsetEnd + 1 - Offset; I < VecSz; ++I) 6096 Mask[I] = I; 6097 Cost += TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, InsertVecTy, Mask); 6098 } 6099 } 6100 return Cost; 6101 } 6102 case Instruction::ZExt: 6103 case Instruction::SExt: 6104 case Instruction::FPToUI: 6105 case Instruction::FPToSI: 6106 case Instruction::FPExt: 6107 case Instruction::PtrToInt: 6108 case Instruction::IntToPtr: 6109 case Instruction::SIToFP: 6110 case Instruction::UIToFP: 6111 case Instruction::Trunc: 6112 case Instruction::FPTrunc: 6113 case Instruction::BitCast: { 6114 Type *SrcTy = VL0->getOperand(0)->getType(); 6115 InstructionCost ScalarEltCost = 6116 TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy, 6117 TTI::getCastContextHint(VL0), CostKind, VL0); 6118 if (NeedToShuffleReuses) { 6119 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6120 } 6121 6122 // Calculate the cost of this instruction. 6123 InstructionCost ScalarCost = VL.size() * ScalarEltCost; 6124 6125 auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size()); 6126 InstructionCost VecCost = 0; 6127 // Check if the values are candidates to demote. 6128 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) { 6129 VecCost = CommonCost + TTI->getCastInstrCost( 6130 E->getOpcode(), VecTy, SrcVecTy, 6131 TTI::getCastContextHint(VL0), CostKind, VL0); 6132 } 6133 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6134 return VecCost - ScalarCost; 6135 } 6136 case Instruction::FCmp: 6137 case Instruction::ICmp: 6138 case Instruction::Select: { 6139 // Calculate the cost of this instruction. 6140 InstructionCost ScalarEltCost = 6141 TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 6142 CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0); 6143 if (NeedToShuffleReuses) { 6144 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6145 } 6146 auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size()); 6147 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 6148 6149 // Check if all entries in VL are either compares or selects with compares 6150 // as condition that have the same predicates. 6151 CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE; 6152 bool First = true; 6153 for (auto *V : VL) { 6154 CmpInst::Predicate CurrentPred; 6155 auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value()); 6156 if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) && 6157 !match(V, MatchCmp)) || 6158 (!First && VecPred != CurrentPred)) { 6159 VecPred = CmpInst::BAD_ICMP_PREDICATE; 6160 break; 6161 } 6162 First = false; 6163 VecPred = CurrentPred; 6164 } 6165 6166 InstructionCost VecCost = TTI->getCmpSelInstrCost( 6167 E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0); 6168 // Check if it is possible and profitable to use min/max for selects in 6169 // VL. 6170 // 6171 auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL); 6172 if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) { 6173 IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy, 6174 {VecTy, VecTy}); 6175 InstructionCost IntrinsicCost = 6176 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 6177 // If the selects are the only uses of the compares, they will be dead 6178 // and we can adjust the cost by removing their cost. 6179 if (IntrinsicAndUse.second) 6180 IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, 6181 MaskTy, VecPred, CostKind); 6182 VecCost = std::min(VecCost, IntrinsicCost); 6183 } 6184 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6185 return CommonCost + VecCost - ScalarCost; 6186 } 6187 case Instruction::FNeg: 6188 case Instruction::Add: 6189 case Instruction::FAdd: 6190 case Instruction::Sub: 6191 case Instruction::FSub: 6192 case Instruction::Mul: 6193 case Instruction::FMul: 6194 case Instruction::UDiv: 6195 case Instruction::SDiv: 6196 case Instruction::FDiv: 6197 case Instruction::URem: 6198 case Instruction::SRem: 6199 case Instruction::FRem: 6200 case Instruction::Shl: 6201 case Instruction::LShr: 6202 case Instruction::AShr: 6203 case Instruction::And: 6204 case Instruction::Or: 6205 case Instruction::Xor: { 6206 // Certain instructions can be cheaper to vectorize if they have a 6207 // constant second vector operand. 6208 TargetTransformInfo::OperandValueKind Op1VK = 6209 TargetTransformInfo::OK_AnyValue; 6210 TargetTransformInfo::OperandValueKind Op2VK = 6211 TargetTransformInfo::OK_UniformConstantValue; 6212 TargetTransformInfo::OperandValueProperties Op1VP = 6213 TargetTransformInfo::OP_None; 6214 TargetTransformInfo::OperandValueProperties Op2VP = 6215 TargetTransformInfo::OP_PowerOf2; 6216 6217 // If all operands are exactly the same ConstantInt then set the 6218 // operand kind to OK_UniformConstantValue. 6219 // If instead not all operands are constants, then set the operand kind 6220 // to OK_AnyValue. If all operands are constants but not the same, 6221 // then set the operand kind to OK_NonUniformConstantValue. 6222 ConstantInt *CInt0 = nullptr; 6223 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 6224 const Instruction *I = cast<Instruction>(VL[i]); 6225 unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0; 6226 ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx)); 6227 if (!CInt) { 6228 Op2VK = TargetTransformInfo::OK_AnyValue; 6229 Op2VP = TargetTransformInfo::OP_None; 6230 break; 6231 } 6232 if (Op2VP == TargetTransformInfo::OP_PowerOf2 && 6233 !CInt->getValue().isPowerOf2()) 6234 Op2VP = TargetTransformInfo::OP_None; 6235 if (i == 0) { 6236 CInt0 = CInt; 6237 continue; 6238 } 6239 if (CInt0 != CInt) 6240 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 6241 } 6242 6243 SmallVector<const Value *, 4> Operands(VL0->operand_values()); 6244 InstructionCost ScalarEltCost = 6245 TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK, 6246 Op2VK, Op1VP, Op2VP, Operands, VL0); 6247 if (NeedToShuffleReuses) { 6248 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6249 } 6250 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 6251 InstructionCost VecCost = 6252 TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK, 6253 Op2VK, Op1VP, Op2VP, Operands, VL0); 6254 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6255 return CommonCost + VecCost - ScalarCost; 6256 } 6257 case Instruction::GetElementPtr: { 6258 TargetTransformInfo::OperandValueKind Op1VK = 6259 TargetTransformInfo::OK_AnyValue; 6260 TargetTransformInfo::OperandValueKind Op2VK = 6261 TargetTransformInfo::OK_UniformConstantValue; 6262 6263 InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost( 6264 Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK); 6265 if (NeedToShuffleReuses) { 6266 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6267 } 6268 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 6269 InstructionCost VecCost = TTI->getArithmeticInstrCost( 6270 Instruction::Add, VecTy, CostKind, Op1VK, Op2VK); 6271 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6272 return CommonCost + VecCost - ScalarCost; 6273 } 6274 case Instruction::Load: { 6275 // Cost of wide load - cost of scalar loads. 6276 Align Alignment = cast<LoadInst>(VL0)->getAlign(); 6277 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 6278 Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0); 6279 if (NeedToShuffleReuses) { 6280 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6281 } 6282 InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost; 6283 InstructionCost VecLdCost; 6284 if (E->State == TreeEntry::Vectorize) { 6285 VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0, 6286 CostKind, VL0); 6287 } else { 6288 assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState"); 6289 Align CommonAlignment = Alignment; 6290 for (Value *V : VL) 6291 CommonAlignment = 6292 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 6293 VecLdCost = TTI->getGatherScatterOpCost( 6294 Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(), 6295 /*VariableMask=*/false, CommonAlignment, CostKind, VL0); 6296 } 6297 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost)); 6298 return CommonCost + VecLdCost - ScalarLdCost; 6299 } 6300 case Instruction::Store: { 6301 // We know that we can merge the stores. Calculate the cost. 6302 bool IsReorder = !E->ReorderIndices.empty(); 6303 auto *SI = 6304 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0); 6305 Align Alignment = SI->getAlign(); 6306 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 6307 Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0); 6308 InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost; 6309 InstructionCost VecStCost = TTI->getMemoryOpCost( 6310 Instruction::Store, VecTy, Alignment, 0, CostKind, VL0); 6311 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost)); 6312 return CommonCost + VecStCost - ScalarStCost; 6313 } 6314 case Instruction::Call: { 6315 CallInst *CI = cast<CallInst>(VL0); 6316 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 6317 6318 // Calculate the cost of the scalar and vector calls. 6319 IntrinsicCostAttributes CostAttrs(ID, *CI, 1); 6320 InstructionCost ScalarEltCost = 6321 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 6322 if (NeedToShuffleReuses) { 6323 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6324 } 6325 InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost; 6326 6327 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 6328 InstructionCost VecCallCost = 6329 std::min(VecCallCosts.first, VecCallCosts.second); 6330 6331 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost 6332 << " (" << VecCallCost << "-" << ScalarCallCost << ")" 6333 << " for " << *CI << "\n"); 6334 6335 return CommonCost + VecCallCost - ScalarCallCost; 6336 } 6337 case Instruction::ShuffleVector: { 6338 assert(E->isAltShuffle() && 6339 ((Instruction::isBinaryOp(E->getOpcode()) && 6340 Instruction::isBinaryOp(E->getAltOpcode())) || 6341 (Instruction::isCast(E->getOpcode()) && 6342 Instruction::isCast(E->getAltOpcode())) || 6343 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 6344 "Invalid Shuffle Vector Operand"); 6345 InstructionCost ScalarCost = 0; 6346 if (NeedToShuffleReuses) { 6347 for (unsigned Idx : E->ReuseShuffleIndices) { 6348 Instruction *I = cast<Instruction>(VL[Idx]); 6349 CommonCost -= TTI->getInstructionCost(I, CostKind); 6350 } 6351 for (Value *V : VL) { 6352 Instruction *I = cast<Instruction>(V); 6353 CommonCost += TTI->getInstructionCost(I, CostKind); 6354 } 6355 } 6356 for (Value *V : VL) { 6357 Instruction *I = cast<Instruction>(V); 6358 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 6359 ScalarCost += TTI->getInstructionCost(I, CostKind); 6360 } 6361 // VecCost is equal to sum of the cost of creating 2 vectors 6362 // and the cost of creating shuffle. 6363 InstructionCost VecCost = 0; 6364 // Try to find the previous shuffle node with the same operands and same 6365 // main/alternate ops. 6366 auto &&TryFindNodeWithEqualOperands = [this, E]() { 6367 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 6368 if (TE.get() == E) 6369 break; 6370 if (TE->isAltShuffle() && 6371 ((TE->getOpcode() == E->getOpcode() && 6372 TE->getAltOpcode() == E->getAltOpcode()) || 6373 (TE->getOpcode() == E->getAltOpcode() && 6374 TE->getAltOpcode() == E->getOpcode())) && 6375 TE->hasEqualOperands(*E)) 6376 return true; 6377 } 6378 return false; 6379 }; 6380 if (TryFindNodeWithEqualOperands()) { 6381 LLVM_DEBUG({ 6382 dbgs() << "SLP: diamond match for alternate node found.\n"; 6383 E->dump(); 6384 }); 6385 // No need to add new vector costs here since we're going to reuse 6386 // same main/alternate vector ops, just do different shuffling. 6387 } else if (Instruction::isBinaryOp(E->getOpcode())) { 6388 VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind); 6389 VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy, 6390 CostKind); 6391 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 6392 VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, 6393 Builder.getInt1Ty(), 6394 CI0->getPredicate(), CostKind, VL0); 6395 VecCost += TTI->getCmpSelInstrCost( 6396 E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 6397 cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind, 6398 E->getAltOp()); 6399 } else { 6400 Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType(); 6401 Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType(); 6402 auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size()); 6403 auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size()); 6404 VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty, 6405 TTI::CastContextHint::None, CostKind); 6406 VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty, 6407 TTI::CastContextHint::None, CostKind); 6408 } 6409 6410 if (E->ReuseShuffleIndices.empty()) { 6411 CommonCost = 6412 TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy); 6413 } else { 6414 SmallVector<int> Mask; 6415 buildShuffleEntryMask( 6416 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 6417 [E](Instruction *I) { 6418 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 6419 return I->getOpcode() == E->getAltOpcode(); 6420 }, 6421 Mask); 6422 CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, 6423 FinalVecTy, Mask); 6424 } 6425 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6426 return CommonCost + VecCost - ScalarCost; 6427 } 6428 default: 6429 llvm_unreachable("Unknown instruction"); 6430 } 6431 } 6432 6433 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const { 6434 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height " 6435 << VectorizableTree.size() << " is fully vectorizable .\n"); 6436 6437 auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) { 6438 SmallVector<int> Mask; 6439 return TE->State == TreeEntry::NeedToGather && 6440 !any_of(TE->Scalars, 6441 [this](Value *V) { return EphValues.contains(V); }) && 6442 (allConstant(TE->Scalars) || isSplat(TE->Scalars) || 6443 TE->Scalars.size() < Limit || 6444 ((TE->getOpcode() == Instruction::ExtractElement || 6445 all_of(TE->Scalars, 6446 [](Value *V) { 6447 return isa<ExtractElementInst, UndefValue>(V); 6448 })) && 6449 isFixedVectorShuffle(TE->Scalars, Mask)) || 6450 (TE->State == TreeEntry::NeedToGather && 6451 TE->getOpcode() == Instruction::Load && !TE->isAltShuffle())); 6452 }; 6453 6454 // We only handle trees of heights 1 and 2. 6455 if (VectorizableTree.size() == 1 && 6456 (VectorizableTree[0]->State == TreeEntry::Vectorize || 6457 (ForReduction && 6458 AreVectorizableGathers(VectorizableTree[0].get(), 6459 VectorizableTree[0]->Scalars.size()) && 6460 VectorizableTree[0]->getVectorFactor() > 2))) 6461 return true; 6462 6463 if (VectorizableTree.size() != 2) 6464 return false; 6465 6466 // Handle splat and all-constants stores. Also try to vectorize tiny trees 6467 // with the second gather nodes if they have less scalar operands rather than 6468 // the initial tree element (may be profitable to shuffle the second gather) 6469 // or they are extractelements, which form shuffle. 6470 SmallVector<int> Mask; 6471 if (VectorizableTree[0]->State == TreeEntry::Vectorize && 6472 AreVectorizableGathers(VectorizableTree[1].get(), 6473 VectorizableTree[0]->Scalars.size())) 6474 return true; 6475 6476 // Gathering cost would be too much for tiny trees. 6477 if (VectorizableTree[0]->State == TreeEntry::NeedToGather || 6478 (VectorizableTree[1]->State == TreeEntry::NeedToGather && 6479 VectorizableTree[0]->State != TreeEntry::ScatterVectorize)) 6480 return false; 6481 6482 return true; 6483 } 6484 6485 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts, 6486 TargetTransformInfo *TTI, 6487 bool MustMatchOrInst) { 6488 // Look past the root to find a source value. Arbitrarily follow the 6489 // path through operand 0 of any 'or'. Also, peek through optional 6490 // shift-left-by-multiple-of-8-bits. 6491 Value *ZextLoad = Root; 6492 const APInt *ShAmtC; 6493 bool FoundOr = false; 6494 while (!isa<ConstantExpr>(ZextLoad) && 6495 (match(ZextLoad, m_Or(m_Value(), m_Value())) || 6496 (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) && 6497 ShAmtC->urem(8) == 0))) { 6498 auto *BinOp = cast<BinaryOperator>(ZextLoad); 6499 ZextLoad = BinOp->getOperand(0); 6500 if (BinOp->getOpcode() == Instruction::Or) 6501 FoundOr = true; 6502 } 6503 // Check if the input is an extended load of the required or/shift expression. 6504 Value *Load; 6505 if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root || 6506 !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load)) 6507 return false; 6508 6509 // Require that the total load bit width is a legal integer type. 6510 // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target. 6511 // But <16 x i8> --> i128 is not, so the backend probably can't reduce it. 6512 Type *SrcTy = Load->getType(); 6513 unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts; 6514 if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth))) 6515 return false; 6516 6517 // Everything matched - assume that we can fold the whole sequence using 6518 // load combining. 6519 LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at " 6520 << *(cast<Instruction>(Root)) << "\n"); 6521 6522 return true; 6523 } 6524 6525 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const { 6526 if (RdxKind != RecurKind::Or) 6527 return false; 6528 6529 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 6530 Value *FirstReduced = VectorizableTree[0]->Scalars[0]; 6531 return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI, 6532 /* MatchOr */ false); 6533 } 6534 6535 bool BoUpSLP::isLoadCombineCandidate() const { 6536 // Peek through a final sequence of stores and check if all operations are 6537 // likely to be load-combined. 6538 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 6539 for (Value *Scalar : VectorizableTree[0]->Scalars) { 6540 Value *X; 6541 if (!match(Scalar, m_Store(m_Value(X), m_Value())) || 6542 !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true)) 6543 return false; 6544 } 6545 return true; 6546 } 6547 6548 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const { 6549 // No need to vectorize inserts of gathered values. 6550 if (VectorizableTree.size() == 2 && 6551 isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) && 6552 VectorizableTree[1]->State == TreeEntry::NeedToGather && 6553 (VectorizableTree[1]->getVectorFactor() <= 2 || 6554 !(isSplat(VectorizableTree[1]->Scalars) || 6555 allConstant(VectorizableTree[1]->Scalars)))) 6556 return true; 6557 6558 // We can vectorize the tree if its size is greater than or equal to the 6559 // minimum size specified by the MinTreeSize command line option. 6560 if (VectorizableTree.size() >= MinTreeSize) 6561 return false; 6562 6563 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we 6564 // can vectorize it if we can prove it fully vectorizable. 6565 if (isFullyVectorizableTinyTree(ForReduction)) 6566 return false; 6567 6568 assert(VectorizableTree.empty() 6569 ? ExternalUses.empty() 6570 : true && "We shouldn't have any external users"); 6571 6572 // Otherwise, we can't vectorize the tree. It is both tiny and not fully 6573 // vectorizable. 6574 return true; 6575 } 6576 6577 InstructionCost BoUpSLP::getSpillCost() const { 6578 // Walk from the bottom of the tree to the top, tracking which values are 6579 // live. When we see a call instruction that is not part of our tree, 6580 // query TTI to see if there is a cost to keeping values live over it 6581 // (for example, if spills and fills are required). 6582 unsigned BundleWidth = VectorizableTree.front()->Scalars.size(); 6583 InstructionCost Cost = 0; 6584 6585 SmallPtrSet<Instruction*, 4> LiveValues; 6586 Instruction *PrevInst = nullptr; 6587 6588 // The entries in VectorizableTree are not necessarily ordered by their 6589 // position in basic blocks. Collect them and order them by dominance so later 6590 // instructions are guaranteed to be visited first. For instructions in 6591 // different basic blocks, we only scan to the beginning of the block, so 6592 // their order does not matter, as long as all instructions in a basic block 6593 // are grouped together. Using dominance ensures a deterministic order. 6594 SmallVector<Instruction *, 16> OrderedScalars; 6595 for (const auto &TEPtr : VectorizableTree) { 6596 Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]); 6597 if (!Inst) 6598 continue; 6599 OrderedScalars.push_back(Inst); 6600 } 6601 llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) { 6602 auto *NodeA = DT->getNode(A->getParent()); 6603 auto *NodeB = DT->getNode(B->getParent()); 6604 assert(NodeA && "Should only process reachable instructions"); 6605 assert(NodeB && "Should only process reachable instructions"); 6606 assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && 6607 "Different nodes should have different DFS numbers"); 6608 if (NodeA != NodeB) 6609 return NodeA->getDFSNumIn() < NodeB->getDFSNumIn(); 6610 return B->comesBefore(A); 6611 }); 6612 6613 for (Instruction *Inst : OrderedScalars) { 6614 if (!PrevInst) { 6615 PrevInst = Inst; 6616 continue; 6617 } 6618 6619 // Update LiveValues. 6620 LiveValues.erase(PrevInst); 6621 for (auto &J : PrevInst->operands()) { 6622 if (isa<Instruction>(&*J) && getTreeEntry(&*J)) 6623 LiveValues.insert(cast<Instruction>(&*J)); 6624 } 6625 6626 LLVM_DEBUG({ 6627 dbgs() << "SLP: #LV: " << LiveValues.size(); 6628 for (auto *X : LiveValues) 6629 dbgs() << " " << X->getName(); 6630 dbgs() << ", Looking at "; 6631 Inst->dump(); 6632 }); 6633 6634 // Now find the sequence of instructions between PrevInst and Inst. 6635 unsigned NumCalls = 0; 6636 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(), 6637 PrevInstIt = 6638 PrevInst->getIterator().getReverse(); 6639 while (InstIt != PrevInstIt) { 6640 if (PrevInstIt == PrevInst->getParent()->rend()) { 6641 PrevInstIt = Inst->getParent()->rbegin(); 6642 continue; 6643 } 6644 6645 // Debug information does not impact spill cost. 6646 if ((isa<CallInst>(&*PrevInstIt) && 6647 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) && 6648 &*PrevInstIt != PrevInst) 6649 NumCalls++; 6650 6651 ++PrevInstIt; 6652 } 6653 6654 if (NumCalls) { 6655 SmallVector<Type*, 4> V; 6656 for (auto *II : LiveValues) { 6657 auto *ScalarTy = II->getType(); 6658 if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy)) 6659 ScalarTy = VectorTy->getElementType(); 6660 V.push_back(FixedVectorType::get(ScalarTy, BundleWidth)); 6661 } 6662 Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V); 6663 } 6664 6665 PrevInst = Inst; 6666 } 6667 6668 return Cost; 6669 } 6670 6671 /// Check if two insertelement instructions are from the same buildvector. 6672 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU, 6673 InsertElementInst *V) { 6674 // Instructions must be from the same basic blocks. 6675 if (VU->getParent() != V->getParent()) 6676 return false; 6677 // Checks if 2 insertelements are from the same buildvector. 6678 if (VU->getType() != V->getType()) 6679 return false; 6680 // Multiple used inserts are separate nodes. 6681 if (!VU->hasOneUse() && !V->hasOneUse()) 6682 return false; 6683 auto *IE1 = VU; 6684 auto *IE2 = V; 6685 unsigned Idx1 = *getInsertIndex(IE1); 6686 unsigned Idx2 = *getInsertIndex(IE2); 6687 // Go through the vector operand of insertelement instructions trying to find 6688 // either VU as the original vector for IE2 or V as the original vector for 6689 // IE1. 6690 do { 6691 if (IE2 == VU) 6692 return VU->hasOneUse(); 6693 if (IE1 == V) 6694 return V->hasOneUse(); 6695 if (IE1) { 6696 if ((IE1 != VU && !IE1->hasOneUse()) || 6697 getInsertIndex(IE1).getValueOr(Idx2) == Idx2) 6698 IE1 = nullptr; 6699 else 6700 IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0)); 6701 } 6702 if (IE2) { 6703 if ((IE2 != V && !IE2->hasOneUse()) || 6704 getInsertIndex(IE2).getValueOr(Idx1) == Idx1) 6705 IE2 = nullptr; 6706 else 6707 IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0)); 6708 } 6709 } while (IE1 || IE2); 6710 return false; 6711 } 6712 6713 /// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the 6714 /// buildvector sequence. 6715 static bool isFirstInsertElement(const InsertElementInst *IE1, 6716 const InsertElementInst *IE2) { 6717 if (IE1 == IE2) 6718 return false; 6719 const auto *I1 = IE1; 6720 const auto *I2 = IE2; 6721 const InsertElementInst *PrevI1; 6722 const InsertElementInst *PrevI2; 6723 unsigned Idx1 = *getInsertIndex(IE1); 6724 unsigned Idx2 = *getInsertIndex(IE2); 6725 do { 6726 if (I2 == IE1) 6727 return true; 6728 if (I1 == IE2) 6729 return false; 6730 PrevI1 = I1; 6731 PrevI2 = I2; 6732 if (I1 && (I1 == IE1 || I1->hasOneUse()) && 6733 getInsertIndex(I1).getValueOr(Idx2) != Idx2) 6734 I1 = dyn_cast<InsertElementInst>(I1->getOperand(0)); 6735 if (I2 && ((I2 == IE2 || I2->hasOneUse())) && 6736 getInsertIndex(I2).getValueOr(Idx1) != Idx1) 6737 I2 = dyn_cast<InsertElementInst>(I2->getOperand(0)); 6738 } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2)); 6739 llvm_unreachable("Two different buildvectors not expected."); 6740 } 6741 6742 namespace { 6743 /// Returns incoming Value *, if the requested type is Value * too, or a default 6744 /// value, otherwise. 6745 struct ValueSelect { 6746 template <typename U> 6747 static typename std::enable_if<std::is_same<Value *, U>::value, Value *>::type 6748 get(Value *V) { 6749 return V; 6750 } 6751 template <typename U> 6752 static typename std::enable_if<!std::is_same<Value *, U>::value, U>::type 6753 get(Value *) { 6754 return U(); 6755 } 6756 }; 6757 } // namespace 6758 6759 /// Does the analysis of the provided shuffle masks and performs the requested 6760 /// actions on the vectors with the given shuffle masks. It tries to do it in 6761 /// several steps. 6762 /// 1. If the Base vector is not undef vector, resizing the very first mask to 6763 /// have common VF and perform action for 2 input vectors (including non-undef 6764 /// Base). Other shuffle masks are combined with the resulting after the 1 stage 6765 /// and processed as a shuffle of 2 elements. 6766 /// 2. If the Base is undef vector and have only 1 shuffle mask, perform the 6767 /// action only for 1 vector with the given mask, if it is not the identity 6768 /// mask. 6769 /// 3. If > 2 masks are used, perform the remaining shuffle actions for 2 6770 /// vectors, combing the masks properly between the steps. 6771 template <typename T> 6772 static T *performExtractsShuffleAction( 6773 MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base, 6774 function_ref<unsigned(T *)> GetVF, 6775 function_ref<std::pair<T *, bool>(T *, ArrayRef<int>)> ResizeAction, 6776 function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) { 6777 assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts."); 6778 SmallVector<int> Mask(ShuffleMask.begin()->second); 6779 auto VMIt = std::next(ShuffleMask.begin()); 6780 T *Prev = nullptr; 6781 bool IsBaseNotUndef = !isUndefVector(Base); 6782 if (IsBaseNotUndef) { 6783 // Base is not undef, need to combine it with the next subvectors. 6784 std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask); 6785 for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) { 6786 if (Mask[Idx] == UndefMaskElem) 6787 Mask[Idx] = Idx; 6788 else 6789 Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF; 6790 } 6791 auto *V = ValueSelect::get<T *>(Base); 6792 (void)V; 6793 assert((!V || GetVF(V) == Mask.size()) && 6794 "Expected base vector of VF number of elements."); 6795 Prev = Action(Mask, {nullptr, Res.first}); 6796 } else if (ShuffleMask.size() == 1) { 6797 // Base is undef and only 1 vector is shuffled - perform the action only for 6798 // single vector, if the mask is not the identity mask. 6799 std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask); 6800 if (Res.second) 6801 // Identity mask is found. 6802 Prev = Res.first; 6803 else 6804 Prev = Action(Mask, {ShuffleMask.begin()->first}); 6805 } else { 6806 // Base is undef and at least 2 input vectors shuffled - perform 2 vectors 6807 // shuffles step by step, combining shuffle between the steps. 6808 unsigned Vec1VF = GetVF(ShuffleMask.begin()->first); 6809 unsigned Vec2VF = GetVF(VMIt->first); 6810 if (Vec1VF == Vec2VF) { 6811 // No need to resize the input vectors since they are of the same size, we 6812 // can shuffle them directly. 6813 ArrayRef<int> SecMask = VMIt->second; 6814 for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) { 6815 if (SecMask[I] != UndefMaskElem) { 6816 assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars."); 6817 Mask[I] = SecMask[I] + Vec1VF; 6818 } 6819 } 6820 Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first}); 6821 } else { 6822 // Vectors of different sizes - resize and reshuffle. 6823 std::pair<T *, bool> Res1 = 6824 ResizeAction(ShuffleMask.begin()->first, Mask); 6825 std::pair<T *, bool> Res2 = ResizeAction(VMIt->first, VMIt->second); 6826 ArrayRef<int> SecMask = VMIt->second; 6827 for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) { 6828 if (Mask[I] != UndefMaskElem) { 6829 assert(SecMask[I] == UndefMaskElem && "Multiple uses of scalars."); 6830 if (Res1.second) 6831 Mask[I] = I; 6832 } else if (SecMask[I] != UndefMaskElem) { 6833 assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars."); 6834 Mask[I] = (Res2.second ? I : SecMask[I]) + VF; 6835 } 6836 } 6837 Prev = Action(Mask, {Res1.first, Res2.first}); 6838 } 6839 VMIt = std::next(VMIt); 6840 } 6841 // Perform requested actions for the remaining masks/vectors. 6842 for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) { 6843 // Shuffle other input vectors, if any. 6844 std::pair<T *, bool> Res = ResizeAction(VMIt->first, VMIt->second); 6845 ArrayRef<int> SecMask = VMIt->second; 6846 for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) { 6847 if (SecMask[I] != UndefMaskElem) { 6848 assert((Mask[I] == UndefMaskElem || IsBaseNotUndef) && 6849 "Multiple uses of scalars."); 6850 Mask[I] = (Res.second ? I : SecMask[I]) + VF; 6851 } else if (Mask[I] != UndefMaskElem) { 6852 Mask[I] = I; 6853 } 6854 } 6855 Prev = Action(Mask, {Prev, Res.first}); 6856 } 6857 return Prev; 6858 } 6859 6860 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) { 6861 InstructionCost Cost = 0; 6862 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size " 6863 << VectorizableTree.size() << ".\n"); 6864 6865 unsigned BundleWidth = VectorizableTree[0]->Scalars.size(); 6866 6867 for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) { 6868 TreeEntry &TE = *VectorizableTree[I]; 6869 6870 InstructionCost C = getEntryCost(&TE, VectorizedVals); 6871 Cost += C; 6872 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6873 << " for bundle that starts with " << *TE.Scalars[0] 6874 << ".\n" 6875 << "SLP: Current total cost = " << Cost << "\n"); 6876 } 6877 6878 SmallPtrSet<Value *, 16> ExtractCostCalculated; 6879 InstructionCost ExtractCost = 0; 6880 SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks; 6881 SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers; 6882 SmallVector<APInt> DemandedElts; 6883 for (ExternalUser &EU : ExternalUses) { 6884 // We only add extract cost once for the same scalar. 6885 if (!isa_and_nonnull<InsertElementInst>(EU.User) && 6886 !ExtractCostCalculated.insert(EU.Scalar).second) 6887 continue; 6888 6889 // Uses by ephemeral values are free (because the ephemeral value will be 6890 // removed prior to code generation, and so the extraction will be 6891 // removed as well). 6892 if (EphValues.count(EU.User)) 6893 continue; 6894 6895 // No extract cost for vector "scalar" 6896 if (isa<FixedVectorType>(EU.Scalar->getType())) 6897 continue; 6898 6899 // Already counted the cost for external uses when tried to adjust the cost 6900 // for extractelements, no need to add it again. 6901 if (isa<ExtractElementInst>(EU.Scalar)) 6902 continue; 6903 6904 // If found user is an insertelement, do not calculate extract cost but try 6905 // to detect it as a final shuffled/identity match. 6906 if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) { 6907 if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) { 6908 Optional<unsigned> InsertIdx = getInsertIndex(VU); 6909 if (InsertIdx) { 6910 const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar); 6911 auto *It = 6912 find_if(FirstUsers, 6913 [VU](const std::pair<Value *, const TreeEntry *> &Pair) { 6914 return areTwoInsertFromSameBuildVector( 6915 VU, cast<InsertElementInst>(Pair.first)); 6916 }); 6917 int VecId = -1; 6918 if (It == FirstUsers.end()) { 6919 (void)ShuffleMasks.emplace_back(); 6920 SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE]; 6921 if (Mask.empty()) 6922 Mask.assign(FTy->getNumElements(), UndefMaskElem); 6923 // Find the insertvector, vectorized in tree, if any. 6924 Value *Base = VU; 6925 while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) { 6926 if (IEBase != EU.User && 6927 (!IEBase->hasOneUse() || 6928 getInsertIndex(IEBase).getValueOr(*InsertIdx) == *InsertIdx)) 6929 break; 6930 // Build the mask for the vectorized insertelement instructions. 6931 if (const TreeEntry *E = getTreeEntry(IEBase)) { 6932 VU = IEBase; 6933 do { 6934 IEBase = cast<InsertElementInst>(Base); 6935 int Idx = *getInsertIndex(IEBase); 6936 assert(Mask[Idx] == UndefMaskElem && 6937 "InsertElementInstruction used already."); 6938 Mask[Idx] = Idx; 6939 Base = IEBase->getOperand(0); 6940 } while (E == getTreeEntry(Base)); 6941 break; 6942 } 6943 Base = cast<InsertElementInst>(Base)->getOperand(0); 6944 } 6945 FirstUsers.emplace_back(VU, ScalarTE); 6946 DemandedElts.push_back(APInt::getZero(FTy->getNumElements())); 6947 VecId = FirstUsers.size() - 1; 6948 } else { 6949 if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first))) 6950 It->first = VU; 6951 VecId = std::distance(FirstUsers.begin(), It); 6952 } 6953 int InIdx = *InsertIdx; 6954 SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE]; 6955 if (Mask.empty()) 6956 Mask.assign(FTy->getNumElements(), UndefMaskElem); 6957 Mask[InIdx] = EU.Lane; 6958 DemandedElts[VecId].setBit(InIdx); 6959 continue; 6960 } 6961 } 6962 } 6963 6964 // If we plan to rewrite the tree in a smaller type, we will need to sign 6965 // extend the extracted value back to the original type. Here, we account 6966 // for the extract and the added cost of the sign extend if needed. 6967 auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth); 6968 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 6969 if (MinBWs.count(ScalarRoot)) { 6970 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 6971 auto Extend = 6972 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt; 6973 VecTy = FixedVectorType::get(MinTy, BundleWidth); 6974 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(), 6975 VecTy, EU.Lane); 6976 } else { 6977 ExtractCost += 6978 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane); 6979 } 6980 } 6981 6982 InstructionCost SpillCost = getSpillCost(); 6983 Cost += SpillCost + ExtractCost; 6984 auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask) { 6985 InstructionCost C = 0; 6986 unsigned VF = Mask.size(); 6987 unsigned VecVF = TE->getVectorFactor(); 6988 if (VF != VecVF && 6989 (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) || 6990 (all_of(Mask, 6991 [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) && 6992 !ShuffleVectorInst::isIdentityMask(Mask)))) { 6993 SmallVector<int> OrigMask(VecVF, UndefMaskElem); 6994 std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)), 6995 OrigMask.begin()); 6996 C = TTI->getShuffleCost( 6997 TTI::SK_PermuteSingleSrc, 6998 FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask); 6999 LLVM_DEBUG( 7000 dbgs() << "SLP: Adding cost " << C 7001 << " for final shuffle of insertelement external users.\n"; 7002 TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"); 7003 Cost += C; 7004 return std::make_pair(TE, true); 7005 } 7006 return std::make_pair(TE, false); 7007 }; 7008 // Calculate the cost of the reshuffled vectors, if any. 7009 for (int I = 0, E = FirstUsers.size(); I < E; ++I) { 7010 Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0); 7011 unsigned VF = ShuffleMasks[I].begin()->second.size(); 7012 auto *FTy = FixedVectorType::get( 7013 cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF); 7014 auto Vector = ShuffleMasks[I].takeVector(); 7015 auto &&EstimateShufflesCost = [this, FTy, 7016 &Cost](ArrayRef<int> Mask, 7017 ArrayRef<const TreeEntry *> TEs) { 7018 assert((TEs.size() == 1 || TEs.size() == 2) && 7019 "Expected exactly 1 or 2 tree entries."); 7020 if (TEs.size() == 1) { 7021 int Limit = 2 * Mask.size(); 7022 if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) || 7023 !ShuffleVectorInst::isIdentityMask(Mask)) { 7024 InstructionCost C = 7025 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask); 7026 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 7027 << " for final shuffle of insertelement " 7028 "external users.\n"; 7029 TEs.front()->dump(); 7030 dbgs() << "SLP: Current total cost = " << Cost << "\n"); 7031 Cost += C; 7032 } 7033 } else { 7034 InstructionCost C = 7035 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask); 7036 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 7037 << " for final shuffle of vector node and external " 7038 "insertelement users.\n"; 7039 if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump(); 7040 dbgs() << "SLP: Current total cost = " << Cost << "\n"); 7041 Cost += C; 7042 } 7043 return TEs.back(); 7044 }; 7045 (void)performExtractsShuffleAction<const TreeEntry>( 7046 makeMutableArrayRef(Vector.data(), Vector.size()), Base, 7047 [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF, 7048 EstimateShufflesCost); 7049 InstructionCost InsertCost = TTI->getScalarizationOverhead( 7050 cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I], 7051 /*Insert*/ true, /*Extract*/ false); 7052 Cost -= InsertCost; 7053 } 7054 7055 #ifndef NDEBUG 7056 SmallString<256> Str; 7057 { 7058 raw_svector_ostream OS(Str); 7059 OS << "SLP: Spill Cost = " << SpillCost << ".\n" 7060 << "SLP: Extract Cost = " << ExtractCost << ".\n" 7061 << "SLP: Total Cost = " << Cost << ".\n"; 7062 } 7063 LLVM_DEBUG(dbgs() << Str); 7064 if (ViewSLPTree) 7065 ViewGraph(this, "SLP" + F->getName(), false, Str); 7066 #endif 7067 7068 return Cost; 7069 } 7070 7071 Optional<TargetTransformInfo::ShuffleKind> 7072 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 7073 SmallVectorImpl<const TreeEntry *> &Entries) { 7074 // TODO: currently checking only for Scalars in the tree entry, need to count 7075 // reused elements too for better cost estimation. 7076 Mask.assign(TE->Scalars.size(), UndefMaskElem); 7077 Entries.clear(); 7078 // Build a lists of values to tree entries. 7079 DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs; 7080 for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) { 7081 if (EntryPtr.get() == TE) 7082 break; 7083 if (EntryPtr->State != TreeEntry::NeedToGather) 7084 continue; 7085 for (Value *V : EntryPtr->Scalars) 7086 ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get()); 7087 } 7088 // Find all tree entries used by the gathered values. If no common entries 7089 // found - not a shuffle. 7090 // Here we build a set of tree nodes for each gathered value and trying to 7091 // find the intersection between these sets. If we have at least one common 7092 // tree node for each gathered value - we have just a permutation of the 7093 // single vector. If we have 2 different sets, we're in situation where we 7094 // have a permutation of 2 input vectors. 7095 SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs; 7096 DenseMap<Value *, int> UsedValuesEntry; 7097 for (Value *V : TE->Scalars) { 7098 if (isa<UndefValue>(V)) 7099 continue; 7100 // Build a list of tree entries where V is used. 7101 SmallPtrSet<const TreeEntry *, 4> VToTEs; 7102 auto It = ValueToTEs.find(V); 7103 if (It != ValueToTEs.end()) 7104 VToTEs = It->second; 7105 if (const TreeEntry *VTE = getTreeEntry(V)) 7106 VToTEs.insert(VTE); 7107 if (VToTEs.empty()) 7108 return None; 7109 if (UsedTEs.empty()) { 7110 // The first iteration, just insert the list of nodes to vector. 7111 UsedTEs.push_back(VToTEs); 7112 } else { 7113 // Need to check if there are any previously used tree nodes which use V. 7114 // If there are no such nodes, consider that we have another one input 7115 // vector. 7116 SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs); 7117 unsigned Idx = 0; 7118 for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) { 7119 // Do we have a non-empty intersection of previously listed tree entries 7120 // and tree entries using current V? 7121 set_intersect(VToTEs, Set); 7122 if (!VToTEs.empty()) { 7123 // Yes, write the new subset and continue analysis for the next 7124 // scalar. 7125 Set.swap(VToTEs); 7126 break; 7127 } 7128 VToTEs = SavedVToTEs; 7129 ++Idx; 7130 } 7131 // No non-empty intersection found - need to add a second set of possible 7132 // source vectors. 7133 if (Idx == UsedTEs.size()) { 7134 // If the number of input vectors is greater than 2 - not a permutation, 7135 // fallback to the regular gather. 7136 if (UsedTEs.size() == 2) 7137 return None; 7138 UsedTEs.push_back(SavedVToTEs); 7139 Idx = UsedTEs.size() - 1; 7140 } 7141 UsedValuesEntry.try_emplace(V, Idx); 7142 } 7143 } 7144 7145 if (UsedTEs.empty()) { 7146 assert(all_of(TE->Scalars, UndefValue::classof) && 7147 "Expected vector of undefs only."); 7148 return None; 7149 } 7150 7151 unsigned VF = 0; 7152 if (UsedTEs.size() == 1) { 7153 // Try to find the perfect match in another gather node at first. 7154 auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) { 7155 return EntryPtr->isSame(TE->Scalars); 7156 }); 7157 if (It != UsedTEs.front().end()) { 7158 Entries.push_back(*It); 7159 std::iota(Mask.begin(), Mask.end(), 0); 7160 return TargetTransformInfo::SK_PermuteSingleSrc; 7161 } 7162 // No perfect match, just shuffle, so choose the first tree node. 7163 Entries.push_back(*UsedTEs.front().begin()); 7164 } else { 7165 // Try to find nodes with the same vector factor. 7166 assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries."); 7167 DenseMap<int, const TreeEntry *> VFToTE; 7168 for (const TreeEntry *TE : UsedTEs.front()) 7169 VFToTE.try_emplace(TE->getVectorFactor(), TE); 7170 for (const TreeEntry *TE : UsedTEs.back()) { 7171 auto It = VFToTE.find(TE->getVectorFactor()); 7172 if (It != VFToTE.end()) { 7173 VF = It->first; 7174 Entries.push_back(It->second); 7175 Entries.push_back(TE); 7176 break; 7177 } 7178 } 7179 // No 2 source vectors with the same vector factor - give up and do regular 7180 // gather. 7181 if (Entries.empty()) 7182 return None; 7183 } 7184 7185 // Build a shuffle mask for better cost estimation and vector emission. 7186 for (int I = 0, E = TE->Scalars.size(); I < E; ++I) { 7187 Value *V = TE->Scalars[I]; 7188 if (isa<UndefValue>(V)) 7189 continue; 7190 unsigned Idx = UsedValuesEntry.lookup(V); 7191 const TreeEntry *VTE = Entries[Idx]; 7192 int FoundLane = VTE->findLaneForValue(V); 7193 Mask[I] = Idx * VF + FoundLane; 7194 // Extra check required by isSingleSourceMaskImpl function (called by 7195 // ShuffleVectorInst::isSingleSourceMask). 7196 if (Mask[I] >= 2 * E) 7197 return None; 7198 } 7199 switch (Entries.size()) { 7200 case 1: 7201 return TargetTransformInfo::SK_PermuteSingleSrc; 7202 case 2: 7203 return TargetTransformInfo::SK_PermuteTwoSrc; 7204 default: 7205 break; 7206 } 7207 return None; 7208 } 7209 7210 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty, 7211 const APInt &ShuffledIndices, 7212 bool NeedToShuffle) const { 7213 InstructionCost Cost = 7214 TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true, 7215 /*Extract*/ false); 7216 if (NeedToShuffle) 7217 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty); 7218 return Cost; 7219 } 7220 7221 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const { 7222 // Find the type of the operands in VL. 7223 Type *ScalarTy = VL[0]->getType(); 7224 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 7225 ScalarTy = SI->getValueOperand()->getType(); 7226 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 7227 bool DuplicateNonConst = false; 7228 // Find the cost of inserting/extracting values from the vector. 7229 // Check if the same elements are inserted several times and count them as 7230 // shuffle candidates. 7231 APInt ShuffledElements = APInt::getZero(VL.size()); 7232 DenseSet<Value *> UniqueElements; 7233 // Iterate in reverse order to consider insert elements with the high cost. 7234 for (unsigned I = VL.size(); I > 0; --I) { 7235 unsigned Idx = I - 1; 7236 // No need to shuffle duplicates for constants. 7237 if (isConstant(VL[Idx])) { 7238 ShuffledElements.setBit(Idx); 7239 continue; 7240 } 7241 if (!UniqueElements.insert(VL[Idx]).second) { 7242 DuplicateNonConst = true; 7243 ShuffledElements.setBit(Idx); 7244 } 7245 } 7246 return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst); 7247 } 7248 7249 // Perform operand reordering on the instructions in VL and return the reordered 7250 // operands in Left and Right. 7251 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 7252 SmallVectorImpl<Value *> &Left, 7253 SmallVectorImpl<Value *> &Right, 7254 const DataLayout &DL, 7255 ScalarEvolution &SE, 7256 const BoUpSLP &R) { 7257 if (VL.empty()) 7258 return; 7259 VLOperands Ops(VL, DL, SE, R); 7260 // Reorder the operands in place. 7261 Ops.reorder(); 7262 Left = Ops.getVL(0); 7263 Right = Ops.getVL(1); 7264 } 7265 7266 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) { 7267 // Get the basic block this bundle is in. All instructions in the bundle 7268 // should be in this block (except for extractelement-like instructions with 7269 // constant indeces). 7270 auto *Front = E->getMainOp(); 7271 auto *BB = Front->getParent(); 7272 assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool { 7273 auto *I = cast<Instruction>(V); 7274 return !E->isOpcodeOrAlt(I) || I->getParent() == BB || 7275 isVectorLikeInstWithConstOps(I); 7276 })); 7277 7278 auto &&FindLastInst = [E, Front, this, &BB]() { 7279 Instruction *LastInst = Front; 7280 for (Value *V : E->Scalars) { 7281 auto *I = dyn_cast<Instruction>(V); 7282 if (!I) 7283 continue; 7284 if (LastInst->getParent() == I->getParent()) { 7285 if (LastInst->comesBefore(I)) 7286 LastInst = I; 7287 continue; 7288 } 7289 assert(isVectorLikeInstWithConstOps(LastInst) && 7290 isVectorLikeInstWithConstOps(I) && 7291 "Expected vector-like insts only."); 7292 if (!DT->isReachableFromEntry(LastInst->getParent())) { 7293 LastInst = I; 7294 continue; 7295 } 7296 if (!DT->isReachableFromEntry(I->getParent())) 7297 continue; 7298 auto *NodeA = DT->getNode(LastInst->getParent()); 7299 auto *NodeB = DT->getNode(I->getParent()); 7300 assert(NodeA && "Should only process reachable instructions"); 7301 assert(NodeB && "Should only process reachable instructions"); 7302 assert((NodeA == NodeB) == 7303 (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && 7304 "Different nodes should have different DFS numbers"); 7305 if (NodeA->getDFSNumIn() < NodeB->getDFSNumIn()) 7306 LastInst = I; 7307 } 7308 BB = LastInst->getParent(); 7309 return LastInst; 7310 }; 7311 7312 auto &&FindFirstInst = [E, Front]() { 7313 Instruction *FirstInst = Front; 7314 for (Value *V : E->Scalars) { 7315 auto *I = dyn_cast<Instruction>(V); 7316 if (!I) 7317 continue; 7318 if (I->comesBefore(FirstInst)) 7319 FirstInst = I; 7320 } 7321 return FirstInst; 7322 }; 7323 7324 // Set the insert point to the beginning of the basic block if the entry 7325 // should not be scheduled. 7326 if (E->State != TreeEntry::NeedToGather && 7327 doesNotNeedToSchedule(E->Scalars)) { 7328 Instruction *InsertInst; 7329 if (all_of(E->Scalars, isUsedOutsideBlock)) 7330 InsertInst = FindLastInst(); 7331 else 7332 InsertInst = FindFirstInst(); 7333 // If the instruction is PHI, set the insert point after all the PHIs. 7334 if (isa<PHINode>(InsertInst)) 7335 InsertInst = BB->getFirstNonPHI(); 7336 BasicBlock::iterator InsertPt = InsertInst->getIterator(); 7337 Builder.SetInsertPoint(BB, InsertPt); 7338 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 7339 return; 7340 } 7341 7342 // The last instruction in the bundle in program order. 7343 Instruction *LastInst = nullptr; 7344 7345 // Find the last instruction. The common case should be that BB has been 7346 // scheduled, and the last instruction is VL.back(). So we start with 7347 // VL.back() and iterate over schedule data until we reach the end of the 7348 // bundle. The end of the bundle is marked by null ScheduleData. 7349 if (BlocksSchedules.count(BB)) { 7350 Value *V = E->isOneOf(E->Scalars.back()); 7351 if (doesNotNeedToBeScheduled(V)) 7352 V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled); 7353 auto *Bundle = BlocksSchedules[BB]->getScheduleData(V); 7354 if (Bundle && Bundle->isPartOfBundle()) 7355 for (; Bundle; Bundle = Bundle->NextInBundle) 7356 if (Bundle->OpValue == Bundle->Inst) 7357 LastInst = Bundle->Inst; 7358 } 7359 7360 // LastInst can still be null at this point if there's either not an entry 7361 // for BB in BlocksSchedules or there's no ScheduleData available for 7362 // VL.back(). This can be the case if buildTree_rec aborts for various 7363 // reasons (e.g., the maximum recursion depth is reached, the maximum region 7364 // size is reached, etc.). ScheduleData is initialized in the scheduling 7365 // "dry-run". 7366 // 7367 // If this happens, we can still find the last instruction by brute force. We 7368 // iterate forwards from Front (inclusive) until we either see all 7369 // instructions in the bundle or reach the end of the block. If Front is the 7370 // last instruction in program order, LastInst will be set to Front, and we 7371 // will visit all the remaining instructions in the block. 7372 // 7373 // One of the reasons we exit early from buildTree_rec is to place an upper 7374 // bound on compile-time. Thus, taking an additional compile-time hit here is 7375 // not ideal. However, this should be exceedingly rare since it requires that 7376 // we both exit early from buildTree_rec and that the bundle be out-of-order 7377 // (causing us to iterate all the way to the end of the block). 7378 if (!LastInst) { 7379 LastInst = FindLastInst(); 7380 // If the instruction is PHI, set the insert point after all the PHIs. 7381 if (isa<PHINode>(LastInst)) 7382 LastInst = BB->getFirstNonPHI()->getPrevNode(); 7383 } 7384 assert(LastInst && "Failed to find last instruction in bundle"); 7385 7386 // Set the insertion point after the last instruction in the bundle. Set the 7387 // debug location to Front. 7388 Builder.SetInsertPoint(BB, std::next(LastInst->getIterator())); 7389 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 7390 } 7391 7392 Value *BoUpSLP::gather(ArrayRef<Value *> VL) { 7393 // List of instructions/lanes from current block and/or the blocks which are 7394 // part of the current loop. These instructions will be inserted at the end to 7395 // make it possible to optimize loops and hoist invariant instructions out of 7396 // the loops body with better chances for success. 7397 SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts; 7398 SmallSet<int, 4> PostponedIndices; 7399 Loop *L = LI->getLoopFor(Builder.GetInsertBlock()); 7400 auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) { 7401 SmallPtrSet<BasicBlock *, 4> Visited; 7402 while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second) 7403 InsertBB = InsertBB->getSinglePredecessor(); 7404 return InsertBB && InsertBB == InstBB; 7405 }; 7406 for (int I = 0, E = VL.size(); I < E; ++I) { 7407 if (auto *Inst = dyn_cast<Instruction>(VL[I])) 7408 if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) || 7409 getTreeEntry(Inst) || (L && (L->contains(Inst)))) && 7410 PostponedIndices.insert(I).second) 7411 PostponedInsts.emplace_back(Inst, I); 7412 } 7413 7414 auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) { 7415 Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos)); 7416 auto *InsElt = dyn_cast<InsertElementInst>(Vec); 7417 if (!InsElt) 7418 return Vec; 7419 GatherShuffleSeq.insert(InsElt); 7420 CSEBlocks.insert(InsElt->getParent()); 7421 // Add to our 'need-to-extract' list. 7422 if (TreeEntry *Entry = getTreeEntry(V)) { 7423 // Find which lane we need to extract. 7424 unsigned FoundLane = Entry->findLaneForValue(V); 7425 ExternalUses.emplace_back(V, InsElt, FoundLane); 7426 } 7427 return Vec; 7428 }; 7429 Value *Val0 = 7430 isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0]; 7431 FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size()); 7432 Value *Vec = PoisonValue::get(VecTy); 7433 SmallVector<int> NonConsts; 7434 // Insert constant values at first. 7435 for (int I = 0, E = VL.size(); I < E; ++I) { 7436 if (PostponedIndices.contains(I)) 7437 continue; 7438 if (!isConstant(VL[I])) { 7439 NonConsts.push_back(I); 7440 continue; 7441 } 7442 Vec = CreateInsertElement(Vec, VL[I], I); 7443 } 7444 // Insert non-constant values. 7445 for (int I : NonConsts) 7446 Vec = CreateInsertElement(Vec, VL[I], I); 7447 // Append instructions, which are/may be part of the loop, in the end to make 7448 // it possible to hoist non-loop-based instructions. 7449 for (const std::pair<Value *, unsigned> &Pair : PostponedInsts) 7450 Vec = CreateInsertElement(Vec, Pair.first, Pair.second); 7451 7452 return Vec; 7453 } 7454 7455 namespace { 7456 /// Merges shuffle masks and emits final shuffle instruction, if required. 7457 class ShuffleInstructionBuilder { 7458 IRBuilderBase &Builder; 7459 const unsigned VF = 0; 7460 bool IsFinalized = false; 7461 SmallVector<int, 4> Mask; 7462 /// Holds all of the instructions that we gathered. 7463 SetVector<Instruction *> &GatherShuffleSeq; 7464 /// A list of blocks that we are going to CSE. 7465 SetVector<BasicBlock *> &CSEBlocks; 7466 7467 public: 7468 ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF, 7469 SetVector<Instruction *> &GatherShuffleSeq, 7470 SetVector<BasicBlock *> &CSEBlocks) 7471 : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq), 7472 CSEBlocks(CSEBlocks) {} 7473 7474 /// Adds a mask, inverting it before applying. 7475 void addInversedMask(ArrayRef<unsigned> SubMask) { 7476 if (SubMask.empty()) 7477 return; 7478 SmallVector<int, 4> NewMask; 7479 inversePermutation(SubMask, NewMask); 7480 addMask(NewMask); 7481 } 7482 7483 /// Functions adds masks, merging them into single one. 7484 void addMask(ArrayRef<unsigned> SubMask) { 7485 SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end()); 7486 addMask(NewMask); 7487 } 7488 7489 void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); } 7490 7491 Value *finalize(Value *V) { 7492 IsFinalized = true; 7493 unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements(); 7494 if (VF == ValueVF && Mask.empty()) 7495 return V; 7496 SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem); 7497 std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0); 7498 addMask(NormalizedMask); 7499 7500 if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask)) 7501 return V; 7502 Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle"); 7503 if (auto *I = dyn_cast<Instruction>(Vec)) { 7504 GatherShuffleSeq.insert(I); 7505 CSEBlocks.insert(I->getParent()); 7506 } 7507 return Vec; 7508 } 7509 7510 ~ShuffleInstructionBuilder() { 7511 assert((IsFinalized || Mask.empty()) && 7512 "Shuffle construction must be finalized."); 7513 } 7514 }; 7515 } // namespace 7516 7517 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { 7518 const unsigned VF = VL.size(); 7519 InstructionsState S = getSameOpcode(VL); 7520 if (S.getOpcode()) { 7521 if (TreeEntry *E = getTreeEntry(S.OpValue)) 7522 if (E->isSame(VL)) { 7523 Value *V = vectorizeTree(E); 7524 if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) { 7525 if (!E->ReuseShuffleIndices.empty()) { 7526 // Reshuffle to get only unique values. 7527 // If some of the scalars are duplicated in the vectorization tree 7528 // entry, we do not vectorize them but instead generate a mask for 7529 // the reuses. But if there are several users of the same entry, 7530 // they may have different vectorization factors. This is especially 7531 // important for PHI nodes. In this case, we need to adapt the 7532 // resulting instruction for the user vectorization factor and have 7533 // to reshuffle it again to take only unique elements of the vector. 7534 // Without this code the function incorrectly returns reduced vector 7535 // instruction with the same elements, not with the unique ones. 7536 7537 // block: 7538 // %phi = phi <2 x > { .., %entry} {%shuffle, %block} 7539 // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0> 7540 // ... (use %2) 7541 // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0} 7542 // br %block 7543 SmallVector<int> UniqueIdxs(VF, UndefMaskElem); 7544 SmallSet<int, 4> UsedIdxs; 7545 int Pos = 0; 7546 int Sz = VL.size(); 7547 for (int Idx : E->ReuseShuffleIndices) { 7548 if (Idx != Sz && Idx != UndefMaskElem && 7549 UsedIdxs.insert(Idx).second) 7550 UniqueIdxs[Idx] = Pos; 7551 ++Pos; 7552 } 7553 assert(VF >= UsedIdxs.size() && "Expected vectorization factor " 7554 "less than original vector size."); 7555 UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem); 7556 V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle"); 7557 } else { 7558 assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() && 7559 "Expected vectorization factor less " 7560 "than original vector size."); 7561 SmallVector<int> UniformMask(VF, 0); 7562 std::iota(UniformMask.begin(), UniformMask.end(), 0); 7563 V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle"); 7564 } 7565 if (auto *I = dyn_cast<Instruction>(V)) { 7566 GatherShuffleSeq.insert(I); 7567 CSEBlocks.insert(I->getParent()); 7568 } 7569 } 7570 return V; 7571 } 7572 } 7573 7574 // Can't vectorize this, so simply build a new vector with each lane 7575 // corresponding to the requested value. 7576 return createBuildVector(VL); 7577 } 7578 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) { 7579 unsigned VF = VL.size(); 7580 // Exploit possible reuse of values across lanes. 7581 SmallVector<int> ReuseShuffleIndicies; 7582 SmallVector<Value *> UniqueValues; 7583 if (VL.size() > 2) { 7584 DenseMap<Value *, unsigned> UniquePositions; 7585 unsigned NumValues = 7586 std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) { 7587 return !isa<UndefValue>(V); 7588 }).base()); 7589 VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues)); 7590 int UniqueVals = 0; 7591 for (Value *V : VL.drop_back(VL.size() - VF)) { 7592 if (isa<UndefValue>(V)) { 7593 ReuseShuffleIndicies.emplace_back(UndefMaskElem); 7594 continue; 7595 } 7596 if (isConstant(V)) { 7597 ReuseShuffleIndicies.emplace_back(UniqueValues.size()); 7598 UniqueValues.emplace_back(V); 7599 continue; 7600 } 7601 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 7602 ReuseShuffleIndicies.emplace_back(Res.first->second); 7603 if (Res.second) { 7604 UniqueValues.emplace_back(V); 7605 ++UniqueVals; 7606 } 7607 } 7608 if (UniqueVals == 1 && UniqueValues.size() == 1) { 7609 // Emit pure splat vector. 7610 ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(), 7611 UndefMaskElem); 7612 } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) { 7613 if (UniqueValues.empty()) { 7614 assert(all_of(VL, UndefValue::classof) && "Expected list of undefs."); 7615 NumValues = VF; 7616 } 7617 ReuseShuffleIndicies.clear(); 7618 UniqueValues.clear(); 7619 UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues)); 7620 } 7621 UniqueValues.append(VF - UniqueValues.size(), 7622 PoisonValue::get(VL[0]->getType())); 7623 VL = UniqueValues; 7624 } 7625 7626 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 7627 CSEBlocks); 7628 Value *Vec = gather(VL); 7629 if (!ReuseShuffleIndicies.empty()) { 7630 ShuffleBuilder.addMask(ReuseShuffleIndicies); 7631 Vec = ShuffleBuilder.finalize(Vec); 7632 } 7633 return Vec; 7634 } 7635 7636 Value *BoUpSLP::vectorizeTree(TreeEntry *E) { 7637 IRBuilder<>::InsertPointGuard Guard(Builder); 7638 7639 if (E->VectorizedValue) { 7640 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"); 7641 return E->VectorizedValue; 7642 } 7643 7644 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 7645 unsigned VF = E->getVectorFactor(); 7646 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 7647 CSEBlocks); 7648 if (E->State == TreeEntry::NeedToGather) { 7649 if (E->getMainOp()) 7650 setInsertPointAfterBundle(E); 7651 Value *Vec; 7652 SmallVector<int> Mask; 7653 SmallVector<const TreeEntry *> Entries; 7654 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 7655 isGatherShuffledEntry(E, Mask, Entries); 7656 if (Shuffle.hasValue()) { 7657 assert((Entries.size() == 1 || Entries.size() == 2) && 7658 "Expected shuffle of 1 or 2 entries."); 7659 Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue, 7660 Entries.back()->VectorizedValue, Mask); 7661 if (auto *I = dyn_cast<Instruction>(Vec)) { 7662 GatherShuffleSeq.insert(I); 7663 CSEBlocks.insert(I->getParent()); 7664 } 7665 } else { 7666 Vec = gather(E->Scalars); 7667 } 7668 if (NeedToShuffleReuses) { 7669 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7670 Vec = ShuffleBuilder.finalize(Vec); 7671 } 7672 E->VectorizedValue = Vec; 7673 return Vec; 7674 } 7675 7676 assert((E->State == TreeEntry::Vectorize || 7677 E->State == TreeEntry::ScatterVectorize) && 7678 "Unhandled state"); 7679 unsigned ShuffleOrOp = 7680 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 7681 Instruction *VL0 = E->getMainOp(); 7682 Type *ScalarTy = VL0->getType(); 7683 if (auto *Store = dyn_cast<StoreInst>(VL0)) 7684 ScalarTy = Store->getValueOperand()->getType(); 7685 else if (auto *IE = dyn_cast<InsertElementInst>(VL0)) 7686 ScalarTy = IE->getOperand(1)->getType(); 7687 auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size()); 7688 switch (ShuffleOrOp) { 7689 case Instruction::PHI: { 7690 assert( 7691 (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) && 7692 "PHI reordering is free."); 7693 auto *PH = cast<PHINode>(VL0); 7694 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI()); 7695 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 7696 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); 7697 Value *V = NewPhi; 7698 7699 // Adjust insertion point once all PHI's have been generated. 7700 Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt()); 7701 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 7702 7703 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7704 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7705 V = ShuffleBuilder.finalize(V); 7706 7707 E->VectorizedValue = V; 7708 7709 // PHINodes may have multiple entries from the same block. We want to 7710 // visit every block once. 7711 SmallPtrSet<BasicBlock*, 4> VisitedBBs; 7712 7713 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 7714 ValueList Operands; 7715 BasicBlock *IBB = PH->getIncomingBlock(i); 7716 7717 if (!VisitedBBs.insert(IBB).second) { 7718 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB); 7719 continue; 7720 } 7721 7722 Builder.SetInsertPoint(IBB->getTerminator()); 7723 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 7724 Value *Vec = vectorizeTree(E->getOperand(i)); 7725 NewPhi->addIncoming(Vec, IBB); 7726 } 7727 7728 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && 7729 "Invalid number of incoming values"); 7730 return V; 7731 } 7732 7733 case Instruction::ExtractElement: { 7734 Value *V = E->getSingleOperand(0); 7735 Builder.SetInsertPoint(VL0); 7736 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7737 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7738 V = ShuffleBuilder.finalize(V); 7739 E->VectorizedValue = V; 7740 return V; 7741 } 7742 case Instruction::ExtractValue: { 7743 auto *LI = cast<LoadInst>(E->getSingleOperand(0)); 7744 Builder.SetInsertPoint(LI); 7745 auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace()); 7746 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy); 7747 LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign()); 7748 Value *NewV = propagateMetadata(V, E->Scalars); 7749 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7750 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7751 NewV = ShuffleBuilder.finalize(NewV); 7752 E->VectorizedValue = NewV; 7753 return NewV; 7754 } 7755 case Instruction::InsertElement: { 7756 assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique"); 7757 Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back())); 7758 Value *V = vectorizeTree(E->getOperand(1)); 7759 7760 // Create InsertVector shuffle if necessary 7761 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 7762 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); 7763 })); 7764 const unsigned NumElts = 7765 cast<FixedVectorType>(FirstInsert->getType())->getNumElements(); 7766 const unsigned NumScalars = E->Scalars.size(); 7767 7768 unsigned Offset = *getInsertIndex(VL0); 7769 assert(Offset < NumElts && "Failed to find vector index offset"); 7770 7771 // Create shuffle to resize vector 7772 SmallVector<int> Mask; 7773 if (!E->ReorderIndices.empty()) { 7774 inversePermutation(E->ReorderIndices, Mask); 7775 Mask.append(NumElts - NumScalars, UndefMaskElem); 7776 } else { 7777 Mask.assign(NumElts, UndefMaskElem); 7778 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 7779 } 7780 // Create InsertVector shuffle if necessary 7781 bool IsIdentity = true; 7782 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 7783 Mask.swap(PrevMask); 7784 for (unsigned I = 0; I < NumScalars; ++I) { 7785 Value *Scalar = E->Scalars[PrevMask[I]]; 7786 unsigned InsertIdx = *getInsertIndex(Scalar); 7787 IsIdentity &= InsertIdx - Offset == I; 7788 Mask[InsertIdx - Offset] = I; 7789 } 7790 if (!IsIdentity || NumElts != NumScalars) { 7791 V = Builder.CreateShuffleVector(V, Mask); 7792 if (auto *I = dyn_cast<Instruction>(V)) { 7793 GatherShuffleSeq.insert(I); 7794 CSEBlocks.insert(I->getParent()); 7795 } 7796 } 7797 7798 if ((!IsIdentity || Offset != 0 || 7799 !isUndefVector(FirstInsert->getOperand(0))) && 7800 NumElts != NumScalars) { 7801 SmallVector<int> InsertMask(NumElts); 7802 std::iota(InsertMask.begin(), InsertMask.end(), 0); 7803 for (unsigned I = 0; I < NumElts; I++) { 7804 if (Mask[I] != UndefMaskElem) 7805 InsertMask[Offset + I] = NumElts + I; 7806 } 7807 7808 V = Builder.CreateShuffleVector( 7809 FirstInsert->getOperand(0), V, InsertMask, 7810 cast<Instruction>(E->Scalars.back())->getName()); 7811 if (auto *I = dyn_cast<Instruction>(V)) { 7812 GatherShuffleSeq.insert(I); 7813 CSEBlocks.insert(I->getParent()); 7814 } 7815 } 7816 7817 ++NumVectorInstructions; 7818 E->VectorizedValue = V; 7819 return V; 7820 } 7821 case Instruction::ZExt: 7822 case Instruction::SExt: 7823 case Instruction::FPToUI: 7824 case Instruction::FPToSI: 7825 case Instruction::FPExt: 7826 case Instruction::PtrToInt: 7827 case Instruction::IntToPtr: 7828 case Instruction::SIToFP: 7829 case Instruction::UIToFP: 7830 case Instruction::Trunc: 7831 case Instruction::FPTrunc: 7832 case Instruction::BitCast: { 7833 setInsertPointAfterBundle(E); 7834 7835 Value *InVec = vectorizeTree(E->getOperand(0)); 7836 7837 if (E->VectorizedValue) { 7838 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7839 return E->VectorizedValue; 7840 } 7841 7842 auto *CI = cast<CastInst>(VL0); 7843 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); 7844 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7845 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7846 V = ShuffleBuilder.finalize(V); 7847 7848 E->VectorizedValue = V; 7849 ++NumVectorInstructions; 7850 return V; 7851 } 7852 case Instruction::FCmp: 7853 case Instruction::ICmp: { 7854 setInsertPointAfterBundle(E); 7855 7856 Value *L = vectorizeTree(E->getOperand(0)); 7857 Value *R = vectorizeTree(E->getOperand(1)); 7858 7859 if (E->VectorizedValue) { 7860 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7861 return E->VectorizedValue; 7862 } 7863 7864 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 7865 Value *V = Builder.CreateCmp(P0, L, R); 7866 propagateIRFlags(V, E->Scalars, VL0); 7867 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7868 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7869 V = ShuffleBuilder.finalize(V); 7870 7871 E->VectorizedValue = V; 7872 ++NumVectorInstructions; 7873 return V; 7874 } 7875 case Instruction::Select: { 7876 setInsertPointAfterBundle(E); 7877 7878 Value *Cond = vectorizeTree(E->getOperand(0)); 7879 Value *True = vectorizeTree(E->getOperand(1)); 7880 Value *False = vectorizeTree(E->getOperand(2)); 7881 7882 if (E->VectorizedValue) { 7883 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7884 return E->VectorizedValue; 7885 } 7886 7887 Value *V = Builder.CreateSelect(Cond, True, False); 7888 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7889 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7890 V = ShuffleBuilder.finalize(V); 7891 7892 E->VectorizedValue = V; 7893 ++NumVectorInstructions; 7894 return V; 7895 } 7896 case Instruction::FNeg: { 7897 setInsertPointAfterBundle(E); 7898 7899 Value *Op = vectorizeTree(E->getOperand(0)); 7900 7901 if (E->VectorizedValue) { 7902 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7903 return E->VectorizedValue; 7904 } 7905 7906 Value *V = Builder.CreateUnOp( 7907 static_cast<Instruction::UnaryOps>(E->getOpcode()), Op); 7908 propagateIRFlags(V, E->Scalars, VL0); 7909 if (auto *I = dyn_cast<Instruction>(V)) 7910 V = propagateMetadata(I, E->Scalars); 7911 7912 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7913 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7914 V = ShuffleBuilder.finalize(V); 7915 7916 E->VectorizedValue = V; 7917 ++NumVectorInstructions; 7918 7919 return V; 7920 } 7921 case Instruction::Add: 7922 case Instruction::FAdd: 7923 case Instruction::Sub: 7924 case Instruction::FSub: 7925 case Instruction::Mul: 7926 case Instruction::FMul: 7927 case Instruction::UDiv: 7928 case Instruction::SDiv: 7929 case Instruction::FDiv: 7930 case Instruction::URem: 7931 case Instruction::SRem: 7932 case Instruction::FRem: 7933 case Instruction::Shl: 7934 case Instruction::LShr: 7935 case Instruction::AShr: 7936 case Instruction::And: 7937 case Instruction::Or: 7938 case Instruction::Xor: { 7939 setInsertPointAfterBundle(E); 7940 7941 Value *LHS = vectorizeTree(E->getOperand(0)); 7942 Value *RHS = vectorizeTree(E->getOperand(1)); 7943 7944 if (E->VectorizedValue) { 7945 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7946 return E->VectorizedValue; 7947 } 7948 7949 Value *V = Builder.CreateBinOp( 7950 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, 7951 RHS); 7952 propagateIRFlags(V, E->Scalars, VL0); 7953 if (auto *I = dyn_cast<Instruction>(V)) 7954 V = propagateMetadata(I, E->Scalars); 7955 7956 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7957 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7958 V = ShuffleBuilder.finalize(V); 7959 7960 E->VectorizedValue = V; 7961 ++NumVectorInstructions; 7962 7963 return V; 7964 } 7965 case Instruction::Load: { 7966 // Loads are inserted at the head of the tree because we don't want to 7967 // sink them all the way down past store instructions. 7968 setInsertPointAfterBundle(E); 7969 7970 LoadInst *LI = cast<LoadInst>(VL0); 7971 Instruction *NewLI; 7972 unsigned AS = LI->getPointerAddressSpace(); 7973 Value *PO = LI->getPointerOperand(); 7974 if (E->State == TreeEntry::Vectorize) { 7975 Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS)); 7976 NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign()); 7977 7978 // The pointer operand uses an in-tree scalar so we add the new BitCast 7979 // or LoadInst to ExternalUses list to make sure that an extract will 7980 // be generated in the future. 7981 if (TreeEntry *Entry = getTreeEntry(PO)) { 7982 // Find which lane we need to extract. 7983 unsigned FoundLane = Entry->findLaneForValue(PO); 7984 ExternalUses.emplace_back( 7985 PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane); 7986 } 7987 } else { 7988 assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state"); 7989 Value *VecPtr = vectorizeTree(E->getOperand(0)); 7990 // Use the minimum alignment of the gathered loads. 7991 Align CommonAlignment = LI->getAlign(); 7992 for (Value *V : E->Scalars) 7993 CommonAlignment = 7994 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 7995 NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment); 7996 } 7997 Value *V = propagateMetadata(NewLI, E->Scalars); 7998 7999 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8000 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8001 V = ShuffleBuilder.finalize(V); 8002 E->VectorizedValue = V; 8003 ++NumVectorInstructions; 8004 return V; 8005 } 8006 case Instruction::Store: { 8007 auto *SI = cast<StoreInst>(VL0); 8008 unsigned AS = SI->getPointerAddressSpace(); 8009 8010 setInsertPointAfterBundle(E); 8011 8012 Value *VecValue = vectorizeTree(E->getOperand(0)); 8013 ShuffleBuilder.addMask(E->ReorderIndices); 8014 VecValue = ShuffleBuilder.finalize(VecValue); 8015 8016 Value *ScalarPtr = SI->getPointerOperand(); 8017 Value *VecPtr = Builder.CreateBitCast( 8018 ScalarPtr, VecValue->getType()->getPointerTo(AS)); 8019 StoreInst *ST = 8020 Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign()); 8021 8022 // The pointer operand uses an in-tree scalar, so add the new BitCast or 8023 // StoreInst to ExternalUses to make sure that an extract will be 8024 // generated in the future. 8025 if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) { 8026 // Find which lane we need to extract. 8027 unsigned FoundLane = Entry->findLaneForValue(ScalarPtr); 8028 ExternalUses.push_back(ExternalUser( 8029 ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST, 8030 FoundLane)); 8031 } 8032 8033 Value *V = propagateMetadata(ST, E->Scalars); 8034 8035 E->VectorizedValue = V; 8036 ++NumVectorInstructions; 8037 return V; 8038 } 8039 case Instruction::GetElementPtr: { 8040 auto *GEP0 = cast<GetElementPtrInst>(VL0); 8041 setInsertPointAfterBundle(E); 8042 8043 Value *Op0 = vectorizeTree(E->getOperand(0)); 8044 8045 SmallVector<Value *> OpVecs; 8046 for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) { 8047 Value *OpVec = vectorizeTree(E->getOperand(J)); 8048 OpVecs.push_back(OpVec); 8049 } 8050 8051 Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs); 8052 if (Instruction *I = dyn_cast<Instruction>(V)) 8053 V = propagateMetadata(I, E->Scalars); 8054 8055 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8056 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8057 V = ShuffleBuilder.finalize(V); 8058 8059 E->VectorizedValue = V; 8060 ++NumVectorInstructions; 8061 8062 return V; 8063 } 8064 case Instruction::Call: { 8065 CallInst *CI = cast<CallInst>(VL0); 8066 setInsertPointAfterBundle(E); 8067 8068 Intrinsic::ID IID = Intrinsic::not_intrinsic; 8069 if (Function *FI = CI->getCalledFunction()) 8070 IID = FI->getIntrinsicID(); 8071 8072 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 8073 8074 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 8075 bool UseIntrinsic = ID != Intrinsic::not_intrinsic && 8076 VecCallCosts.first <= VecCallCosts.second; 8077 8078 Value *ScalarArg = nullptr; 8079 std::vector<Value *> OpVecs; 8080 SmallVector<Type *, 2> TysForDecl = 8081 {FixedVectorType::get(CI->getType(), E->Scalars.size())}; 8082 for (int j = 0, e = CI->arg_size(); j < e; ++j) { 8083 ValueList OpVL; 8084 // Some intrinsics have scalar arguments. This argument should not be 8085 // vectorized. 8086 if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) { 8087 CallInst *CEI = cast<CallInst>(VL0); 8088 ScalarArg = CEI->getArgOperand(j); 8089 OpVecs.push_back(CEI->getArgOperand(j)); 8090 if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j)) 8091 TysForDecl.push_back(ScalarArg->getType()); 8092 continue; 8093 } 8094 8095 Value *OpVec = vectorizeTree(E->getOperand(j)); 8096 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n"); 8097 OpVecs.push_back(OpVec); 8098 if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j)) 8099 TysForDecl.push_back(OpVec->getType()); 8100 } 8101 8102 Function *CF; 8103 if (!UseIntrinsic) { 8104 VFShape Shape = 8105 VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 8106 VecTy->getNumElements())), 8107 false /*HasGlobalPred*/); 8108 CF = VFDatabase(*CI).getVectorizedFunction(Shape); 8109 } else { 8110 CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl); 8111 } 8112 8113 SmallVector<OperandBundleDef, 1> OpBundles; 8114 CI->getOperandBundlesAsDefs(OpBundles); 8115 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles); 8116 8117 // The scalar argument uses an in-tree scalar so we add the new vectorized 8118 // call to ExternalUses list to make sure that an extract will be 8119 // generated in the future. 8120 if (ScalarArg) { 8121 if (TreeEntry *Entry = getTreeEntry(ScalarArg)) { 8122 // Find which lane we need to extract. 8123 unsigned FoundLane = Entry->findLaneForValue(ScalarArg); 8124 ExternalUses.push_back( 8125 ExternalUser(ScalarArg, cast<User>(V), FoundLane)); 8126 } 8127 } 8128 8129 propagateIRFlags(V, E->Scalars, VL0); 8130 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8131 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8132 V = ShuffleBuilder.finalize(V); 8133 8134 E->VectorizedValue = V; 8135 ++NumVectorInstructions; 8136 return V; 8137 } 8138 case Instruction::ShuffleVector: { 8139 assert(E->isAltShuffle() && 8140 ((Instruction::isBinaryOp(E->getOpcode()) && 8141 Instruction::isBinaryOp(E->getAltOpcode())) || 8142 (Instruction::isCast(E->getOpcode()) && 8143 Instruction::isCast(E->getAltOpcode())) || 8144 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 8145 "Invalid Shuffle Vector Operand"); 8146 8147 Value *LHS = nullptr, *RHS = nullptr; 8148 if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) { 8149 setInsertPointAfterBundle(E); 8150 LHS = vectorizeTree(E->getOperand(0)); 8151 RHS = vectorizeTree(E->getOperand(1)); 8152 } else { 8153 setInsertPointAfterBundle(E); 8154 LHS = vectorizeTree(E->getOperand(0)); 8155 } 8156 8157 if (E->VectorizedValue) { 8158 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 8159 return E->VectorizedValue; 8160 } 8161 8162 Value *V0, *V1; 8163 if (Instruction::isBinaryOp(E->getOpcode())) { 8164 V0 = Builder.CreateBinOp( 8165 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS); 8166 V1 = Builder.CreateBinOp( 8167 static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS); 8168 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 8169 V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS); 8170 auto *AltCI = cast<CmpInst>(E->getAltOp()); 8171 CmpInst::Predicate AltPred = AltCI->getPredicate(); 8172 V1 = Builder.CreateCmp(AltPred, LHS, RHS); 8173 } else { 8174 V0 = Builder.CreateCast( 8175 static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy); 8176 V1 = Builder.CreateCast( 8177 static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy); 8178 } 8179 // Add V0 and V1 to later analysis to try to find and remove matching 8180 // instruction, if any. 8181 for (Value *V : {V0, V1}) { 8182 if (auto *I = dyn_cast<Instruction>(V)) { 8183 GatherShuffleSeq.insert(I); 8184 CSEBlocks.insert(I->getParent()); 8185 } 8186 } 8187 8188 // Create shuffle to take alternate operations from the vector. 8189 // Also, gather up main and alt scalar ops to propagate IR flags to 8190 // each vector operation. 8191 ValueList OpScalars, AltScalars; 8192 SmallVector<int> Mask; 8193 buildShuffleEntryMask( 8194 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 8195 [E](Instruction *I) { 8196 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 8197 return isAlternateInstruction(I, E->getMainOp(), E->getAltOp()); 8198 }, 8199 Mask, &OpScalars, &AltScalars); 8200 8201 propagateIRFlags(V0, OpScalars); 8202 propagateIRFlags(V1, AltScalars); 8203 8204 Value *V = Builder.CreateShuffleVector(V0, V1, Mask); 8205 if (auto *I = dyn_cast<Instruction>(V)) { 8206 V = propagateMetadata(I, E->Scalars); 8207 GatherShuffleSeq.insert(I); 8208 CSEBlocks.insert(I->getParent()); 8209 } 8210 V = ShuffleBuilder.finalize(V); 8211 8212 E->VectorizedValue = V; 8213 ++NumVectorInstructions; 8214 8215 return V; 8216 } 8217 default: 8218 llvm_unreachable("unknown inst"); 8219 } 8220 return nullptr; 8221 } 8222 8223 Value *BoUpSLP::vectorizeTree() { 8224 ExtraValueToDebugLocsMap ExternallyUsedValues; 8225 return vectorizeTree(ExternallyUsedValues); 8226 } 8227 8228 namespace { 8229 /// Data type for handling buildvector sequences with the reused scalars from 8230 /// other tree entries. 8231 struct ShuffledInsertData { 8232 /// List of insertelements to be replaced by shuffles. 8233 SmallVector<InsertElementInst *> InsertElements; 8234 /// The parent vectors and shuffle mask for the given list of inserts. 8235 MapVector<Value *, SmallVector<int>> ValueMasks; 8236 }; 8237 } // namespace 8238 8239 Value * 8240 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) { 8241 // All blocks must be scheduled before any instructions are inserted. 8242 for (auto &BSIter : BlocksSchedules) { 8243 scheduleBlock(BSIter.second.get()); 8244 } 8245 8246 Builder.SetInsertPoint(&F->getEntryBlock().front()); 8247 auto *VectorRoot = vectorizeTree(VectorizableTree[0].get()); 8248 8249 // If the vectorized tree can be rewritten in a smaller type, we truncate the 8250 // vectorized root. InstCombine will then rewrite the entire expression. We 8251 // sign extend the extracted values below. 8252 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 8253 if (MinBWs.count(ScalarRoot)) { 8254 if (auto *I = dyn_cast<Instruction>(VectorRoot)) { 8255 // If current instr is a phi and not the last phi, insert it after the 8256 // last phi node. 8257 if (isa<PHINode>(I)) 8258 Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt()); 8259 else 8260 Builder.SetInsertPoint(&*++BasicBlock::iterator(I)); 8261 } 8262 auto BundleWidth = VectorizableTree[0]->Scalars.size(); 8263 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 8264 auto *VecTy = FixedVectorType::get(MinTy, BundleWidth); 8265 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy); 8266 VectorizableTree[0]->VectorizedValue = Trunc; 8267 } 8268 8269 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() 8270 << " values .\n"); 8271 8272 SmallVector<ShuffledInsertData> ShuffledInserts; 8273 // Maps vector instruction to original insertelement instruction 8274 DenseMap<Value *, InsertElementInst *> VectorToInsertElement; 8275 // Extract all of the elements with the external uses. 8276 for (const auto &ExternalUse : ExternalUses) { 8277 Value *Scalar = ExternalUse.Scalar; 8278 llvm::User *User = ExternalUse.User; 8279 8280 // Skip users that we already RAUW. This happens when one instruction 8281 // has multiple uses of the same value. 8282 if (User && !is_contained(Scalar->users(), User)) 8283 continue; 8284 TreeEntry *E = getTreeEntry(Scalar); 8285 assert(E && "Invalid scalar"); 8286 assert(E->State != TreeEntry::NeedToGather && 8287 "Extracting from a gather list"); 8288 8289 Value *Vec = E->VectorizedValue; 8290 assert(Vec && "Can't find vectorizable value"); 8291 8292 Value *Lane = Builder.getInt32(ExternalUse.Lane); 8293 auto ExtractAndExtendIfNeeded = [&](Value *Vec) { 8294 if (Scalar->getType() != Vec->getType()) { 8295 Value *Ex; 8296 // "Reuse" the existing extract to improve final codegen. 8297 if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) { 8298 Ex = Builder.CreateExtractElement(ES->getOperand(0), 8299 ES->getOperand(1)); 8300 } else { 8301 Ex = Builder.CreateExtractElement(Vec, Lane); 8302 } 8303 // If necessary, sign-extend or zero-extend ScalarRoot 8304 // to the larger type. 8305 if (!MinBWs.count(ScalarRoot)) 8306 return Ex; 8307 if (MinBWs[ScalarRoot].second) 8308 return Builder.CreateSExt(Ex, Scalar->getType()); 8309 return Builder.CreateZExt(Ex, Scalar->getType()); 8310 } 8311 assert(isa<FixedVectorType>(Scalar->getType()) && 8312 isa<InsertElementInst>(Scalar) && 8313 "In-tree scalar of vector type is not insertelement?"); 8314 auto *IE = cast<InsertElementInst>(Scalar); 8315 VectorToInsertElement.try_emplace(Vec, IE); 8316 return Vec; 8317 }; 8318 // If User == nullptr, the Scalar is used as extra arg. Generate 8319 // ExtractElement instruction and update the record for this scalar in 8320 // ExternallyUsedValues. 8321 if (!User) { 8322 assert(ExternallyUsedValues.count(Scalar) && 8323 "Scalar with nullptr as an external user must be registered in " 8324 "ExternallyUsedValues map"); 8325 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 8326 Builder.SetInsertPoint(VecI->getParent(), 8327 std::next(VecI->getIterator())); 8328 } else { 8329 Builder.SetInsertPoint(&F->getEntryBlock().front()); 8330 } 8331 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 8332 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent()); 8333 auto &NewInstLocs = ExternallyUsedValues[NewInst]; 8334 auto It = ExternallyUsedValues.find(Scalar); 8335 assert(It != ExternallyUsedValues.end() && 8336 "Externally used scalar is not found in ExternallyUsedValues"); 8337 NewInstLocs.append(It->second); 8338 ExternallyUsedValues.erase(Scalar); 8339 // Required to update internally referenced instructions. 8340 Scalar->replaceAllUsesWith(NewInst); 8341 continue; 8342 } 8343 8344 if (auto *VU = dyn_cast<InsertElementInst>(User)) { 8345 // Skip if the scalar is another vector op or Vec is not an instruction. 8346 if (!Scalar->getType()->isVectorTy() && isa<Instruction>(Vec)) { 8347 if (auto *FTy = dyn_cast<FixedVectorType>(User->getType())) { 8348 Optional<unsigned> InsertIdx = getInsertIndex(VU); 8349 if (InsertIdx) { 8350 auto *It = 8351 find_if(ShuffledInserts, [VU](const ShuffledInsertData &Data) { 8352 // Checks if 2 insertelements are from the same buildvector. 8353 InsertElementInst *VecInsert = Data.InsertElements.front(); 8354 return areTwoInsertFromSameBuildVector(VU, VecInsert); 8355 }); 8356 unsigned Idx = *InsertIdx; 8357 if (It == ShuffledInserts.end()) { 8358 (void)ShuffledInserts.emplace_back(); 8359 It = std::next(ShuffledInserts.begin(), 8360 ShuffledInserts.size() - 1); 8361 SmallVectorImpl<int> &Mask = It->ValueMasks[Vec]; 8362 if (Mask.empty()) 8363 Mask.assign(FTy->getNumElements(), UndefMaskElem); 8364 // Find the insertvector, vectorized in tree, if any. 8365 Value *Base = VU; 8366 while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) { 8367 if (IEBase != User && 8368 (!IEBase->hasOneUse() || 8369 getInsertIndex(IEBase).getValueOr(Idx) == Idx)) 8370 break; 8371 // Build the mask for the vectorized insertelement instructions. 8372 if (const TreeEntry *E = getTreeEntry(IEBase)) { 8373 do { 8374 IEBase = cast<InsertElementInst>(Base); 8375 int IEIdx = *getInsertIndex(IEBase); 8376 assert(Mask[Idx] == UndefMaskElem && 8377 "InsertElementInstruction used already."); 8378 Mask[IEIdx] = IEIdx; 8379 Base = IEBase->getOperand(0); 8380 } while (E == getTreeEntry(Base)); 8381 break; 8382 } 8383 Base = cast<InsertElementInst>(Base)->getOperand(0); 8384 // After the vectorization the def-use chain has changed, need 8385 // to look through original insertelement instructions, if they 8386 // get replaced by vector instructions. 8387 auto It = VectorToInsertElement.find(Base); 8388 if (It != VectorToInsertElement.end()) 8389 Base = It->second; 8390 } 8391 } 8392 SmallVectorImpl<int> &Mask = It->ValueMasks[Vec]; 8393 if (Mask.empty()) 8394 Mask.assign(FTy->getNumElements(), UndefMaskElem); 8395 Mask[Idx] = ExternalUse.Lane; 8396 It->InsertElements.push_back(cast<InsertElementInst>(User)); 8397 continue; 8398 } 8399 } 8400 } 8401 } 8402 8403 // Generate extracts for out-of-tree users. 8404 // Find the insertion point for the extractelement lane. 8405 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 8406 if (PHINode *PH = dyn_cast<PHINode>(User)) { 8407 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { 8408 if (PH->getIncomingValue(i) == Scalar) { 8409 Instruction *IncomingTerminator = 8410 PH->getIncomingBlock(i)->getTerminator(); 8411 if (isa<CatchSwitchInst>(IncomingTerminator)) { 8412 Builder.SetInsertPoint(VecI->getParent(), 8413 std::next(VecI->getIterator())); 8414 } else { 8415 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator()); 8416 } 8417 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 8418 CSEBlocks.insert(PH->getIncomingBlock(i)); 8419 PH->setOperand(i, NewInst); 8420 } 8421 } 8422 } else { 8423 Builder.SetInsertPoint(cast<Instruction>(User)); 8424 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 8425 CSEBlocks.insert(cast<Instruction>(User)->getParent()); 8426 User->replaceUsesOfWith(Scalar, NewInst); 8427 } 8428 } else { 8429 Builder.SetInsertPoint(&F->getEntryBlock().front()); 8430 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 8431 CSEBlocks.insert(&F->getEntryBlock()); 8432 User->replaceUsesOfWith(Scalar, NewInst); 8433 } 8434 8435 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n"); 8436 } 8437 8438 // Checks if the mask is an identity mask. 8439 auto &&IsIdentityMask = [](ArrayRef<int> Mask, FixedVectorType *VecTy) { 8440 int Limit = Mask.size(); 8441 return VecTy->getNumElements() == Mask.size() && 8442 all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) && 8443 ShuffleVectorInst::isIdentityMask(Mask); 8444 }; 8445 // Tries to combine 2 different masks into single one. 8446 auto &&CombineMasks = [](SmallVectorImpl<int> &Mask, ArrayRef<int> ExtMask) { 8447 SmallVector<int> NewMask(ExtMask.size(), UndefMaskElem); 8448 for (int I = 0, Sz = ExtMask.size(); I < Sz; ++I) { 8449 if (ExtMask[I] == UndefMaskElem) 8450 continue; 8451 NewMask[I] = Mask[ExtMask[I]]; 8452 } 8453 Mask.swap(NewMask); 8454 }; 8455 // Peek through shuffles, trying to simplify the final shuffle code. 8456 auto &&PeekThroughShuffles = 8457 [&IsIdentityMask, &CombineMasks](Value *&V, SmallVectorImpl<int> &Mask, 8458 bool CheckForLengthChange = false) { 8459 while (auto *SV = dyn_cast<ShuffleVectorInst>(V)) { 8460 // Exit if not a fixed vector type or changing size shuffle. 8461 if (!isa<FixedVectorType>(SV->getType()) || 8462 (CheckForLengthChange && SV->changesLength())) 8463 break; 8464 // Exit if the identity or broadcast mask is found. 8465 if (IsIdentityMask(Mask, cast<FixedVectorType>(SV->getType())) || 8466 SV->isZeroEltSplat()) 8467 break; 8468 bool IsOp1Undef = isUndefVector(SV->getOperand(0)); 8469 bool IsOp2Undef = isUndefVector(SV->getOperand(1)); 8470 if (!IsOp1Undef && !IsOp2Undef) 8471 break; 8472 SmallVector<int> ShuffleMask(SV->getShuffleMask().begin(), 8473 SV->getShuffleMask().end()); 8474 CombineMasks(ShuffleMask, Mask); 8475 Mask.swap(ShuffleMask); 8476 if (IsOp2Undef) 8477 V = SV->getOperand(0); 8478 else 8479 V = SV->getOperand(1); 8480 } 8481 }; 8482 // Smart shuffle instruction emission, walks through shuffles trees and 8483 // tries to find the best matching vector for the actual shuffle 8484 // instruction. 8485 auto &&CreateShuffle = [this, &IsIdentityMask, &PeekThroughShuffles, 8486 &CombineMasks](Value *V1, Value *V2, 8487 ArrayRef<int> Mask) -> Value * { 8488 assert(V1 && "Expected at least one vector value."); 8489 if (V2 && !isUndefVector(V2)) { 8490 // Peek through shuffles. 8491 Value *Op1 = V1; 8492 Value *Op2 = V2; 8493 int VF = 8494 cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue(); 8495 SmallVector<int> CombinedMask1(Mask.size(), UndefMaskElem); 8496 SmallVector<int> CombinedMask2(Mask.size(), UndefMaskElem); 8497 for (int I = 0, E = Mask.size(); I < E; ++I) { 8498 if (Mask[I] < VF) 8499 CombinedMask1[I] = Mask[I]; 8500 else 8501 CombinedMask2[I] = Mask[I] - VF; 8502 } 8503 Value *PrevOp1; 8504 Value *PrevOp2; 8505 do { 8506 PrevOp1 = Op1; 8507 PrevOp2 = Op2; 8508 PeekThroughShuffles(Op1, CombinedMask1, /*CheckForLengthChange=*/true); 8509 PeekThroughShuffles(Op2, CombinedMask2, /*CheckForLengthChange=*/true); 8510 // Check if we have 2 resizing shuffles - need to peek through operands 8511 // again. 8512 if (auto *SV1 = dyn_cast<ShuffleVectorInst>(Op1)) 8513 if (auto *SV2 = dyn_cast<ShuffleVectorInst>(Op2)) 8514 if (SV1->getOperand(0)->getType() == 8515 SV2->getOperand(0)->getType() && 8516 SV1->getOperand(0)->getType() != SV1->getType() && 8517 isUndefVector(SV1->getOperand(1)) && 8518 isUndefVector(SV2->getOperand(1))) { 8519 Op1 = SV1->getOperand(0); 8520 Op2 = SV2->getOperand(0); 8521 SmallVector<int> ShuffleMask1(SV1->getShuffleMask().begin(), 8522 SV1->getShuffleMask().end()); 8523 CombineMasks(ShuffleMask1, CombinedMask1); 8524 CombinedMask1.swap(ShuffleMask1); 8525 SmallVector<int> ShuffleMask2(SV2->getShuffleMask().begin(), 8526 SV2->getShuffleMask().end()); 8527 CombineMasks(ShuffleMask2, CombinedMask2); 8528 CombinedMask2.swap(ShuffleMask2); 8529 } 8530 } while (PrevOp1 != Op1 || PrevOp2 != Op2); 8531 VF = cast<VectorType>(Op1->getType()) 8532 ->getElementCount() 8533 .getKnownMinValue(); 8534 for (int I = 0, E = Mask.size(); I < E; ++I) { 8535 if (CombinedMask2[I] != UndefMaskElem) { 8536 assert(CombinedMask1[I] == UndefMaskElem && 8537 "Expected undefined mask element"); 8538 CombinedMask1[I] = CombinedMask2[I] + (Op1 == Op2 ? 0 : VF); 8539 } 8540 } 8541 Value *Vec = Builder.CreateShuffleVector( 8542 Op1, Op1 == Op2 ? PoisonValue::get(Op1->getType()) : Op2, 8543 CombinedMask1); 8544 if (auto *I = dyn_cast<Instruction>(Vec)) { 8545 GatherShuffleSeq.insert(I); 8546 CSEBlocks.insert(I->getParent()); 8547 } 8548 return Vec; 8549 } 8550 if (isa<PoisonValue>(V1)) 8551 return PoisonValue::get(FixedVectorType::get( 8552 cast<VectorType>(V1->getType())->getElementType(), Mask.size())); 8553 Value *Op = V1; 8554 SmallVector<int> CombinedMask(Mask.begin(), Mask.end()); 8555 PeekThroughShuffles(Op, CombinedMask); 8556 if (!isa<FixedVectorType>(Op->getType()) || 8557 !IsIdentityMask(CombinedMask, cast<FixedVectorType>(Op->getType()))) { 8558 Value *Vec = Builder.CreateShuffleVector(Op, CombinedMask); 8559 if (auto *I = dyn_cast<Instruction>(Vec)) { 8560 GatherShuffleSeq.insert(I); 8561 CSEBlocks.insert(I->getParent()); 8562 } 8563 return Vec; 8564 } 8565 return Op; 8566 }; 8567 8568 auto &&ResizeToVF = [&CreateShuffle](Value *Vec, ArrayRef<int> Mask) { 8569 unsigned VF = Mask.size(); 8570 unsigned VecVF = cast<FixedVectorType>(Vec->getType())->getNumElements(); 8571 if (VF != VecVF) { 8572 if (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); })) { 8573 Vec = CreateShuffle(Vec, nullptr, Mask); 8574 return std::make_pair(Vec, true); 8575 } 8576 SmallVector<int> ResizeMask(VF, UndefMaskElem); 8577 for (unsigned I = 0; I < VF; ++I) { 8578 if (Mask[I] != UndefMaskElem) 8579 ResizeMask[Mask[I]] = Mask[I]; 8580 } 8581 Vec = CreateShuffle(Vec, nullptr, ResizeMask); 8582 } 8583 8584 return std::make_pair(Vec, false); 8585 }; 8586 // Perform shuffling of the vectorize tree entries for better handling of 8587 // external extracts. 8588 for (int I = 0, E = ShuffledInserts.size(); I < E; ++I) { 8589 // Find the first and the last instruction in the list of insertelements. 8590 sort(ShuffledInserts[I].InsertElements, isFirstInsertElement); 8591 InsertElementInst *FirstInsert = ShuffledInserts[I].InsertElements.front(); 8592 InsertElementInst *LastInsert = ShuffledInserts[I].InsertElements.back(); 8593 Builder.SetInsertPoint(LastInsert); 8594 auto Vector = ShuffledInserts[I].ValueMasks.takeVector(); 8595 Value *NewInst = performExtractsShuffleAction<Value>( 8596 makeMutableArrayRef(Vector.data(), Vector.size()), 8597 FirstInsert->getOperand(0), 8598 [](Value *Vec) { 8599 return cast<VectorType>(Vec->getType()) 8600 ->getElementCount() 8601 .getKnownMinValue(); 8602 }, 8603 ResizeToVF, 8604 [FirstInsert, &CreateShuffle](ArrayRef<int> Mask, 8605 ArrayRef<Value *> Vals) { 8606 assert((Vals.size() == 1 || Vals.size() == 2) && 8607 "Expected exactly 1 or 2 input values."); 8608 if (Vals.size() == 1) { 8609 // Do not create shuffle if the mask is a simple identity 8610 // non-resizing mask. 8611 if (Mask.size() != cast<FixedVectorType>(Vals.front()->getType()) 8612 ->getNumElements() || 8613 !ShuffleVectorInst::isIdentityMask(Mask)) 8614 return CreateShuffle(Vals.front(), nullptr, Mask); 8615 return Vals.front(); 8616 } 8617 return CreateShuffle(Vals.front() ? Vals.front() 8618 : FirstInsert->getOperand(0), 8619 Vals.back(), Mask); 8620 }); 8621 auto It = ShuffledInserts[I].InsertElements.rbegin(); 8622 // Rebuild buildvector chain. 8623 InsertElementInst *II = nullptr; 8624 if (It != ShuffledInserts[I].InsertElements.rend()) 8625 II = *It; 8626 SmallVector<Instruction *> Inserts; 8627 while (It != ShuffledInserts[I].InsertElements.rend()) { 8628 assert(II && "Must be an insertelement instruction."); 8629 if (*It == II) 8630 ++It; 8631 else 8632 Inserts.push_back(cast<Instruction>(II)); 8633 II = dyn_cast<InsertElementInst>(II->getOperand(0)); 8634 } 8635 for (Instruction *II : reverse(Inserts)) { 8636 II->replaceUsesOfWith(II->getOperand(0), NewInst); 8637 if (auto *NewI = dyn_cast<Instruction>(NewInst)) 8638 if (II->getParent() == NewI->getParent() && II->comesBefore(NewI)) 8639 II->moveAfter(NewI); 8640 NewInst = II; 8641 } 8642 LastInsert->replaceAllUsesWith(NewInst); 8643 for (InsertElementInst *IE : reverse(ShuffledInserts[I].InsertElements)) { 8644 IE->replaceUsesOfWith(IE->getOperand(1), 8645 PoisonValue::get(IE->getOperand(1)->getType())); 8646 eraseInstruction(IE); 8647 } 8648 CSEBlocks.insert(LastInsert->getParent()); 8649 } 8650 8651 // For each vectorized value: 8652 for (auto &TEPtr : VectorizableTree) { 8653 TreeEntry *Entry = TEPtr.get(); 8654 8655 // No need to handle users of gathered values. 8656 if (Entry->State == TreeEntry::NeedToGather) 8657 continue; 8658 8659 assert(Entry->VectorizedValue && "Can't find vectorizable value"); 8660 8661 // For each lane: 8662 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 8663 Value *Scalar = Entry->Scalars[Lane]; 8664 8665 #ifndef NDEBUG 8666 Type *Ty = Scalar->getType(); 8667 if (!Ty->isVoidTy()) { 8668 for (User *U : Scalar->users()) { 8669 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n"); 8670 8671 // It is legal to delete users in the ignorelist. 8672 assert((getTreeEntry(U) || 8673 (UserIgnoreList && UserIgnoreList->contains(U)) || 8674 (isa_and_nonnull<Instruction>(U) && 8675 isDeleted(cast<Instruction>(U)))) && 8676 "Deleting out-of-tree value"); 8677 } 8678 } 8679 #endif 8680 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n"); 8681 eraseInstruction(cast<Instruction>(Scalar)); 8682 } 8683 } 8684 8685 Builder.ClearInsertionPoint(); 8686 InstrElementSize.clear(); 8687 8688 return VectorizableTree[0]->VectorizedValue; 8689 } 8690 8691 void BoUpSLP::optimizeGatherSequence() { 8692 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size() 8693 << " gather sequences instructions.\n"); 8694 // LICM InsertElementInst sequences. 8695 for (Instruction *I : GatherShuffleSeq) { 8696 if (isDeleted(I)) 8697 continue; 8698 8699 // Check if this block is inside a loop. 8700 Loop *L = LI->getLoopFor(I->getParent()); 8701 if (!L) 8702 continue; 8703 8704 // Check if it has a preheader. 8705 BasicBlock *PreHeader = L->getLoopPreheader(); 8706 if (!PreHeader) 8707 continue; 8708 8709 // If the vector or the element that we insert into it are 8710 // instructions that are defined in this basic block then we can't 8711 // hoist this instruction. 8712 if (any_of(I->operands(), [L](Value *V) { 8713 auto *OpI = dyn_cast<Instruction>(V); 8714 return OpI && L->contains(OpI); 8715 })) 8716 continue; 8717 8718 // We can hoist this instruction. Move it to the pre-header. 8719 I->moveBefore(PreHeader->getTerminator()); 8720 } 8721 8722 // Make a list of all reachable blocks in our CSE queue. 8723 SmallVector<const DomTreeNode *, 8> CSEWorkList; 8724 CSEWorkList.reserve(CSEBlocks.size()); 8725 for (BasicBlock *BB : CSEBlocks) 8726 if (DomTreeNode *N = DT->getNode(BB)) { 8727 assert(DT->isReachableFromEntry(N)); 8728 CSEWorkList.push_back(N); 8729 } 8730 8731 // Sort blocks by domination. This ensures we visit a block after all blocks 8732 // dominating it are visited. 8733 llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) { 8734 assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && 8735 "Different nodes should have different DFS numbers"); 8736 return A->getDFSNumIn() < B->getDFSNumIn(); 8737 }); 8738 8739 // Less defined shuffles can be replaced by the more defined copies. 8740 // Between two shuffles one is less defined if it has the same vector operands 8741 // and its mask indeces are the same as in the first one or undefs. E.g. 8742 // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0, 8743 // poison, <0, 0, 0, 0>. 8744 auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2, 8745 SmallVectorImpl<int> &NewMask) { 8746 if (I1->getType() != I2->getType()) 8747 return false; 8748 auto *SI1 = dyn_cast<ShuffleVectorInst>(I1); 8749 auto *SI2 = dyn_cast<ShuffleVectorInst>(I2); 8750 if (!SI1 || !SI2) 8751 return I1->isIdenticalTo(I2); 8752 if (SI1->isIdenticalTo(SI2)) 8753 return true; 8754 for (int I = 0, E = SI1->getNumOperands(); I < E; ++I) 8755 if (SI1->getOperand(I) != SI2->getOperand(I)) 8756 return false; 8757 // Check if the second instruction is more defined than the first one. 8758 NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end()); 8759 ArrayRef<int> SM1 = SI1->getShuffleMask(); 8760 // Count trailing undefs in the mask to check the final number of used 8761 // registers. 8762 unsigned LastUndefsCnt = 0; 8763 for (int I = 0, E = NewMask.size(); I < E; ++I) { 8764 if (SM1[I] == UndefMaskElem) 8765 ++LastUndefsCnt; 8766 else 8767 LastUndefsCnt = 0; 8768 if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem && 8769 NewMask[I] != SM1[I]) 8770 return false; 8771 if (NewMask[I] == UndefMaskElem) 8772 NewMask[I] = SM1[I]; 8773 } 8774 // Check if the last undefs actually change the final number of used vector 8775 // registers. 8776 return SM1.size() - LastUndefsCnt > 1 && 8777 TTI->getNumberOfParts(SI1->getType()) == 8778 TTI->getNumberOfParts( 8779 FixedVectorType::get(SI1->getType()->getElementType(), 8780 SM1.size() - LastUndefsCnt)); 8781 }; 8782 // Perform O(N^2) search over the gather/shuffle sequences and merge identical 8783 // instructions. TODO: We can further optimize this scan if we split the 8784 // instructions into different buckets based on the insert lane. 8785 SmallVector<Instruction *, 16> Visited; 8786 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) { 8787 assert(*I && 8788 (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && 8789 "Worklist not sorted properly!"); 8790 BasicBlock *BB = (*I)->getBlock(); 8791 // For all instructions in blocks containing gather sequences: 8792 for (Instruction &In : llvm::make_early_inc_range(*BB)) { 8793 if (isDeleted(&In)) 8794 continue; 8795 if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) && 8796 !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In)) 8797 continue; 8798 8799 // Check if we can replace this instruction with any of the 8800 // visited instructions. 8801 bool Replaced = false; 8802 for (Instruction *&V : Visited) { 8803 SmallVector<int> NewMask; 8804 if (IsIdenticalOrLessDefined(&In, V, NewMask) && 8805 DT->dominates(V->getParent(), In.getParent())) { 8806 In.replaceAllUsesWith(V); 8807 eraseInstruction(&In); 8808 if (auto *SI = dyn_cast<ShuffleVectorInst>(V)) 8809 if (!NewMask.empty()) 8810 SI->setShuffleMask(NewMask); 8811 Replaced = true; 8812 break; 8813 } 8814 if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) && 8815 GatherShuffleSeq.contains(V) && 8816 IsIdenticalOrLessDefined(V, &In, NewMask) && 8817 DT->dominates(In.getParent(), V->getParent())) { 8818 In.moveAfter(V); 8819 V->replaceAllUsesWith(&In); 8820 eraseInstruction(V); 8821 if (auto *SI = dyn_cast<ShuffleVectorInst>(&In)) 8822 if (!NewMask.empty()) 8823 SI->setShuffleMask(NewMask); 8824 V = &In; 8825 Replaced = true; 8826 break; 8827 } 8828 } 8829 if (!Replaced) { 8830 assert(!is_contained(Visited, &In)); 8831 Visited.push_back(&In); 8832 } 8833 } 8834 } 8835 CSEBlocks.clear(); 8836 GatherShuffleSeq.clear(); 8837 } 8838 8839 BoUpSLP::ScheduleData * 8840 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) { 8841 ScheduleData *Bundle = nullptr; 8842 ScheduleData *PrevInBundle = nullptr; 8843 for (Value *V : VL) { 8844 if (doesNotNeedToBeScheduled(V)) 8845 continue; 8846 ScheduleData *BundleMember = getScheduleData(V); 8847 assert(BundleMember && 8848 "no ScheduleData for bundle member " 8849 "(maybe not in same basic block)"); 8850 assert(BundleMember->isSchedulingEntity() && 8851 "bundle member already part of other bundle"); 8852 if (PrevInBundle) { 8853 PrevInBundle->NextInBundle = BundleMember; 8854 } else { 8855 Bundle = BundleMember; 8856 } 8857 8858 // Group the instructions to a bundle. 8859 BundleMember->FirstInBundle = Bundle; 8860 PrevInBundle = BundleMember; 8861 } 8862 assert(Bundle && "Failed to find schedule bundle"); 8863 return Bundle; 8864 } 8865 8866 // Groups the instructions to a bundle (which is then a single scheduling entity) 8867 // and schedules instructions until the bundle gets ready. 8868 Optional<BoUpSLP::ScheduleData *> 8869 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 8870 const InstructionsState &S) { 8871 // No need to schedule PHIs, insertelement, extractelement and extractvalue 8872 // instructions. 8873 if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) || 8874 doesNotNeedToSchedule(VL)) 8875 return nullptr; 8876 8877 // Initialize the instruction bundle. 8878 Instruction *OldScheduleEnd = ScheduleEnd; 8879 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n"); 8880 8881 auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule, 8882 ScheduleData *Bundle) { 8883 // The scheduling region got new instructions at the lower end (or it is a 8884 // new region for the first bundle). This makes it necessary to 8885 // recalculate all dependencies. 8886 // It is seldom that this needs to be done a second time after adding the 8887 // initial bundle to the region. 8888 if (ScheduleEnd != OldScheduleEnd) { 8889 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) 8890 doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); }); 8891 ReSchedule = true; 8892 } 8893 if (Bundle) { 8894 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle 8895 << " in block " << BB->getName() << "\n"); 8896 calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP); 8897 } 8898 8899 if (ReSchedule) { 8900 resetSchedule(); 8901 initialFillReadyList(ReadyInsts); 8902 } 8903 8904 // Now try to schedule the new bundle or (if no bundle) just calculate 8905 // dependencies. As soon as the bundle is "ready" it means that there are no 8906 // cyclic dependencies and we can schedule it. Note that's important that we 8907 // don't "schedule" the bundle yet (see cancelScheduling). 8908 while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) && 8909 !ReadyInsts.empty()) { 8910 ScheduleData *Picked = ReadyInsts.pop_back_val(); 8911 assert(Picked->isSchedulingEntity() && Picked->isReady() && 8912 "must be ready to schedule"); 8913 schedule(Picked, ReadyInsts); 8914 } 8915 }; 8916 8917 // Make sure that the scheduling region contains all 8918 // instructions of the bundle. 8919 for (Value *V : VL) { 8920 if (doesNotNeedToBeScheduled(V)) 8921 continue; 8922 if (!extendSchedulingRegion(V, S)) { 8923 // If the scheduling region got new instructions at the lower end (or it 8924 // is a new region for the first bundle). This makes it necessary to 8925 // recalculate all dependencies. 8926 // Otherwise the compiler may crash trying to incorrectly calculate 8927 // dependencies and emit instruction in the wrong order at the actual 8928 // scheduling. 8929 TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr); 8930 return None; 8931 } 8932 } 8933 8934 bool ReSchedule = false; 8935 for (Value *V : VL) { 8936 if (doesNotNeedToBeScheduled(V)) 8937 continue; 8938 ScheduleData *BundleMember = getScheduleData(V); 8939 assert(BundleMember && 8940 "no ScheduleData for bundle member (maybe not in same basic block)"); 8941 8942 // Make sure we don't leave the pieces of the bundle in the ready list when 8943 // whole bundle might not be ready. 8944 ReadyInsts.remove(BundleMember); 8945 8946 if (!BundleMember->IsScheduled) 8947 continue; 8948 // A bundle member was scheduled as single instruction before and now 8949 // needs to be scheduled as part of the bundle. We just get rid of the 8950 // existing schedule. 8951 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember 8952 << " was already scheduled\n"); 8953 ReSchedule = true; 8954 } 8955 8956 auto *Bundle = buildBundle(VL); 8957 TryScheduleBundleImpl(ReSchedule, Bundle); 8958 if (!Bundle->isReady()) { 8959 cancelScheduling(VL, S.OpValue); 8960 return None; 8961 } 8962 return Bundle; 8963 } 8964 8965 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL, 8966 Value *OpValue) { 8967 if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) || 8968 doesNotNeedToSchedule(VL)) 8969 return; 8970 8971 if (doesNotNeedToBeScheduled(OpValue)) 8972 OpValue = *find_if_not(VL, doesNotNeedToBeScheduled); 8973 ScheduleData *Bundle = getScheduleData(OpValue); 8974 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n"); 8975 assert(!Bundle->IsScheduled && 8976 "Can't cancel bundle which is already scheduled"); 8977 assert(Bundle->isSchedulingEntity() && 8978 (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) && 8979 "tried to unbundle something which is not a bundle"); 8980 8981 // Remove the bundle from the ready list. 8982 if (Bundle->isReady()) 8983 ReadyInsts.remove(Bundle); 8984 8985 // Un-bundle: make single instructions out of the bundle. 8986 ScheduleData *BundleMember = Bundle; 8987 while (BundleMember) { 8988 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links"); 8989 BundleMember->FirstInBundle = BundleMember; 8990 ScheduleData *Next = BundleMember->NextInBundle; 8991 BundleMember->NextInBundle = nullptr; 8992 BundleMember->TE = nullptr; 8993 if (BundleMember->unscheduledDepsInBundle() == 0) { 8994 ReadyInsts.insert(BundleMember); 8995 } 8996 BundleMember = Next; 8997 } 8998 } 8999 9000 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() { 9001 // Allocate a new ScheduleData for the instruction. 9002 if (ChunkPos >= ChunkSize) { 9003 ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize)); 9004 ChunkPos = 0; 9005 } 9006 return &(ScheduleDataChunks.back()[ChunkPos++]); 9007 } 9008 9009 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V, 9010 const InstructionsState &S) { 9011 if (getScheduleData(V, isOneOf(S, V))) 9012 return true; 9013 Instruction *I = dyn_cast<Instruction>(V); 9014 assert(I && "bundle member must be an instruction"); 9015 assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && 9016 !doesNotNeedToBeScheduled(I) && 9017 "phi nodes/insertelements/extractelements/extractvalues don't need to " 9018 "be scheduled"); 9019 auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool { 9020 ScheduleData *ISD = getScheduleData(I); 9021 if (!ISD) 9022 return false; 9023 assert(isInSchedulingRegion(ISD) && 9024 "ScheduleData not in scheduling region"); 9025 ScheduleData *SD = allocateScheduleDataChunks(); 9026 SD->Inst = I; 9027 SD->init(SchedulingRegionID, S.OpValue); 9028 ExtraScheduleDataMap[I][S.OpValue] = SD; 9029 return true; 9030 }; 9031 if (CheckScheduleForI(I)) 9032 return true; 9033 if (!ScheduleStart) { 9034 // It's the first instruction in the new region. 9035 initScheduleData(I, I->getNextNode(), nullptr, nullptr); 9036 ScheduleStart = I; 9037 ScheduleEnd = I->getNextNode(); 9038 if (isOneOf(S, I) != I) 9039 CheckScheduleForI(I); 9040 assert(ScheduleEnd && "tried to vectorize a terminator?"); 9041 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n"); 9042 return true; 9043 } 9044 // Search up and down at the same time, because we don't know if the new 9045 // instruction is above or below the existing scheduling region. 9046 BasicBlock::reverse_iterator UpIter = 9047 ++ScheduleStart->getIterator().getReverse(); 9048 BasicBlock::reverse_iterator UpperEnd = BB->rend(); 9049 BasicBlock::iterator DownIter = ScheduleEnd->getIterator(); 9050 BasicBlock::iterator LowerEnd = BB->end(); 9051 while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I && 9052 &*DownIter != I) { 9053 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) { 9054 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n"); 9055 return false; 9056 } 9057 9058 ++UpIter; 9059 ++DownIter; 9060 } 9061 if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) { 9062 assert(I->getParent() == ScheduleStart->getParent() && 9063 "Instruction is in wrong basic block."); 9064 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion); 9065 ScheduleStart = I; 9066 if (isOneOf(S, I) != I) 9067 CheckScheduleForI(I); 9068 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I 9069 << "\n"); 9070 return true; 9071 } 9072 assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && 9073 "Expected to reach top of the basic block or instruction down the " 9074 "lower end."); 9075 assert(I->getParent() == ScheduleEnd->getParent() && 9076 "Instruction is in wrong basic block."); 9077 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion, 9078 nullptr); 9079 ScheduleEnd = I->getNextNode(); 9080 if (isOneOf(S, I) != I) 9081 CheckScheduleForI(I); 9082 assert(ScheduleEnd && "tried to vectorize a terminator?"); 9083 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n"); 9084 return true; 9085 } 9086 9087 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI, 9088 Instruction *ToI, 9089 ScheduleData *PrevLoadStore, 9090 ScheduleData *NextLoadStore) { 9091 ScheduleData *CurrentLoadStore = PrevLoadStore; 9092 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) { 9093 // No need to allocate data for non-schedulable instructions. 9094 if (doesNotNeedToBeScheduled(I)) 9095 continue; 9096 ScheduleData *SD = ScheduleDataMap.lookup(I); 9097 if (!SD) { 9098 SD = allocateScheduleDataChunks(); 9099 ScheduleDataMap[I] = SD; 9100 SD->Inst = I; 9101 } 9102 assert(!isInSchedulingRegion(SD) && 9103 "new ScheduleData already in scheduling region"); 9104 SD->init(SchedulingRegionID, I); 9105 9106 if (I->mayReadOrWriteMemory() && 9107 (!isa<IntrinsicInst>(I) || 9108 (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect && 9109 cast<IntrinsicInst>(I)->getIntrinsicID() != 9110 Intrinsic::pseudoprobe))) { 9111 // Update the linked list of memory accessing instructions. 9112 if (CurrentLoadStore) { 9113 CurrentLoadStore->NextLoadStore = SD; 9114 } else { 9115 FirstLoadStoreInRegion = SD; 9116 } 9117 CurrentLoadStore = SD; 9118 } 9119 9120 if (match(I, m_Intrinsic<Intrinsic::stacksave>()) || 9121 match(I, m_Intrinsic<Intrinsic::stackrestore>())) 9122 RegionHasStackSave = true; 9123 } 9124 if (NextLoadStore) { 9125 if (CurrentLoadStore) 9126 CurrentLoadStore->NextLoadStore = NextLoadStore; 9127 } else { 9128 LastLoadStoreInRegion = CurrentLoadStore; 9129 } 9130 } 9131 9132 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD, 9133 bool InsertInReadyList, 9134 BoUpSLP *SLP) { 9135 assert(SD->isSchedulingEntity()); 9136 9137 SmallVector<ScheduleData *, 10> WorkList; 9138 WorkList.push_back(SD); 9139 9140 while (!WorkList.empty()) { 9141 ScheduleData *SD = WorkList.pop_back_val(); 9142 for (ScheduleData *BundleMember = SD; BundleMember; 9143 BundleMember = BundleMember->NextInBundle) { 9144 assert(isInSchedulingRegion(BundleMember)); 9145 if (BundleMember->hasValidDependencies()) 9146 continue; 9147 9148 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember 9149 << "\n"); 9150 BundleMember->Dependencies = 0; 9151 BundleMember->resetUnscheduledDeps(); 9152 9153 // Handle def-use chain dependencies. 9154 if (BundleMember->OpValue != BundleMember->Inst) { 9155 if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) { 9156 BundleMember->Dependencies++; 9157 ScheduleData *DestBundle = UseSD->FirstInBundle; 9158 if (!DestBundle->IsScheduled) 9159 BundleMember->incrementUnscheduledDeps(1); 9160 if (!DestBundle->hasValidDependencies()) 9161 WorkList.push_back(DestBundle); 9162 } 9163 } else { 9164 for (User *U : BundleMember->Inst->users()) { 9165 if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) { 9166 BundleMember->Dependencies++; 9167 ScheduleData *DestBundle = UseSD->FirstInBundle; 9168 if (!DestBundle->IsScheduled) 9169 BundleMember->incrementUnscheduledDeps(1); 9170 if (!DestBundle->hasValidDependencies()) 9171 WorkList.push_back(DestBundle); 9172 } 9173 } 9174 } 9175 9176 auto makeControlDependent = [&](Instruction *I) { 9177 auto *DepDest = getScheduleData(I); 9178 assert(DepDest && "must be in schedule window"); 9179 DepDest->ControlDependencies.push_back(BundleMember); 9180 BundleMember->Dependencies++; 9181 ScheduleData *DestBundle = DepDest->FirstInBundle; 9182 if (!DestBundle->IsScheduled) 9183 BundleMember->incrementUnscheduledDeps(1); 9184 if (!DestBundle->hasValidDependencies()) 9185 WorkList.push_back(DestBundle); 9186 }; 9187 9188 // Any instruction which isn't safe to speculate at the begining of the 9189 // block is control dependend on any early exit or non-willreturn call 9190 // which proceeds it. 9191 if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) { 9192 for (Instruction *I = BundleMember->Inst->getNextNode(); 9193 I != ScheduleEnd; I = I->getNextNode()) { 9194 if (isSafeToSpeculativelyExecute(I, &*BB->begin())) 9195 continue; 9196 9197 // Add the dependency 9198 makeControlDependent(I); 9199 9200 if (!isGuaranteedToTransferExecutionToSuccessor(I)) 9201 // Everything past here must be control dependent on I. 9202 break; 9203 } 9204 } 9205 9206 if (RegionHasStackSave) { 9207 // If we have an inalloc alloca instruction, it needs to be scheduled 9208 // after any preceeding stacksave. We also need to prevent any alloca 9209 // from reordering above a preceeding stackrestore. 9210 if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) || 9211 match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) { 9212 for (Instruction *I = BundleMember->Inst->getNextNode(); 9213 I != ScheduleEnd; I = I->getNextNode()) { 9214 if (match(I, m_Intrinsic<Intrinsic::stacksave>()) || 9215 match(I, m_Intrinsic<Intrinsic::stackrestore>())) 9216 // Any allocas past here must be control dependent on I, and I 9217 // must be memory dependend on BundleMember->Inst. 9218 break; 9219 9220 if (!isa<AllocaInst>(I)) 9221 continue; 9222 9223 // Add the dependency 9224 makeControlDependent(I); 9225 } 9226 } 9227 9228 // In addition to the cases handle just above, we need to prevent 9229 // allocas from moving below a stacksave. The stackrestore case 9230 // is currently thought to be conservatism. 9231 if (isa<AllocaInst>(BundleMember->Inst)) { 9232 for (Instruction *I = BundleMember->Inst->getNextNode(); 9233 I != ScheduleEnd; I = I->getNextNode()) { 9234 if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) && 9235 !match(I, m_Intrinsic<Intrinsic::stackrestore>())) 9236 continue; 9237 9238 // Add the dependency 9239 makeControlDependent(I); 9240 break; 9241 } 9242 } 9243 } 9244 9245 // Handle the memory dependencies (if any). 9246 ScheduleData *DepDest = BundleMember->NextLoadStore; 9247 if (!DepDest) 9248 continue; 9249 Instruction *SrcInst = BundleMember->Inst; 9250 assert(SrcInst->mayReadOrWriteMemory() && 9251 "NextLoadStore list for non memory effecting bundle?"); 9252 MemoryLocation SrcLoc = getLocation(SrcInst); 9253 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory(); 9254 unsigned numAliased = 0; 9255 unsigned DistToSrc = 1; 9256 9257 for ( ; DepDest; DepDest = DepDest->NextLoadStore) { 9258 assert(isInSchedulingRegion(DepDest)); 9259 9260 // We have two limits to reduce the complexity: 9261 // 1) AliasedCheckLimit: It's a small limit to reduce calls to 9262 // SLP->isAliased (which is the expensive part in this loop). 9263 // 2) MaxMemDepDistance: It's for very large blocks and it aborts 9264 // the whole loop (even if the loop is fast, it's quadratic). 9265 // It's important for the loop break condition (see below) to 9266 // check this limit even between two read-only instructions. 9267 if (DistToSrc >= MaxMemDepDistance || 9268 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) && 9269 (numAliased >= AliasedCheckLimit || 9270 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) { 9271 9272 // We increment the counter only if the locations are aliased 9273 // (instead of counting all alias checks). This gives a better 9274 // balance between reduced runtime and accurate dependencies. 9275 numAliased++; 9276 9277 DepDest->MemoryDependencies.push_back(BundleMember); 9278 BundleMember->Dependencies++; 9279 ScheduleData *DestBundle = DepDest->FirstInBundle; 9280 if (!DestBundle->IsScheduled) { 9281 BundleMember->incrementUnscheduledDeps(1); 9282 } 9283 if (!DestBundle->hasValidDependencies()) { 9284 WorkList.push_back(DestBundle); 9285 } 9286 } 9287 9288 // Example, explaining the loop break condition: Let's assume our 9289 // starting instruction is i0 and MaxMemDepDistance = 3. 9290 // 9291 // +--------v--v--v 9292 // i0,i1,i2,i3,i4,i5,i6,i7,i8 9293 // +--------^--^--^ 9294 // 9295 // MaxMemDepDistance let us stop alias-checking at i3 and we add 9296 // dependencies from i0 to i3,i4,.. (even if they are not aliased). 9297 // Previously we already added dependencies from i3 to i6,i7,i8 9298 // (because of MaxMemDepDistance). As we added a dependency from 9299 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8 9300 // and we can abort this loop at i6. 9301 if (DistToSrc >= 2 * MaxMemDepDistance) 9302 break; 9303 DistToSrc++; 9304 } 9305 } 9306 if (InsertInReadyList && SD->isReady()) { 9307 ReadyInsts.insert(SD); 9308 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst 9309 << "\n"); 9310 } 9311 } 9312 } 9313 9314 void BoUpSLP::BlockScheduling::resetSchedule() { 9315 assert(ScheduleStart && 9316 "tried to reset schedule on block which has not been scheduled"); 9317 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 9318 doForAllOpcodes(I, [&](ScheduleData *SD) { 9319 assert(isInSchedulingRegion(SD) && 9320 "ScheduleData not in scheduling region"); 9321 SD->IsScheduled = false; 9322 SD->resetUnscheduledDeps(); 9323 }); 9324 } 9325 ReadyInsts.clear(); 9326 } 9327 9328 void BoUpSLP::scheduleBlock(BlockScheduling *BS) { 9329 if (!BS->ScheduleStart) 9330 return; 9331 9332 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n"); 9333 9334 // A key point - if we got here, pre-scheduling was able to find a valid 9335 // scheduling of the sub-graph of the scheduling window which consists 9336 // of all vector bundles and their transitive users. As such, we do not 9337 // need to reschedule anything *outside of* that subgraph. 9338 9339 BS->resetSchedule(); 9340 9341 // For the real scheduling we use a more sophisticated ready-list: it is 9342 // sorted by the original instruction location. This lets the final schedule 9343 // be as close as possible to the original instruction order. 9344 // WARNING: If changing this order causes a correctness issue, that means 9345 // there is some missing dependence edge in the schedule data graph. 9346 struct ScheduleDataCompare { 9347 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const { 9348 return SD2->SchedulingPriority < SD1->SchedulingPriority; 9349 } 9350 }; 9351 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts; 9352 9353 // Ensure that all dependency data is updated (for nodes in the sub-graph) 9354 // and fill the ready-list with initial instructions. 9355 int Idx = 0; 9356 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; 9357 I = I->getNextNode()) { 9358 BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) { 9359 TreeEntry *SDTE = getTreeEntry(SD->Inst); 9360 (void)SDTE; 9361 assert((isVectorLikeInstWithConstOps(SD->Inst) || 9362 SD->isPartOfBundle() == 9363 (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) && 9364 "scheduler and vectorizer bundle mismatch"); 9365 SD->FirstInBundle->SchedulingPriority = Idx++; 9366 9367 if (SD->isSchedulingEntity() && SD->isPartOfBundle()) 9368 BS->calculateDependencies(SD, false, this); 9369 }); 9370 } 9371 BS->initialFillReadyList(ReadyInsts); 9372 9373 Instruction *LastScheduledInst = BS->ScheduleEnd; 9374 9375 // Do the "real" scheduling. 9376 while (!ReadyInsts.empty()) { 9377 ScheduleData *picked = *ReadyInsts.begin(); 9378 ReadyInsts.erase(ReadyInsts.begin()); 9379 9380 // Move the scheduled instruction(s) to their dedicated places, if not 9381 // there yet. 9382 for (ScheduleData *BundleMember = picked; BundleMember; 9383 BundleMember = BundleMember->NextInBundle) { 9384 Instruction *pickedInst = BundleMember->Inst; 9385 if (pickedInst->getNextNode() != LastScheduledInst) 9386 pickedInst->moveBefore(LastScheduledInst); 9387 LastScheduledInst = pickedInst; 9388 } 9389 9390 BS->schedule(picked, ReadyInsts); 9391 } 9392 9393 // Check that we didn't break any of our invariants. 9394 #ifdef EXPENSIVE_CHECKS 9395 BS->verify(); 9396 #endif 9397 9398 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS) 9399 // Check that all schedulable entities got scheduled 9400 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) { 9401 BS->doForAllOpcodes(I, [&](ScheduleData *SD) { 9402 if (SD->isSchedulingEntity() && SD->hasValidDependencies()) { 9403 assert(SD->IsScheduled && "must be scheduled at this point"); 9404 } 9405 }); 9406 } 9407 #endif 9408 9409 // Avoid duplicate scheduling of the block. 9410 BS->ScheduleStart = nullptr; 9411 } 9412 9413 unsigned BoUpSLP::getVectorElementSize(Value *V) { 9414 // If V is a store, just return the width of the stored value (or value 9415 // truncated just before storing) without traversing the expression tree. 9416 // This is the common case. 9417 if (auto *Store = dyn_cast<StoreInst>(V)) 9418 return DL->getTypeSizeInBits(Store->getValueOperand()->getType()); 9419 9420 if (auto *IEI = dyn_cast<InsertElementInst>(V)) 9421 return getVectorElementSize(IEI->getOperand(1)); 9422 9423 auto E = InstrElementSize.find(V); 9424 if (E != InstrElementSize.end()) 9425 return E->second; 9426 9427 // If V is not a store, we can traverse the expression tree to find loads 9428 // that feed it. The type of the loaded value may indicate a more suitable 9429 // width than V's type. We want to base the vector element size on the width 9430 // of memory operations where possible. 9431 SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist; 9432 SmallPtrSet<Instruction *, 16> Visited; 9433 if (auto *I = dyn_cast<Instruction>(V)) { 9434 Worklist.emplace_back(I, I->getParent()); 9435 Visited.insert(I); 9436 } 9437 9438 // Traverse the expression tree in bottom-up order looking for loads. If we 9439 // encounter an instruction we don't yet handle, we give up. 9440 auto Width = 0u; 9441 while (!Worklist.empty()) { 9442 Instruction *I; 9443 BasicBlock *Parent; 9444 std::tie(I, Parent) = Worklist.pop_back_val(); 9445 9446 // We should only be looking at scalar instructions here. If the current 9447 // instruction has a vector type, skip. 9448 auto *Ty = I->getType(); 9449 if (isa<VectorType>(Ty)) 9450 continue; 9451 9452 // If the current instruction is a load, update MaxWidth to reflect the 9453 // width of the loaded value. 9454 if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) || 9455 isa<ExtractValueInst>(I)) 9456 Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty)); 9457 9458 // Otherwise, we need to visit the operands of the instruction. We only 9459 // handle the interesting cases from buildTree here. If an operand is an 9460 // instruction we haven't yet visited and from the same basic block as the 9461 // user or the use is a PHI node, we add it to the worklist. 9462 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 9463 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) || 9464 isa<UnaryOperator>(I)) { 9465 for (Use &U : I->operands()) 9466 if (auto *J = dyn_cast<Instruction>(U.get())) 9467 if (Visited.insert(J).second && 9468 (isa<PHINode>(I) || J->getParent() == Parent)) 9469 Worklist.emplace_back(J, J->getParent()); 9470 } else { 9471 break; 9472 } 9473 } 9474 9475 // If we didn't encounter a memory access in the expression tree, or if we 9476 // gave up for some reason, just return the width of V. Otherwise, return the 9477 // maximum width we found. 9478 if (!Width) { 9479 if (auto *CI = dyn_cast<CmpInst>(V)) 9480 V = CI->getOperand(0); 9481 Width = DL->getTypeSizeInBits(V->getType()); 9482 } 9483 9484 for (Instruction *I : Visited) 9485 InstrElementSize[I] = Width; 9486 9487 return Width; 9488 } 9489 9490 // Determine if a value V in a vectorizable expression Expr can be demoted to a 9491 // smaller type with a truncation. We collect the values that will be demoted 9492 // in ToDemote and additional roots that require investigating in Roots. 9493 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr, 9494 SmallVectorImpl<Value *> &ToDemote, 9495 SmallVectorImpl<Value *> &Roots) { 9496 // We can always demote constants. 9497 if (isa<Constant>(V)) { 9498 ToDemote.push_back(V); 9499 return true; 9500 } 9501 9502 // If the value is not an instruction in the expression with only one use, it 9503 // cannot be demoted. 9504 auto *I = dyn_cast<Instruction>(V); 9505 if (!I || !I->hasOneUse() || !Expr.count(I)) 9506 return false; 9507 9508 switch (I->getOpcode()) { 9509 9510 // We can always demote truncations and extensions. Since truncations can 9511 // seed additional demotion, we save the truncated value. 9512 case Instruction::Trunc: 9513 Roots.push_back(I->getOperand(0)); 9514 break; 9515 case Instruction::ZExt: 9516 case Instruction::SExt: 9517 if (isa<ExtractElementInst>(I->getOperand(0)) || 9518 isa<InsertElementInst>(I->getOperand(0))) 9519 return false; 9520 break; 9521 9522 // We can demote certain binary operations if we can demote both of their 9523 // operands. 9524 case Instruction::Add: 9525 case Instruction::Sub: 9526 case Instruction::Mul: 9527 case Instruction::And: 9528 case Instruction::Or: 9529 case Instruction::Xor: 9530 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) || 9531 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots)) 9532 return false; 9533 break; 9534 9535 // We can demote selects if we can demote their true and false values. 9536 case Instruction::Select: { 9537 SelectInst *SI = cast<SelectInst>(I); 9538 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) || 9539 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots)) 9540 return false; 9541 break; 9542 } 9543 9544 // We can demote phis if we can demote all their incoming operands. Note that 9545 // we don't need to worry about cycles since we ensure single use above. 9546 case Instruction::PHI: { 9547 PHINode *PN = cast<PHINode>(I); 9548 for (Value *IncValue : PN->incoming_values()) 9549 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots)) 9550 return false; 9551 break; 9552 } 9553 9554 // Otherwise, conservatively give up. 9555 default: 9556 return false; 9557 } 9558 9559 // Record the value that we can demote. 9560 ToDemote.push_back(V); 9561 return true; 9562 } 9563 9564 void BoUpSLP::computeMinimumValueSizes() { 9565 // If there are no external uses, the expression tree must be rooted by a 9566 // store. We can't demote in-memory values, so there is nothing to do here. 9567 if (ExternalUses.empty()) 9568 return; 9569 9570 // We only attempt to truncate integer expressions. 9571 auto &TreeRoot = VectorizableTree[0]->Scalars; 9572 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType()); 9573 if (!TreeRootIT) 9574 return; 9575 9576 // If the expression is not rooted by a store, these roots should have 9577 // external uses. We will rely on InstCombine to rewrite the expression in 9578 // the narrower type. However, InstCombine only rewrites single-use values. 9579 // This means that if a tree entry other than a root is used externally, it 9580 // must have multiple uses and InstCombine will not rewrite it. The code 9581 // below ensures that only the roots are used externally. 9582 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end()); 9583 for (auto &EU : ExternalUses) 9584 if (!Expr.erase(EU.Scalar)) 9585 return; 9586 if (!Expr.empty()) 9587 return; 9588 9589 // Collect the scalar values of the vectorizable expression. We will use this 9590 // context to determine which values can be demoted. If we see a truncation, 9591 // we mark it as seeding another demotion. 9592 for (auto &EntryPtr : VectorizableTree) 9593 Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end()); 9594 9595 // Ensure the roots of the vectorizable tree don't form a cycle. They must 9596 // have a single external user that is not in the vectorizable tree. 9597 for (auto *Root : TreeRoot) 9598 if (!Root->hasOneUse() || Expr.count(*Root->user_begin())) 9599 return; 9600 9601 // Conservatively determine if we can actually truncate the roots of the 9602 // expression. Collect the values that can be demoted in ToDemote and 9603 // additional roots that require investigating in Roots. 9604 SmallVector<Value *, 32> ToDemote; 9605 SmallVector<Value *, 4> Roots; 9606 for (auto *Root : TreeRoot) 9607 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots)) 9608 return; 9609 9610 // The maximum bit width required to represent all the values that can be 9611 // demoted without loss of precision. It would be safe to truncate the roots 9612 // of the expression to this width. 9613 auto MaxBitWidth = 8u; 9614 9615 // We first check if all the bits of the roots are demanded. If they're not, 9616 // we can truncate the roots to this narrower type. 9617 for (auto *Root : TreeRoot) { 9618 auto Mask = DB->getDemandedBits(cast<Instruction>(Root)); 9619 MaxBitWidth = std::max<unsigned>( 9620 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth); 9621 } 9622 9623 // True if the roots can be zero-extended back to their original type, rather 9624 // than sign-extended. We know that if the leading bits are not demanded, we 9625 // can safely zero-extend. So we initialize IsKnownPositive to True. 9626 bool IsKnownPositive = true; 9627 9628 // If all the bits of the roots are demanded, we can try a little harder to 9629 // compute a narrower type. This can happen, for example, if the roots are 9630 // getelementptr indices. InstCombine promotes these indices to the pointer 9631 // width. Thus, all their bits are technically demanded even though the 9632 // address computation might be vectorized in a smaller type. 9633 // 9634 // We start by looking at each entry that can be demoted. We compute the 9635 // maximum bit width required to store the scalar by using ValueTracking to 9636 // compute the number of high-order bits we can truncate. 9637 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) && 9638 llvm::all_of(TreeRoot, [](Value *R) { 9639 assert(R->hasOneUse() && "Root should have only one use!"); 9640 return isa<GetElementPtrInst>(R->user_back()); 9641 })) { 9642 MaxBitWidth = 8u; 9643 9644 // Determine if the sign bit of all the roots is known to be zero. If not, 9645 // IsKnownPositive is set to False. 9646 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) { 9647 KnownBits Known = computeKnownBits(R, *DL); 9648 return Known.isNonNegative(); 9649 }); 9650 9651 // Determine the maximum number of bits required to store the scalar 9652 // values. 9653 for (auto *Scalar : ToDemote) { 9654 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT); 9655 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType()); 9656 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth); 9657 } 9658 9659 // If we can't prove that the sign bit is zero, we must add one to the 9660 // maximum bit width to account for the unknown sign bit. This preserves 9661 // the existing sign bit so we can safely sign-extend the root back to the 9662 // original type. Otherwise, if we know the sign bit is zero, we will 9663 // zero-extend the root instead. 9664 // 9665 // FIXME: This is somewhat suboptimal, as there will be cases where adding 9666 // one to the maximum bit width will yield a larger-than-necessary 9667 // type. In general, we need to add an extra bit only if we can't 9668 // prove that the upper bit of the original type is equal to the 9669 // upper bit of the proposed smaller type. If these two bits are the 9670 // same (either zero or one) we know that sign-extending from the 9671 // smaller type will result in the same value. Here, since we can't 9672 // yet prove this, we are just making the proposed smaller type 9673 // larger to ensure correctness. 9674 if (!IsKnownPositive) 9675 ++MaxBitWidth; 9676 } 9677 9678 // Round MaxBitWidth up to the next power-of-two. 9679 if (!isPowerOf2_64(MaxBitWidth)) 9680 MaxBitWidth = NextPowerOf2(MaxBitWidth); 9681 9682 // If the maximum bit width we compute is less than the with of the roots' 9683 // type, we can proceed with the narrowing. Otherwise, do nothing. 9684 if (MaxBitWidth >= TreeRootIT->getBitWidth()) 9685 return; 9686 9687 // If we can truncate the root, we must collect additional values that might 9688 // be demoted as a result. That is, those seeded by truncations we will 9689 // modify. 9690 while (!Roots.empty()) 9691 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots); 9692 9693 // Finally, map the values we can demote to the maximum bit with we computed. 9694 for (auto *Scalar : ToDemote) 9695 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive); 9696 } 9697 9698 namespace { 9699 9700 /// The SLPVectorizer Pass. 9701 struct SLPVectorizer : public FunctionPass { 9702 SLPVectorizerPass Impl; 9703 9704 /// Pass identification, replacement for typeid 9705 static char ID; 9706 9707 explicit SLPVectorizer() : FunctionPass(ID) { 9708 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); 9709 } 9710 9711 bool doInitialization(Module &M) override { return false; } 9712 9713 bool runOnFunction(Function &F) override { 9714 if (skipFunction(F)) 9715 return false; 9716 9717 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 9718 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 9719 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 9720 auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr; 9721 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 9722 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 9723 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 9724 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 9725 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); 9726 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 9727 9728 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 9729 } 9730 9731 void getAnalysisUsage(AnalysisUsage &AU) const override { 9732 FunctionPass::getAnalysisUsage(AU); 9733 AU.addRequired<AssumptionCacheTracker>(); 9734 AU.addRequired<ScalarEvolutionWrapperPass>(); 9735 AU.addRequired<AAResultsWrapperPass>(); 9736 AU.addRequired<TargetTransformInfoWrapperPass>(); 9737 AU.addRequired<LoopInfoWrapperPass>(); 9738 AU.addRequired<DominatorTreeWrapperPass>(); 9739 AU.addRequired<DemandedBitsWrapperPass>(); 9740 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 9741 AU.addRequired<InjectTLIMappingsLegacy>(); 9742 AU.addPreserved<LoopInfoWrapperPass>(); 9743 AU.addPreserved<DominatorTreeWrapperPass>(); 9744 AU.addPreserved<AAResultsWrapperPass>(); 9745 AU.addPreserved<GlobalsAAWrapperPass>(); 9746 AU.setPreservesCFG(); 9747 } 9748 }; 9749 9750 } // end anonymous namespace 9751 9752 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) { 9753 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 9754 auto *TTI = &AM.getResult<TargetIRAnalysis>(F); 9755 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F); 9756 auto *AA = &AM.getResult<AAManager>(F); 9757 auto *LI = &AM.getResult<LoopAnalysis>(F); 9758 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 9759 auto *AC = &AM.getResult<AssumptionAnalysis>(F); 9760 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F); 9761 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 9762 9763 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 9764 if (!Changed) 9765 return PreservedAnalyses::all(); 9766 9767 PreservedAnalyses PA; 9768 PA.preserveSet<CFGAnalyses>(); 9769 return PA; 9770 } 9771 9772 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_, 9773 TargetTransformInfo *TTI_, 9774 TargetLibraryInfo *TLI_, AAResults *AA_, 9775 LoopInfo *LI_, DominatorTree *DT_, 9776 AssumptionCache *AC_, DemandedBits *DB_, 9777 OptimizationRemarkEmitter *ORE_) { 9778 if (!RunSLPVectorization) 9779 return false; 9780 SE = SE_; 9781 TTI = TTI_; 9782 TLI = TLI_; 9783 AA = AA_; 9784 LI = LI_; 9785 DT = DT_; 9786 AC = AC_; 9787 DB = DB_; 9788 DL = &F.getParent()->getDataLayout(); 9789 9790 Stores.clear(); 9791 GEPs.clear(); 9792 bool Changed = false; 9793 9794 // If the target claims to have no vector registers don't attempt 9795 // vectorization. 9796 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) { 9797 LLVM_DEBUG( 9798 dbgs() << "SLP: Didn't find any vector registers for target, abort.\n"); 9799 return false; 9800 } 9801 9802 // Don't vectorize when the attribute NoImplicitFloat is used. 9803 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) 9804 return false; 9805 9806 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"); 9807 9808 // Use the bottom up slp vectorizer to construct chains that start with 9809 // store instructions. 9810 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_); 9811 9812 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to 9813 // delete instructions. 9814 9815 // Update DFS numbers now so that we can use them for ordering. 9816 DT->updateDFSNumbers(); 9817 9818 // Scan the blocks in the function in post order. 9819 for (auto BB : post_order(&F.getEntryBlock())) { 9820 // Start new block - clear the list of reduction roots. 9821 R.clearReductionData(); 9822 collectSeedInstructions(BB); 9823 9824 // Vectorize trees that end at stores. 9825 if (!Stores.empty()) { 9826 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size() 9827 << " underlying objects.\n"); 9828 Changed |= vectorizeStoreChains(R); 9829 } 9830 9831 // Vectorize trees that end at reductions. 9832 Changed |= vectorizeChainsInBlock(BB, R); 9833 9834 // Vectorize the index computations of getelementptr instructions. This 9835 // is primarily intended to catch gather-like idioms ending at 9836 // non-consecutive loads. 9837 if (!GEPs.empty()) { 9838 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size() 9839 << " underlying objects.\n"); 9840 Changed |= vectorizeGEPIndices(BB, R); 9841 } 9842 } 9843 9844 if (Changed) { 9845 R.optimizeGatherSequence(); 9846 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n"); 9847 } 9848 return Changed; 9849 } 9850 9851 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R, 9852 unsigned Idx, unsigned MinVF) { 9853 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size() 9854 << "\n"); 9855 const unsigned Sz = R.getVectorElementSize(Chain[0]); 9856 unsigned VF = Chain.size(); 9857 9858 if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF) 9859 return false; 9860 9861 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx 9862 << "\n"); 9863 9864 R.buildTree(Chain); 9865 if (R.isTreeTinyAndNotFullyVectorizable()) 9866 return false; 9867 if (R.isLoadCombineCandidate()) 9868 return false; 9869 R.reorderTopToBottom(); 9870 R.reorderBottomToTop(); 9871 R.buildExternalUses(); 9872 9873 R.computeMinimumValueSizes(); 9874 9875 InstructionCost Cost = R.getTreeCost(); 9876 9877 LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n"); 9878 if (Cost < -SLPCostThreshold) { 9879 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n"); 9880 9881 using namespace ore; 9882 9883 R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized", 9884 cast<StoreInst>(Chain[0])) 9885 << "Stores SLP vectorized with cost " << NV("Cost", Cost) 9886 << " and with tree size " 9887 << NV("TreeSize", R.getTreeSize())); 9888 9889 R.vectorizeTree(); 9890 return true; 9891 } 9892 9893 return false; 9894 } 9895 9896 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores, 9897 BoUpSLP &R) { 9898 // We may run into multiple chains that merge into a single chain. We mark the 9899 // stores that we vectorized so that we don't visit the same store twice. 9900 BoUpSLP::ValueSet VectorizedStores; 9901 bool Changed = false; 9902 9903 int E = Stores.size(); 9904 SmallBitVector Tails(E, false); 9905 int MaxIter = MaxStoreLookup.getValue(); 9906 SmallVector<std::pair<int, int>, 16> ConsecutiveChain( 9907 E, std::make_pair(E, INT_MAX)); 9908 SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false)); 9909 int IterCnt; 9910 auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter, 9911 &CheckedPairs, 9912 &ConsecutiveChain](int K, int Idx) { 9913 if (IterCnt >= MaxIter) 9914 return true; 9915 if (CheckedPairs[Idx].test(K)) 9916 return ConsecutiveChain[K].second == 1 && 9917 ConsecutiveChain[K].first == Idx; 9918 ++IterCnt; 9919 CheckedPairs[Idx].set(K); 9920 CheckedPairs[K].set(Idx); 9921 Optional<int> Diff = getPointersDiff( 9922 Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(), 9923 Stores[Idx]->getValueOperand()->getType(), 9924 Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true); 9925 if (!Diff || *Diff == 0) 9926 return false; 9927 int Val = *Diff; 9928 if (Val < 0) { 9929 if (ConsecutiveChain[Idx].second > -Val) { 9930 Tails.set(K); 9931 ConsecutiveChain[Idx] = std::make_pair(K, -Val); 9932 } 9933 return false; 9934 } 9935 if (ConsecutiveChain[K].second <= Val) 9936 return false; 9937 9938 Tails.set(Idx); 9939 ConsecutiveChain[K] = std::make_pair(Idx, Val); 9940 return Val == 1; 9941 }; 9942 // Do a quadratic search on all of the given stores in reverse order and find 9943 // all of the pairs of stores that follow each other. 9944 for (int Idx = E - 1; Idx >= 0; --Idx) { 9945 // If a store has multiple consecutive store candidates, search according 9946 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ... 9947 // This is because usually pairing with immediate succeeding or preceding 9948 // candidate create the best chance to find slp vectorization opportunity. 9949 const int MaxLookDepth = std::max(E - Idx, Idx + 1); 9950 IterCnt = 0; 9951 for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset) 9952 if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) || 9953 (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx))) 9954 break; 9955 } 9956 9957 // Tracks if we tried to vectorize stores starting from the given tail 9958 // already. 9959 SmallBitVector TriedTails(E, false); 9960 // For stores that start but don't end a link in the chain: 9961 for (int Cnt = E; Cnt > 0; --Cnt) { 9962 int I = Cnt - 1; 9963 if (ConsecutiveChain[I].first == E || Tails.test(I)) 9964 continue; 9965 // We found a store instr that starts a chain. Now follow the chain and try 9966 // to vectorize it. 9967 BoUpSLP::ValueList Operands; 9968 // Collect the chain into a list. 9969 while (I != E && !VectorizedStores.count(Stores[I])) { 9970 Operands.push_back(Stores[I]); 9971 Tails.set(I); 9972 if (ConsecutiveChain[I].second != 1) { 9973 // Mark the new end in the chain and go back, if required. It might be 9974 // required if the original stores come in reversed order, for example. 9975 if (ConsecutiveChain[I].first != E && 9976 Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) && 9977 !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) { 9978 TriedTails.set(I); 9979 Tails.reset(ConsecutiveChain[I].first); 9980 if (Cnt < ConsecutiveChain[I].first + 2) 9981 Cnt = ConsecutiveChain[I].first + 2; 9982 } 9983 break; 9984 } 9985 // Move to the next value in the chain. 9986 I = ConsecutiveChain[I].first; 9987 } 9988 assert(!Operands.empty() && "Expected non-empty list of stores."); 9989 9990 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 9991 unsigned EltSize = R.getVectorElementSize(Operands[0]); 9992 unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize); 9993 9994 unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store), 9995 MaxElts); 9996 auto *Store = cast<StoreInst>(Operands[0]); 9997 Type *StoreTy = Store->getValueOperand()->getType(); 9998 Type *ValueTy = StoreTy; 9999 if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand())) 10000 ValueTy = Trunc->getSrcTy(); 10001 unsigned MinVF = TTI->getStoreMinimumVF( 10002 R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy); 10003 10004 // FIXME: Is division-by-2 the correct step? Should we assert that the 10005 // register size is a power-of-2? 10006 unsigned StartIdx = 0; 10007 for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) { 10008 for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) { 10009 ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size); 10010 if (!VectorizedStores.count(Slice.front()) && 10011 !VectorizedStores.count(Slice.back()) && 10012 vectorizeStoreChain(Slice, R, Cnt, MinVF)) { 10013 // Mark the vectorized stores so that we don't vectorize them again. 10014 VectorizedStores.insert(Slice.begin(), Slice.end()); 10015 Changed = true; 10016 // If we vectorized initial block, no need to try to vectorize it 10017 // again. 10018 if (Cnt == StartIdx) 10019 StartIdx += Size; 10020 Cnt += Size; 10021 continue; 10022 } 10023 ++Cnt; 10024 } 10025 // Check if the whole array was vectorized already - exit. 10026 if (StartIdx >= Operands.size()) 10027 break; 10028 } 10029 } 10030 10031 return Changed; 10032 } 10033 10034 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) { 10035 // Initialize the collections. We will make a single pass over the block. 10036 Stores.clear(); 10037 GEPs.clear(); 10038 10039 // Visit the store and getelementptr instructions in BB and organize them in 10040 // Stores and GEPs according to the underlying objects of their pointer 10041 // operands. 10042 for (Instruction &I : *BB) { 10043 // Ignore store instructions that are volatile or have a pointer operand 10044 // that doesn't point to a scalar type. 10045 if (auto *SI = dyn_cast<StoreInst>(&I)) { 10046 if (!SI->isSimple()) 10047 continue; 10048 if (!isValidElementType(SI->getValueOperand()->getType())) 10049 continue; 10050 Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI); 10051 } 10052 10053 // Ignore getelementptr instructions that have more than one index, a 10054 // constant index, or a pointer operand that doesn't point to a scalar 10055 // type. 10056 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 10057 auto Idx = GEP->idx_begin()->get(); 10058 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx)) 10059 continue; 10060 if (!isValidElementType(Idx->getType())) 10061 continue; 10062 if (GEP->getType()->isVectorTy()) 10063 continue; 10064 GEPs[GEP->getPointerOperand()].push_back(GEP); 10065 } 10066 } 10067 } 10068 10069 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { 10070 if (!A || !B) 10071 return false; 10072 if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B)) 10073 return false; 10074 Value *VL[] = {A, B}; 10075 return tryToVectorizeList(VL, R); 10076 } 10077 10078 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, 10079 bool LimitForRegisterSize) { 10080 if (VL.size() < 2) 10081 return false; 10082 10083 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " 10084 << VL.size() << ".\n"); 10085 10086 // Check that all of the parts are instructions of the same type, 10087 // we permit an alternate opcode via InstructionsState. 10088 InstructionsState S = getSameOpcode(VL); 10089 if (!S.getOpcode()) 10090 return false; 10091 10092 Instruction *I0 = cast<Instruction>(S.OpValue); 10093 // Make sure invalid types (including vector type) are rejected before 10094 // determining vectorization factor for scalar instructions. 10095 for (Value *V : VL) { 10096 Type *Ty = V->getType(); 10097 if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) { 10098 // NOTE: the following will give user internal llvm type name, which may 10099 // not be useful. 10100 R.getORE()->emit([&]() { 10101 std::string type_str; 10102 llvm::raw_string_ostream rso(type_str); 10103 Ty->print(rso); 10104 return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0) 10105 << "Cannot SLP vectorize list: type " 10106 << rso.str() + " is unsupported by vectorizer"; 10107 }); 10108 return false; 10109 } 10110 } 10111 10112 unsigned Sz = R.getVectorElementSize(I0); 10113 unsigned MinVF = R.getMinVF(Sz); 10114 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF); 10115 MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF); 10116 if (MaxVF < 2) { 10117 R.getORE()->emit([&]() { 10118 return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0) 10119 << "Cannot SLP vectorize list: vectorization factor " 10120 << "less than 2 is not supported"; 10121 }); 10122 return false; 10123 } 10124 10125 bool Changed = false; 10126 bool CandidateFound = false; 10127 InstructionCost MinCost = SLPCostThreshold.getValue(); 10128 Type *ScalarTy = VL[0]->getType(); 10129 if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 10130 ScalarTy = IE->getOperand(1)->getType(); 10131 10132 unsigned NextInst = 0, MaxInst = VL.size(); 10133 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) { 10134 // No actual vectorization should happen, if number of parts is the same as 10135 // provided vectorization factor (i.e. the scalar type is used for vector 10136 // code during codegen). 10137 auto *VecTy = FixedVectorType::get(ScalarTy, VF); 10138 if (TTI->getNumberOfParts(VecTy) == VF) 10139 continue; 10140 for (unsigned I = NextInst; I < MaxInst; ++I) { 10141 unsigned OpsWidth = 0; 10142 10143 if (I + VF > MaxInst) 10144 OpsWidth = MaxInst - I; 10145 else 10146 OpsWidth = VF; 10147 10148 if (!isPowerOf2_32(OpsWidth)) 10149 continue; 10150 10151 if ((LimitForRegisterSize && OpsWidth < MaxVF) || 10152 (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2)) 10153 break; 10154 10155 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth); 10156 // Check that a previous iteration of this loop did not delete the Value. 10157 if (llvm::any_of(Ops, [&R](Value *V) { 10158 auto *I = dyn_cast<Instruction>(V); 10159 return I && R.isDeleted(I); 10160 })) 10161 continue; 10162 10163 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " 10164 << "\n"); 10165 10166 R.buildTree(Ops); 10167 if (R.isTreeTinyAndNotFullyVectorizable()) 10168 continue; 10169 R.reorderTopToBottom(); 10170 R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front())); 10171 R.buildExternalUses(); 10172 10173 R.computeMinimumValueSizes(); 10174 InstructionCost Cost = R.getTreeCost(); 10175 CandidateFound = true; 10176 MinCost = std::min(MinCost, Cost); 10177 10178 if (Cost < -SLPCostThreshold) { 10179 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n"); 10180 R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList", 10181 cast<Instruction>(Ops[0])) 10182 << "SLP vectorized with cost " << ore::NV("Cost", Cost) 10183 << " and with tree size " 10184 << ore::NV("TreeSize", R.getTreeSize())); 10185 10186 R.vectorizeTree(); 10187 // Move to the next bundle. 10188 I += VF - 1; 10189 NextInst = I + 1; 10190 Changed = true; 10191 } 10192 } 10193 } 10194 10195 if (!Changed && CandidateFound) { 10196 R.getORE()->emit([&]() { 10197 return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0) 10198 << "List vectorization was possible but not beneficial with cost " 10199 << ore::NV("Cost", MinCost) << " >= " 10200 << ore::NV("Treshold", -SLPCostThreshold); 10201 }); 10202 } else if (!Changed) { 10203 R.getORE()->emit([&]() { 10204 return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0) 10205 << "Cannot SLP vectorize list: vectorization was impossible" 10206 << " with available vectorization factors"; 10207 }); 10208 } 10209 return Changed; 10210 } 10211 10212 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) { 10213 if (!I) 10214 return false; 10215 10216 if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) || 10217 isa<VectorType>(I->getType())) 10218 return false; 10219 10220 Value *P = I->getParent(); 10221 10222 // Vectorize in current basic block only. 10223 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0)); 10224 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1)); 10225 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P) 10226 return false; 10227 10228 // First collect all possible candidates 10229 SmallVector<std::pair<Value *, Value *>, 4> Candidates; 10230 Candidates.emplace_back(Op0, Op1); 10231 10232 auto *A = dyn_cast<BinaryOperator>(Op0); 10233 auto *B = dyn_cast<BinaryOperator>(Op1); 10234 // Try to skip B. 10235 if (A && B && B->hasOneUse()) { 10236 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); 10237 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); 10238 if (B0 && B0->getParent() == P) 10239 Candidates.emplace_back(A, B0); 10240 if (B1 && B1->getParent() == P) 10241 Candidates.emplace_back(A, B1); 10242 } 10243 // Try to skip A. 10244 if (B && A && A->hasOneUse()) { 10245 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); 10246 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); 10247 if (A0 && A0->getParent() == P) 10248 Candidates.emplace_back(A0, B); 10249 if (A1 && A1->getParent() == P) 10250 Candidates.emplace_back(A1, B); 10251 } 10252 10253 if (Candidates.size() == 1) 10254 return tryToVectorizePair(Op0, Op1, R); 10255 10256 // We have multiple options. Try to pick the single best. 10257 Optional<int> BestCandidate = R.findBestRootPair(Candidates); 10258 if (!BestCandidate) 10259 return false; 10260 return tryToVectorizePair(Candidates[*BestCandidate].first, 10261 Candidates[*BestCandidate].second, R); 10262 } 10263 10264 namespace { 10265 10266 /// Model horizontal reductions. 10267 /// 10268 /// A horizontal reduction is a tree of reduction instructions that has values 10269 /// that can be put into a vector as its leaves. For example: 10270 /// 10271 /// mul mul mul mul 10272 /// \ / \ / 10273 /// + + 10274 /// \ / 10275 /// + 10276 /// This tree has "mul" as its leaf values and "+" as its reduction 10277 /// instructions. A reduction can feed into a store or a binary operation 10278 /// feeding a phi. 10279 /// ... 10280 /// \ / 10281 /// + 10282 /// | 10283 /// phi += 10284 /// 10285 /// Or: 10286 /// ... 10287 /// \ / 10288 /// + 10289 /// | 10290 /// *p = 10291 /// 10292 class HorizontalReduction { 10293 using ReductionOpsType = SmallVector<Value *, 16>; 10294 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>; 10295 ReductionOpsListType ReductionOps; 10296 /// List of possibly reduced values. 10297 SmallVector<SmallVector<Value *>> ReducedVals; 10298 /// Maps reduced value to the corresponding reduction operation. 10299 DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps; 10300 // Use map vector to make stable output. 10301 MapVector<Instruction *, Value *> ExtraArgs; 10302 WeakTrackingVH ReductionRoot; 10303 /// The type of reduction operation. 10304 RecurKind RdxKind; 10305 10306 static bool isCmpSelMinMax(Instruction *I) { 10307 return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) && 10308 RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I)); 10309 } 10310 10311 // And/or are potentially poison-safe logical patterns like: 10312 // select x, y, false 10313 // select x, true, y 10314 static bool isBoolLogicOp(Instruction *I) { 10315 return match(I, m_LogicalAnd(m_Value(), m_Value())) || 10316 match(I, m_LogicalOr(m_Value(), m_Value())); 10317 } 10318 10319 /// Checks if instruction is associative and can be vectorized. 10320 static bool isVectorizable(RecurKind Kind, Instruction *I) { 10321 if (Kind == RecurKind::None) 10322 return false; 10323 10324 // Integer ops that map to select instructions or intrinsics are fine. 10325 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) || 10326 isBoolLogicOp(I)) 10327 return true; 10328 10329 if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) { 10330 // FP min/max are associative except for NaN and -0.0. We do not 10331 // have to rule out -0.0 here because the intrinsic semantics do not 10332 // specify a fixed result for it. 10333 return I->getFastMathFlags().noNaNs(); 10334 } 10335 10336 return I->isAssociative(); 10337 } 10338 10339 static Value *getRdxOperand(Instruction *I, unsigned Index) { 10340 // Poison-safe 'or' takes the form: select X, true, Y 10341 // To make that work with the normal operand processing, we skip the 10342 // true value operand. 10343 // TODO: Change the code and data structures to handle this without a hack. 10344 if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1) 10345 return I->getOperand(2); 10346 return I->getOperand(Index); 10347 } 10348 10349 /// Creates reduction operation with the current opcode. 10350 static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS, 10351 Value *RHS, const Twine &Name, bool UseSelect) { 10352 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind); 10353 switch (Kind) { 10354 case RecurKind::Or: 10355 if (UseSelect && 10356 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 10357 return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name); 10358 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 10359 Name); 10360 case RecurKind::And: 10361 if (UseSelect && 10362 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 10363 return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name); 10364 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 10365 Name); 10366 case RecurKind::Add: 10367 case RecurKind::Mul: 10368 case RecurKind::Xor: 10369 case RecurKind::FAdd: 10370 case RecurKind::FMul: 10371 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 10372 Name); 10373 case RecurKind::FMax: 10374 return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS); 10375 case RecurKind::FMin: 10376 return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS); 10377 case RecurKind::SMax: 10378 if (UseSelect) { 10379 Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name); 10380 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 10381 } 10382 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS); 10383 case RecurKind::SMin: 10384 if (UseSelect) { 10385 Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name); 10386 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 10387 } 10388 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS); 10389 case RecurKind::UMax: 10390 if (UseSelect) { 10391 Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name); 10392 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 10393 } 10394 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS); 10395 case RecurKind::UMin: 10396 if (UseSelect) { 10397 Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name); 10398 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 10399 } 10400 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS); 10401 default: 10402 llvm_unreachable("Unknown reduction operation."); 10403 } 10404 } 10405 10406 /// Creates reduction operation with the current opcode with the IR flags 10407 /// from \p ReductionOps, dropping nuw/nsw flags. 10408 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 10409 Value *RHS, const Twine &Name, 10410 const ReductionOpsListType &ReductionOps) { 10411 bool UseSelect = ReductionOps.size() == 2 || 10412 // Logical or/and. 10413 (ReductionOps.size() == 1 && 10414 isa<SelectInst>(ReductionOps.front().front())); 10415 assert((!UseSelect || ReductionOps.size() != 2 || 10416 isa<SelectInst>(ReductionOps[1][0])) && 10417 "Expected cmp + select pairs for reduction"); 10418 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect); 10419 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 10420 if (auto *Sel = dyn_cast<SelectInst>(Op)) { 10421 propagateIRFlags(Sel->getCondition(), ReductionOps[0], nullptr, 10422 /*IncludeWrapFlags=*/false); 10423 propagateIRFlags(Op, ReductionOps[1], nullptr, 10424 /*IncludeWrapFlags=*/false); 10425 return Op; 10426 } 10427 } 10428 propagateIRFlags(Op, ReductionOps[0], nullptr, /*IncludeWrapFlags=*/false); 10429 return Op; 10430 } 10431 10432 static RecurKind getRdxKind(Value *V) { 10433 auto *I = dyn_cast<Instruction>(V); 10434 if (!I) 10435 return RecurKind::None; 10436 if (match(I, m_Add(m_Value(), m_Value()))) 10437 return RecurKind::Add; 10438 if (match(I, m_Mul(m_Value(), m_Value()))) 10439 return RecurKind::Mul; 10440 if (match(I, m_And(m_Value(), m_Value())) || 10441 match(I, m_LogicalAnd(m_Value(), m_Value()))) 10442 return RecurKind::And; 10443 if (match(I, m_Or(m_Value(), m_Value())) || 10444 match(I, m_LogicalOr(m_Value(), m_Value()))) 10445 return RecurKind::Or; 10446 if (match(I, m_Xor(m_Value(), m_Value()))) 10447 return RecurKind::Xor; 10448 if (match(I, m_FAdd(m_Value(), m_Value()))) 10449 return RecurKind::FAdd; 10450 if (match(I, m_FMul(m_Value(), m_Value()))) 10451 return RecurKind::FMul; 10452 10453 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value()))) 10454 return RecurKind::FMax; 10455 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value()))) 10456 return RecurKind::FMin; 10457 10458 // This matches either cmp+select or intrinsics. SLP is expected to handle 10459 // either form. 10460 // TODO: If we are canonicalizing to intrinsics, we can remove several 10461 // special-case paths that deal with selects. 10462 if (match(I, m_SMax(m_Value(), m_Value()))) 10463 return RecurKind::SMax; 10464 if (match(I, m_SMin(m_Value(), m_Value()))) 10465 return RecurKind::SMin; 10466 if (match(I, m_UMax(m_Value(), m_Value()))) 10467 return RecurKind::UMax; 10468 if (match(I, m_UMin(m_Value(), m_Value()))) 10469 return RecurKind::UMin; 10470 10471 if (auto *Select = dyn_cast<SelectInst>(I)) { 10472 // Try harder: look for min/max pattern based on instructions producing 10473 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2). 10474 // During the intermediate stages of SLP, it's very common to have 10475 // pattern like this (since optimizeGatherSequence is run only once 10476 // at the end): 10477 // %1 = extractelement <2 x i32> %a, i32 0 10478 // %2 = extractelement <2 x i32> %a, i32 1 10479 // %cond = icmp sgt i32 %1, %2 10480 // %3 = extractelement <2 x i32> %a, i32 0 10481 // %4 = extractelement <2 x i32> %a, i32 1 10482 // %select = select i1 %cond, i32 %3, i32 %4 10483 CmpInst::Predicate Pred; 10484 Instruction *L1; 10485 Instruction *L2; 10486 10487 Value *LHS = Select->getTrueValue(); 10488 Value *RHS = Select->getFalseValue(); 10489 Value *Cond = Select->getCondition(); 10490 10491 // TODO: Support inverse predicates. 10492 if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) { 10493 if (!isa<ExtractElementInst>(RHS) || 10494 !L2->isIdenticalTo(cast<Instruction>(RHS))) 10495 return RecurKind::None; 10496 } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) { 10497 if (!isa<ExtractElementInst>(LHS) || 10498 !L1->isIdenticalTo(cast<Instruction>(LHS))) 10499 return RecurKind::None; 10500 } else { 10501 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS)) 10502 return RecurKind::None; 10503 if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) || 10504 !L1->isIdenticalTo(cast<Instruction>(LHS)) || 10505 !L2->isIdenticalTo(cast<Instruction>(RHS))) 10506 return RecurKind::None; 10507 } 10508 10509 switch (Pred) { 10510 default: 10511 return RecurKind::None; 10512 case CmpInst::ICMP_SGT: 10513 case CmpInst::ICMP_SGE: 10514 return RecurKind::SMax; 10515 case CmpInst::ICMP_SLT: 10516 case CmpInst::ICMP_SLE: 10517 return RecurKind::SMin; 10518 case CmpInst::ICMP_UGT: 10519 case CmpInst::ICMP_UGE: 10520 return RecurKind::UMax; 10521 case CmpInst::ICMP_ULT: 10522 case CmpInst::ICMP_ULE: 10523 return RecurKind::UMin; 10524 } 10525 } 10526 return RecurKind::None; 10527 } 10528 10529 /// Get the index of the first operand. 10530 static unsigned getFirstOperandIndex(Instruction *I) { 10531 return isCmpSelMinMax(I) ? 1 : 0; 10532 } 10533 10534 /// Total number of operands in the reduction operation. 10535 static unsigned getNumberOfOperands(Instruction *I) { 10536 return isCmpSelMinMax(I) ? 3 : 2; 10537 } 10538 10539 /// Checks if the instruction is in basic block \p BB. 10540 /// For a cmp+sel min/max reduction check that both ops are in \p BB. 10541 static bool hasSameParent(Instruction *I, BasicBlock *BB) { 10542 if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) { 10543 auto *Sel = cast<SelectInst>(I); 10544 auto *Cmp = dyn_cast<Instruction>(Sel->getCondition()); 10545 return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB; 10546 } 10547 return I->getParent() == BB; 10548 } 10549 10550 /// Expected number of uses for reduction operations/reduced values. 10551 static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) { 10552 if (IsCmpSelMinMax) { 10553 // SelectInst must be used twice while the condition op must have single 10554 // use only. 10555 if (auto *Sel = dyn_cast<SelectInst>(I)) 10556 return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse(); 10557 return I->hasNUses(2); 10558 } 10559 10560 // Arithmetic reduction operation must be used once only. 10561 return I->hasOneUse(); 10562 } 10563 10564 /// Initializes the list of reduction operations. 10565 void initReductionOps(Instruction *I) { 10566 if (isCmpSelMinMax(I)) 10567 ReductionOps.assign(2, ReductionOpsType()); 10568 else 10569 ReductionOps.assign(1, ReductionOpsType()); 10570 } 10571 10572 /// Add all reduction operations for the reduction instruction \p I. 10573 void addReductionOps(Instruction *I) { 10574 if (isCmpSelMinMax(I)) { 10575 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition()); 10576 ReductionOps[1].emplace_back(I); 10577 } else { 10578 ReductionOps[0].emplace_back(I); 10579 } 10580 } 10581 10582 static Value *getLHS(RecurKind Kind, Instruction *I) { 10583 if (Kind == RecurKind::None) 10584 return nullptr; 10585 return I->getOperand(getFirstOperandIndex(I)); 10586 } 10587 static Value *getRHS(RecurKind Kind, Instruction *I) { 10588 if (Kind == RecurKind::None) 10589 return nullptr; 10590 return I->getOperand(getFirstOperandIndex(I) + 1); 10591 } 10592 10593 public: 10594 HorizontalReduction() = default; 10595 10596 /// Try to find a reduction tree. 10597 bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst, 10598 ScalarEvolution &SE, const DataLayout &DL, 10599 const TargetLibraryInfo &TLI) { 10600 assert((!Phi || is_contained(Phi->operands(), Inst)) && 10601 "Phi needs to use the binary operator"); 10602 assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || 10603 isa<IntrinsicInst>(Inst)) && 10604 "Expected binop, select, or intrinsic for reduction matching"); 10605 RdxKind = getRdxKind(Inst); 10606 10607 // We could have a initial reductions that is not an add. 10608 // r *= v1 + v2 + v3 + v4 10609 // In such a case start looking for a tree rooted in the first '+'. 10610 if (Phi) { 10611 if (getLHS(RdxKind, Inst) == Phi) { 10612 Phi = nullptr; 10613 Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst)); 10614 if (!Inst) 10615 return false; 10616 RdxKind = getRdxKind(Inst); 10617 } else if (getRHS(RdxKind, Inst) == Phi) { 10618 Phi = nullptr; 10619 Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst)); 10620 if (!Inst) 10621 return false; 10622 RdxKind = getRdxKind(Inst); 10623 } 10624 } 10625 10626 if (!isVectorizable(RdxKind, Inst)) 10627 return false; 10628 10629 // Analyze "regular" integer/FP types for reductions - no target-specific 10630 // types or pointers. 10631 Type *Ty = Inst->getType(); 10632 if (!isValidElementType(Ty) || Ty->isPointerTy()) 10633 return false; 10634 10635 // Though the ultimate reduction may have multiple uses, its condition must 10636 // have only single use. 10637 if (auto *Sel = dyn_cast<SelectInst>(Inst)) 10638 if (!Sel->getCondition()->hasOneUse()) 10639 return false; 10640 10641 ReductionRoot = Inst; 10642 10643 // Iterate through all the operands of the possible reduction tree and 10644 // gather all the reduced values, sorting them by their value id. 10645 BasicBlock *BB = Inst->getParent(); 10646 bool IsCmpSelMinMax = isCmpSelMinMax(Inst); 10647 SmallVector<Instruction *> Worklist(1, Inst); 10648 // Checks if the operands of the \p TreeN instruction are also reduction 10649 // operations or should be treated as reduced values or an extra argument, 10650 // which is not part of the reduction. 10651 auto &&CheckOperands = [this, IsCmpSelMinMax, 10652 BB](Instruction *TreeN, 10653 SmallVectorImpl<Value *> &ExtraArgs, 10654 SmallVectorImpl<Value *> &PossibleReducedVals, 10655 SmallVectorImpl<Instruction *> &ReductionOps) { 10656 for (int I = getFirstOperandIndex(TreeN), 10657 End = getNumberOfOperands(TreeN); 10658 I < End; ++I) { 10659 Value *EdgeVal = getRdxOperand(TreeN, I); 10660 ReducedValsToOps[EdgeVal].push_back(TreeN); 10661 auto *EdgeInst = dyn_cast<Instruction>(EdgeVal); 10662 // Edge has wrong parent - mark as an extra argument. 10663 if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) && 10664 !hasSameParent(EdgeInst, BB)) { 10665 ExtraArgs.push_back(EdgeVal); 10666 continue; 10667 } 10668 // If the edge is not an instruction, or it is different from the main 10669 // reduction opcode or has too many uses - possible reduced value. 10670 if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind || 10671 IsCmpSelMinMax != isCmpSelMinMax(EdgeInst) || 10672 !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) || 10673 !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) { 10674 PossibleReducedVals.push_back(EdgeVal); 10675 continue; 10676 } 10677 ReductionOps.push_back(EdgeInst); 10678 } 10679 }; 10680 // Try to regroup reduced values so that it gets more profitable to try to 10681 // reduce them. Values are grouped by their value ids, instructions - by 10682 // instruction op id and/or alternate op id, plus do extra analysis for 10683 // loads (grouping them by the distabce between pointers) and cmp 10684 // instructions (grouping them by the predicate). 10685 MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>> 10686 PossibleReducedVals; 10687 initReductionOps(Inst); 10688 while (!Worklist.empty()) { 10689 Instruction *TreeN = Worklist.pop_back_val(); 10690 SmallVector<Value *> Args; 10691 SmallVector<Value *> PossibleRedVals; 10692 SmallVector<Instruction *> PossibleReductionOps; 10693 CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps); 10694 // If too many extra args - mark the instruction itself as a reduction 10695 // value, not a reduction operation. 10696 if (Args.size() < 2) { 10697 addReductionOps(TreeN); 10698 // Add extra args. 10699 if (!Args.empty()) { 10700 assert(Args.size() == 1 && "Expected only single argument."); 10701 ExtraArgs[TreeN] = Args.front(); 10702 } 10703 // Add reduction values. The values are sorted for better vectorization 10704 // results. 10705 for (Value *V : PossibleRedVals) { 10706 size_t Key, Idx; 10707 std::tie(Key, Idx) = generateKeySubkey( 10708 V, &TLI, 10709 [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) { 10710 auto It = PossibleReducedVals.find(Key); 10711 if (It != PossibleReducedVals.end()) { 10712 for (const auto &LoadData : It->second) { 10713 auto *RLI = cast<LoadInst>(LoadData.second.front().first); 10714 if (getPointersDiff(RLI->getType(), 10715 RLI->getPointerOperand(), LI->getType(), 10716 LI->getPointerOperand(), DL, SE, 10717 /*StrictCheck=*/true)) 10718 return hash_value(RLI->getPointerOperand()); 10719 } 10720 } 10721 return hash_value(LI->getPointerOperand()); 10722 }, 10723 /*AllowAlternate=*/false); 10724 ++PossibleReducedVals[Key][Idx] 10725 .insert(std::make_pair(V, 0)) 10726 .first->second; 10727 } 10728 Worklist.append(PossibleReductionOps.rbegin(), 10729 PossibleReductionOps.rend()); 10730 } else { 10731 size_t Key, Idx; 10732 std::tie(Key, Idx) = generateKeySubkey( 10733 TreeN, &TLI, 10734 [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) { 10735 auto It = PossibleReducedVals.find(Key); 10736 if (It != PossibleReducedVals.end()) { 10737 for (const auto &LoadData : It->second) { 10738 auto *RLI = cast<LoadInst>(LoadData.second.front().first); 10739 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(), 10740 LI->getType(), LI->getPointerOperand(), 10741 DL, SE, /*StrictCheck=*/true)) 10742 return hash_value(RLI->getPointerOperand()); 10743 } 10744 } 10745 return hash_value(LI->getPointerOperand()); 10746 }, 10747 /*AllowAlternate=*/false); 10748 ++PossibleReducedVals[Key][Idx] 10749 .insert(std::make_pair(TreeN, 0)) 10750 .first->second; 10751 } 10752 } 10753 auto PossibleReducedValsVect = PossibleReducedVals.takeVector(); 10754 // Sort values by the total number of values kinds to start the reduction 10755 // from the longest possible reduced values sequences. 10756 for (auto &PossibleReducedVals : PossibleReducedValsVect) { 10757 auto PossibleRedVals = PossibleReducedVals.second.takeVector(); 10758 SmallVector<SmallVector<Value *>> PossibleRedValsVect; 10759 for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end(); 10760 It != E; ++It) { 10761 PossibleRedValsVect.emplace_back(); 10762 auto RedValsVect = It->second.takeVector(); 10763 stable_sort(RedValsVect, [](const auto &P1, const auto &P2) { 10764 return P1.second < P2.second; 10765 }); 10766 for (const std::pair<Value *, unsigned> &Data : RedValsVect) 10767 PossibleRedValsVect.back().append(Data.second, Data.first); 10768 } 10769 stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) { 10770 return P1.size() > P2.size(); 10771 }); 10772 ReducedVals.emplace_back(); 10773 for (ArrayRef<Value *> Data : PossibleRedValsVect) 10774 ReducedVals.back().append(Data.rbegin(), Data.rend()); 10775 } 10776 // Sort the reduced values by number of same/alternate opcode and/or pointer 10777 // operand. 10778 stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) { 10779 return P1.size() > P2.size(); 10780 }); 10781 return true; 10782 } 10783 10784 /// Attempt to vectorize the tree found by matchAssociativeReduction. 10785 Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) { 10786 constexpr int ReductionLimit = 4; 10787 constexpr unsigned RegMaxNumber = 4; 10788 constexpr unsigned RedValsMaxNumber = 128; 10789 // If there are a sufficient number of reduction values, reduce 10790 // to a nearby power-of-2. We can safely generate oversized 10791 // vectors and rely on the backend to split them to legal sizes. 10792 unsigned NumReducedVals = std::accumulate( 10793 ReducedVals.begin(), ReducedVals.end(), 0, 10794 [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); }); 10795 if (NumReducedVals < ReductionLimit) 10796 return nullptr; 10797 10798 IRBuilder<> Builder(cast<Instruction>(ReductionRoot)); 10799 10800 // Track the reduced values in case if they are replaced by extractelement 10801 // because of the vectorization. 10802 DenseMap<Value *, WeakTrackingVH> TrackedVals; 10803 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues; 10804 // The same extra argument may be used several times, so log each attempt 10805 // to use it. 10806 for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) { 10807 assert(Pair.first && "DebugLoc must be set."); 10808 ExternallyUsedValues[Pair.second].push_back(Pair.first); 10809 TrackedVals.try_emplace(Pair.second, Pair.second); 10810 } 10811 10812 // The compare instruction of a min/max is the insertion point for new 10813 // instructions and may be replaced with a new compare instruction. 10814 auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) { 10815 assert(isa<SelectInst>(RdxRootInst) && 10816 "Expected min/max reduction to have select root instruction"); 10817 Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition(); 10818 assert(isa<Instruction>(ScalarCond) && 10819 "Expected min/max reduction to have compare condition"); 10820 return cast<Instruction>(ScalarCond); 10821 }; 10822 10823 // The reduction root is used as the insertion point for new instructions, 10824 // so set it as externally used to prevent it from being deleted. 10825 ExternallyUsedValues[ReductionRoot]; 10826 SmallDenseSet<Value *> IgnoreList; 10827 for (ReductionOpsType &RdxOps : ReductionOps) 10828 for (Value *RdxOp : RdxOps) { 10829 if (!RdxOp) 10830 continue; 10831 IgnoreList.insert(RdxOp); 10832 } 10833 bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot)); 10834 10835 // Need to track reduced vals, they may be changed during vectorization of 10836 // subvectors. 10837 for (ArrayRef<Value *> Candidates : ReducedVals) 10838 for (Value *V : Candidates) 10839 TrackedVals.try_emplace(V, V); 10840 10841 DenseMap<Value *, unsigned> VectorizedVals; 10842 Value *VectorizedTree = nullptr; 10843 bool CheckForReusedReductionOps = false; 10844 // Try to vectorize elements based on their type. 10845 for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) { 10846 ArrayRef<Value *> OrigReducedVals = ReducedVals[I]; 10847 InstructionsState S = getSameOpcode(OrigReducedVals); 10848 SmallVector<Value *> Candidates; 10849 DenseMap<Value *, Value *> TrackedToOrig; 10850 for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) { 10851 Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second; 10852 // Check if the reduction value was not overriden by the extractelement 10853 // instruction because of the vectorization and exclude it, if it is not 10854 // compatible with other values. 10855 if (auto *Inst = dyn_cast<Instruction>(RdxVal)) 10856 if (isVectorLikeInstWithConstOps(Inst) && 10857 (!S.getOpcode() || !S.isOpcodeOrAlt(Inst))) 10858 continue; 10859 Candidates.push_back(RdxVal); 10860 TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]); 10861 } 10862 bool ShuffledExtracts = false; 10863 // Try to handle shuffled extractelements. 10864 if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() && 10865 I + 1 < E) { 10866 InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]); 10867 if (NextS.getOpcode() == Instruction::ExtractElement && 10868 !NextS.isAltShuffle()) { 10869 SmallVector<Value *> CommonCandidates(Candidates); 10870 for (Value *RV : ReducedVals[I + 1]) { 10871 Value *RdxVal = TrackedVals.find(RV)->second; 10872 // Check if the reduction value was not overriden by the 10873 // extractelement instruction because of the vectorization and 10874 // exclude it, if it is not compatible with other values. 10875 if (auto *Inst = dyn_cast<Instruction>(RdxVal)) 10876 if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst)) 10877 continue; 10878 CommonCandidates.push_back(RdxVal); 10879 TrackedToOrig.try_emplace(RdxVal, RV); 10880 } 10881 SmallVector<int> Mask; 10882 if (isFixedVectorShuffle(CommonCandidates, Mask)) { 10883 ++I; 10884 Candidates.swap(CommonCandidates); 10885 ShuffledExtracts = true; 10886 } 10887 } 10888 } 10889 unsigned NumReducedVals = Candidates.size(); 10890 if (NumReducedVals < ReductionLimit) 10891 continue; 10892 10893 unsigned MaxVecRegSize = V.getMaxVecRegSize(); 10894 unsigned EltSize = V.getVectorElementSize(Candidates[0]); 10895 unsigned MaxElts = RegMaxNumber * PowerOf2Floor(MaxVecRegSize / EltSize); 10896 10897 unsigned ReduxWidth = std::min<unsigned>( 10898 PowerOf2Floor(NumReducedVals), std::max(RedValsMaxNumber, MaxElts)); 10899 unsigned Start = 0; 10900 unsigned Pos = Start; 10901 // Restarts vectorization attempt with lower vector factor. 10902 unsigned PrevReduxWidth = ReduxWidth; 10903 bool CheckForReusedReductionOpsLocal = false; 10904 auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals, 10905 &CheckForReusedReductionOpsLocal, 10906 &PrevReduxWidth, &V, 10907 &IgnoreList](bool IgnoreVL = false) { 10908 bool IsAnyRedOpGathered = !IgnoreVL && V.isAnyGathered(IgnoreList); 10909 if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) { 10910 // Check if any of the reduction ops are gathered. If so, worth 10911 // trying again with less number of reduction ops. 10912 CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered; 10913 } 10914 ++Pos; 10915 if (Pos < NumReducedVals - ReduxWidth + 1) 10916 return IsAnyRedOpGathered; 10917 Pos = Start; 10918 ReduxWidth /= 2; 10919 return IsAnyRedOpGathered; 10920 }; 10921 while (Pos < NumReducedVals - ReduxWidth + 1 && 10922 ReduxWidth >= ReductionLimit) { 10923 // Dependency in tree of the reduction ops - drop this attempt, try 10924 // later. 10925 if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth && 10926 Start == 0) { 10927 CheckForReusedReductionOps = true; 10928 break; 10929 } 10930 PrevReduxWidth = ReduxWidth; 10931 ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth); 10932 // Beeing analyzed already - skip. 10933 if (V.areAnalyzedReductionVals(VL)) { 10934 (void)AdjustReducedVals(/*IgnoreVL=*/true); 10935 continue; 10936 } 10937 // Early exit if any of the reduction values were deleted during 10938 // previous vectorization attempts. 10939 if (any_of(VL, [&V](Value *RedVal) { 10940 auto *RedValI = dyn_cast<Instruction>(RedVal); 10941 if (!RedValI) 10942 return false; 10943 return V.isDeleted(RedValI); 10944 })) 10945 break; 10946 V.buildTree(VL, IgnoreList); 10947 if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) { 10948 if (!AdjustReducedVals()) 10949 V.analyzedReductionVals(VL); 10950 continue; 10951 } 10952 if (V.isLoadCombineReductionCandidate(RdxKind)) { 10953 if (!AdjustReducedVals()) 10954 V.analyzedReductionVals(VL); 10955 continue; 10956 } 10957 V.reorderTopToBottom(); 10958 // No need to reorder the root node at all. 10959 V.reorderBottomToTop(/*IgnoreReorder=*/true); 10960 // Keep extracted other reduction values, if they are used in the 10961 // vectorization trees. 10962 BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues( 10963 ExternallyUsedValues); 10964 for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) { 10965 if (Cnt == I || (ShuffledExtracts && Cnt == I - 1)) 10966 continue; 10967 for_each(ReducedVals[Cnt], 10968 [&LocalExternallyUsedValues, &TrackedVals](Value *V) { 10969 if (isa<Instruction>(V)) 10970 LocalExternallyUsedValues[TrackedVals[V]]; 10971 }); 10972 } 10973 // Number of uses of the candidates in the vector of values. 10974 SmallDenseMap<Value *, unsigned> NumUses; 10975 for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) { 10976 Value *V = Candidates[Cnt]; 10977 if (NumUses.count(V) > 0) 10978 continue; 10979 NumUses[V] = std::count(VL.begin(), VL.end(), V); 10980 } 10981 for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) { 10982 Value *V = Candidates[Cnt]; 10983 if (NumUses.count(V) > 0) 10984 continue; 10985 NumUses[V] = std::count(VL.begin(), VL.end(), V); 10986 } 10987 // Gather externally used values. 10988 SmallPtrSet<Value *, 4> Visited; 10989 for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) { 10990 Value *V = Candidates[Cnt]; 10991 if (!Visited.insert(V).second) 10992 continue; 10993 unsigned NumOps = VectorizedVals.lookup(V) + NumUses[V]; 10994 if (NumOps != ReducedValsToOps.find(V)->second.size()) 10995 LocalExternallyUsedValues[V]; 10996 } 10997 for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) { 10998 Value *V = Candidates[Cnt]; 10999 if (!Visited.insert(V).second) 11000 continue; 11001 unsigned NumOps = VectorizedVals.lookup(V) + NumUses[V]; 11002 if (NumOps != ReducedValsToOps.find(V)->second.size()) 11003 LocalExternallyUsedValues[V]; 11004 } 11005 V.buildExternalUses(LocalExternallyUsedValues); 11006 11007 V.computeMinimumValueSizes(); 11008 11009 // Intersect the fast-math-flags from all reduction operations. 11010 FastMathFlags RdxFMF; 11011 RdxFMF.set(); 11012 for (Value *U : IgnoreList) 11013 if (auto *FPMO = dyn_cast<FPMathOperator>(U)) 11014 RdxFMF &= FPMO->getFastMathFlags(); 11015 // Estimate cost. 11016 InstructionCost TreeCost = V.getTreeCost(VL); 11017 InstructionCost ReductionCost = 11018 getReductionCost(TTI, VL, ReduxWidth, RdxFMF); 11019 InstructionCost Cost = TreeCost + ReductionCost; 11020 if (!Cost.isValid()) { 11021 LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n"); 11022 return nullptr; 11023 } 11024 if (Cost >= -SLPCostThreshold) { 11025 V.getORE()->emit([&]() { 11026 return OptimizationRemarkMissed( 11027 SV_NAME, "HorSLPNotBeneficial", 11028 ReducedValsToOps.find(VL[0])->second.front()) 11029 << "Vectorizing horizontal reduction is possible" 11030 << "but not beneficial with cost " << ore::NV("Cost", Cost) 11031 << " and threshold " 11032 << ore::NV("Threshold", -SLPCostThreshold); 11033 }); 11034 if (!AdjustReducedVals()) 11035 V.analyzedReductionVals(VL); 11036 continue; 11037 } 11038 11039 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" 11040 << Cost << ". (HorRdx)\n"); 11041 V.getORE()->emit([&]() { 11042 return OptimizationRemark( 11043 SV_NAME, "VectorizedHorizontalReduction", 11044 ReducedValsToOps.find(VL[0])->second.front()) 11045 << "Vectorized horizontal reduction with cost " 11046 << ore::NV("Cost", Cost) << " and with tree size " 11047 << ore::NV("TreeSize", V.getTreeSize()); 11048 }); 11049 11050 Builder.setFastMathFlags(RdxFMF); 11051 11052 // Vectorize a tree. 11053 Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues); 11054 11055 // Emit a reduction. If the root is a select (min/max idiom), the insert 11056 // point is the compare condition of that select. 11057 Instruction *RdxRootInst = cast<Instruction>(ReductionRoot); 11058 if (IsCmpSelMinMax) 11059 Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst)); 11060 else 11061 Builder.SetInsertPoint(RdxRootInst); 11062 11063 // To prevent poison from leaking across what used to be sequential, 11064 // safe, scalar boolean logic operations, the reduction operand must be 11065 // frozen. 11066 if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst)) 11067 VectorizedRoot = Builder.CreateFreeze(VectorizedRoot); 11068 11069 Value *ReducedSubTree = 11070 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI); 11071 11072 if (!VectorizedTree) { 11073 // Initialize the final value in the reduction. 11074 VectorizedTree = ReducedSubTree; 11075 } else { 11076 // Update the final value in the reduction. 11077 Builder.SetCurrentDebugLocation( 11078 cast<Instruction>(ReductionOps.front().front())->getDebugLoc()); 11079 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 11080 ReducedSubTree, "op.rdx", ReductionOps); 11081 } 11082 // Count vectorized reduced values to exclude them from final reduction. 11083 for (Value *V : VL) 11084 ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0) 11085 .first->getSecond(); 11086 Pos += ReduxWidth; 11087 Start = Pos; 11088 ReduxWidth = PowerOf2Floor(NumReducedVals - Pos); 11089 } 11090 } 11091 if (VectorizedTree) { 11092 // Finish the reduction. 11093 // Need to add extra arguments and not vectorized possible reduction 11094 // values. 11095 // Try to avoid dependencies between the scalar remainders after 11096 // reductions. 11097 auto &&FinalGen = 11098 [this, &Builder, 11099 &TrackedVals](ArrayRef<std::pair<Instruction *, Value *>> InstVals) { 11100 unsigned Sz = InstVals.size(); 11101 SmallVector<std::pair<Instruction *, Value *>> ExtraReds(Sz / 2 + 11102 Sz % 2); 11103 for (unsigned I = 0, E = (Sz / 2) * 2; I < E; I += 2) { 11104 Instruction *RedOp = InstVals[I + 1].first; 11105 Builder.SetCurrentDebugLocation(RedOp->getDebugLoc()); 11106 Value *RdxVal1 = InstVals[I].second; 11107 Value *StableRdxVal1 = RdxVal1; 11108 auto It1 = TrackedVals.find(RdxVal1); 11109 if (It1 != TrackedVals.end()) 11110 StableRdxVal1 = It1->second; 11111 Value *RdxVal2 = InstVals[I + 1].second; 11112 Value *StableRdxVal2 = RdxVal2; 11113 auto It2 = TrackedVals.find(RdxVal2); 11114 if (It2 != TrackedVals.end()) 11115 StableRdxVal2 = It2->second; 11116 Value *ExtraRed = createOp(Builder, RdxKind, StableRdxVal1, 11117 StableRdxVal2, "op.rdx", ReductionOps); 11118 ExtraReds[I / 2] = std::make_pair(InstVals[I].first, ExtraRed); 11119 } 11120 if (Sz % 2 == 1) 11121 ExtraReds[Sz / 2] = InstVals.back(); 11122 return ExtraReds; 11123 }; 11124 SmallVector<std::pair<Instruction *, Value *>> ExtraReductions; 11125 SmallPtrSet<Value *, 8> Visited; 11126 for (ArrayRef<Value *> Candidates : ReducedVals) { 11127 for (Value *RdxVal : Candidates) { 11128 if (!Visited.insert(RdxVal).second) 11129 continue; 11130 unsigned NumOps = VectorizedVals.lookup(RdxVal); 11131 for (Instruction *RedOp : 11132 makeArrayRef(ReducedValsToOps.find(RdxVal)->second) 11133 .drop_back(NumOps)) 11134 ExtraReductions.emplace_back(RedOp, RdxVal); 11135 } 11136 } 11137 for (auto &Pair : ExternallyUsedValues) { 11138 // Add each externally used value to the final reduction. 11139 for (auto *I : Pair.second) 11140 ExtraReductions.emplace_back(I, Pair.first); 11141 } 11142 // Iterate through all not-vectorized reduction values/extra arguments. 11143 while (ExtraReductions.size() > 1) { 11144 SmallVector<std::pair<Instruction *, Value *>> NewReds = 11145 FinalGen(ExtraReductions); 11146 ExtraReductions.swap(NewReds); 11147 } 11148 // Final reduction. 11149 if (ExtraReductions.size() == 1) { 11150 Instruction *RedOp = ExtraReductions.back().first; 11151 Builder.SetCurrentDebugLocation(RedOp->getDebugLoc()); 11152 Value *RdxVal = ExtraReductions.back().second; 11153 Value *StableRdxVal = RdxVal; 11154 auto It = TrackedVals.find(RdxVal); 11155 if (It != TrackedVals.end()) 11156 StableRdxVal = It->second; 11157 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 11158 StableRdxVal, "op.rdx", ReductionOps); 11159 } 11160 11161 ReductionRoot->replaceAllUsesWith(VectorizedTree); 11162 11163 // The original scalar reduction is expected to have no remaining 11164 // uses outside the reduction tree itself. Assert that we got this 11165 // correct, replace internal uses with undef, and mark for eventual 11166 // deletion. 11167 #ifndef NDEBUG 11168 SmallSet<Value *, 4> IgnoreSet; 11169 for (ArrayRef<Value *> RdxOps : ReductionOps) 11170 IgnoreSet.insert(RdxOps.begin(), RdxOps.end()); 11171 #endif 11172 for (ArrayRef<Value *> RdxOps : ReductionOps) { 11173 for (Value *Ignore : RdxOps) { 11174 if (!Ignore) 11175 continue; 11176 #ifndef NDEBUG 11177 for (auto *U : Ignore->users()) { 11178 assert(IgnoreSet.count(U) && 11179 "All users must be either in the reduction ops list."); 11180 } 11181 #endif 11182 if (!Ignore->use_empty()) { 11183 Value *Undef = UndefValue::get(Ignore->getType()); 11184 Ignore->replaceAllUsesWith(Undef); 11185 } 11186 V.eraseInstruction(cast<Instruction>(Ignore)); 11187 } 11188 } 11189 } else if (!CheckForReusedReductionOps) { 11190 for (ReductionOpsType &RdxOps : ReductionOps) 11191 for (Value *RdxOp : RdxOps) 11192 V.analyzedReductionRoot(cast<Instruction>(RdxOp)); 11193 } 11194 return VectorizedTree; 11195 } 11196 11197 private: 11198 /// Calculate the cost of a reduction. 11199 InstructionCost getReductionCost(TargetTransformInfo *TTI, 11200 ArrayRef<Value *> ReducedVals, 11201 unsigned ReduxWidth, FastMathFlags FMF) { 11202 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 11203 Value *FirstReducedVal = ReducedVals.front(); 11204 Type *ScalarTy = FirstReducedVal->getType(); 11205 FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth); 11206 InstructionCost VectorCost = 0, ScalarCost; 11207 // If all of the reduced values are constant, the vector cost is 0, since 11208 // the reduction value can be calculated at the compile time. 11209 bool AllConsts = all_of(ReducedVals, isConstant); 11210 switch (RdxKind) { 11211 case RecurKind::Add: 11212 case RecurKind::Mul: 11213 case RecurKind::Or: 11214 case RecurKind::And: 11215 case RecurKind::Xor: 11216 case RecurKind::FAdd: 11217 case RecurKind::FMul: { 11218 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind); 11219 if (!AllConsts) 11220 VectorCost = 11221 TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind); 11222 ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind); 11223 break; 11224 } 11225 case RecurKind::FMax: 11226 case RecurKind::FMin: { 11227 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 11228 if (!AllConsts) { 11229 auto *VecCondTy = 11230 cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 11231 VectorCost = 11232 TTI->getMinMaxReductionCost(VectorTy, VecCondTy, 11233 /*IsUnsigned=*/false, CostKind); 11234 } 11235 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 11236 ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy, 11237 SclCondTy, RdxPred, CostKind) + 11238 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 11239 SclCondTy, RdxPred, CostKind); 11240 break; 11241 } 11242 case RecurKind::SMax: 11243 case RecurKind::SMin: 11244 case RecurKind::UMax: 11245 case RecurKind::UMin: { 11246 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 11247 if (!AllConsts) { 11248 auto *VecCondTy = 11249 cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 11250 bool IsUnsigned = 11251 RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin; 11252 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, 11253 IsUnsigned, CostKind); 11254 } 11255 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 11256 ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy, 11257 SclCondTy, RdxPred, CostKind) + 11258 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 11259 SclCondTy, RdxPred, CostKind); 11260 break; 11261 } 11262 default: 11263 llvm_unreachable("Expected arithmetic or min/max reduction operation"); 11264 } 11265 11266 // Scalar cost is repeated for N-1 elements. 11267 ScalarCost *= (ReduxWidth - 1); 11268 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost 11269 << " for reduction that starts with " << *FirstReducedVal 11270 << " (It is a splitting reduction)\n"); 11271 return VectorCost - ScalarCost; 11272 } 11273 11274 /// Emit a horizontal reduction of the vectorized value. 11275 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder, 11276 unsigned ReduxWidth, const TargetTransformInfo *TTI) { 11277 assert(VectorizedValue && "Need to have a vectorized tree node"); 11278 assert(isPowerOf2_32(ReduxWidth) && 11279 "We only handle power-of-two reductions for now"); 11280 assert(RdxKind != RecurKind::FMulAdd && 11281 "A call to the llvm.fmuladd intrinsic is not handled yet"); 11282 11283 ++NumVectorInstructions; 11284 return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind); 11285 } 11286 }; 11287 11288 } // end anonymous namespace 11289 11290 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) { 11291 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) 11292 return cast<FixedVectorType>(IE->getType())->getNumElements(); 11293 11294 unsigned AggregateSize = 1; 11295 auto *IV = cast<InsertValueInst>(InsertInst); 11296 Type *CurrentType = IV->getType(); 11297 do { 11298 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 11299 for (auto *Elt : ST->elements()) 11300 if (Elt != ST->getElementType(0)) // check homogeneity 11301 return None; 11302 AggregateSize *= ST->getNumElements(); 11303 CurrentType = ST->getElementType(0); 11304 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 11305 AggregateSize *= AT->getNumElements(); 11306 CurrentType = AT->getElementType(); 11307 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) { 11308 AggregateSize *= VT->getNumElements(); 11309 return AggregateSize; 11310 } else if (CurrentType->isSingleValueType()) { 11311 return AggregateSize; 11312 } else { 11313 return None; 11314 } 11315 } while (true); 11316 } 11317 11318 static void findBuildAggregate_rec(Instruction *LastInsertInst, 11319 TargetTransformInfo *TTI, 11320 SmallVectorImpl<Value *> &BuildVectorOpds, 11321 SmallVectorImpl<Value *> &InsertElts, 11322 unsigned OperandOffset) { 11323 do { 11324 Value *InsertedOperand = LastInsertInst->getOperand(1); 11325 Optional<unsigned> OperandIndex = 11326 getInsertIndex(LastInsertInst, OperandOffset); 11327 if (!OperandIndex) 11328 return; 11329 if (isa<InsertElementInst>(InsertedOperand) || 11330 isa<InsertValueInst>(InsertedOperand)) { 11331 findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI, 11332 BuildVectorOpds, InsertElts, *OperandIndex); 11333 11334 } else { 11335 BuildVectorOpds[*OperandIndex] = InsertedOperand; 11336 InsertElts[*OperandIndex] = LastInsertInst; 11337 } 11338 LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0)); 11339 } while (LastInsertInst != nullptr && 11340 (isa<InsertValueInst>(LastInsertInst) || 11341 isa<InsertElementInst>(LastInsertInst)) && 11342 LastInsertInst->hasOneUse()); 11343 } 11344 11345 /// Recognize construction of vectors like 11346 /// %ra = insertelement <4 x float> poison, float %s0, i32 0 11347 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1 11348 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2 11349 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3 11350 /// starting from the last insertelement or insertvalue instruction. 11351 /// 11352 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>}, 11353 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on. 11354 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples. 11355 /// 11356 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type. 11357 /// 11358 /// \return true if it matches. 11359 static bool findBuildAggregate(Instruction *LastInsertInst, 11360 TargetTransformInfo *TTI, 11361 SmallVectorImpl<Value *> &BuildVectorOpds, 11362 SmallVectorImpl<Value *> &InsertElts) { 11363 11364 assert((isa<InsertElementInst>(LastInsertInst) || 11365 isa<InsertValueInst>(LastInsertInst)) && 11366 "Expected insertelement or insertvalue instruction!"); 11367 11368 assert((BuildVectorOpds.empty() && InsertElts.empty()) && 11369 "Expected empty result vectors!"); 11370 11371 Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst); 11372 if (!AggregateSize) 11373 return false; 11374 BuildVectorOpds.resize(*AggregateSize); 11375 InsertElts.resize(*AggregateSize); 11376 11377 findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0); 11378 llvm::erase_value(BuildVectorOpds, nullptr); 11379 llvm::erase_value(InsertElts, nullptr); 11380 if (BuildVectorOpds.size() >= 2) 11381 return true; 11382 11383 return false; 11384 } 11385 11386 /// Try and get a reduction value from a phi node. 11387 /// 11388 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions 11389 /// if they come from either \p ParentBB or a containing loop latch. 11390 /// 11391 /// \returns A candidate reduction value if possible, or \code nullptr \endcode 11392 /// if not possible. 11393 static Value *getReductionValue(const DominatorTree *DT, PHINode *P, 11394 BasicBlock *ParentBB, LoopInfo *LI) { 11395 // There are situations where the reduction value is not dominated by the 11396 // reduction phi. Vectorizing such cases has been reported to cause 11397 // miscompiles. See PR25787. 11398 auto DominatedReduxValue = [&](Value *R) { 11399 return isa<Instruction>(R) && 11400 DT->dominates(P->getParent(), cast<Instruction>(R)->getParent()); 11401 }; 11402 11403 Value *Rdx = nullptr; 11404 11405 // Return the incoming value if it comes from the same BB as the phi node. 11406 if (P->getIncomingBlock(0) == ParentBB) { 11407 Rdx = P->getIncomingValue(0); 11408 } else if (P->getIncomingBlock(1) == ParentBB) { 11409 Rdx = P->getIncomingValue(1); 11410 } 11411 11412 if (Rdx && DominatedReduxValue(Rdx)) 11413 return Rdx; 11414 11415 // Otherwise, check whether we have a loop latch to look at. 11416 Loop *BBL = LI->getLoopFor(ParentBB); 11417 if (!BBL) 11418 return nullptr; 11419 BasicBlock *BBLatch = BBL->getLoopLatch(); 11420 if (!BBLatch) 11421 return nullptr; 11422 11423 // There is a loop latch, return the incoming value if it comes from 11424 // that. This reduction pattern occasionally turns up. 11425 if (P->getIncomingBlock(0) == BBLatch) { 11426 Rdx = P->getIncomingValue(0); 11427 } else if (P->getIncomingBlock(1) == BBLatch) { 11428 Rdx = P->getIncomingValue(1); 11429 } 11430 11431 if (Rdx && DominatedReduxValue(Rdx)) 11432 return Rdx; 11433 11434 return nullptr; 11435 } 11436 11437 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) { 11438 if (match(I, m_BinOp(m_Value(V0), m_Value(V1)))) 11439 return true; 11440 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1)))) 11441 return true; 11442 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1)))) 11443 return true; 11444 if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1)))) 11445 return true; 11446 if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1)))) 11447 return true; 11448 if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1)))) 11449 return true; 11450 if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1)))) 11451 return true; 11452 return false; 11453 } 11454 11455 /// Attempt to reduce a horizontal reduction. 11456 /// If it is legal to match a horizontal reduction feeding the phi node \a P 11457 /// with reduction operators \a Root (or one of its operands) in a basic block 11458 /// \a BB, then check if it can be done. If horizontal reduction is not found 11459 /// and root instruction is a binary operation, vectorization of the operands is 11460 /// attempted. 11461 /// \returns true if a horizontal reduction was matched and reduced or operands 11462 /// of one of the binary instruction were vectorized. 11463 /// \returns false if a horizontal reduction was not matched (or not possible) 11464 /// or no vectorization of any binary operation feeding \a Root instruction was 11465 /// performed. 11466 static bool tryToVectorizeHorReductionOrInstOperands( 11467 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, 11468 TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL, 11469 const TargetLibraryInfo &TLI, 11470 const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) { 11471 if (!ShouldVectorizeHor) 11472 return false; 11473 11474 if (!Root) 11475 return false; 11476 11477 if (Root->getParent() != BB || isa<PHINode>(Root)) 11478 return false; 11479 // Start analysis starting from Root instruction. If horizontal reduction is 11480 // found, try to vectorize it. If it is not a horizontal reduction or 11481 // vectorization is not possible or not effective, and currently analyzed 11482 // instruction is a binary operation, try to vectorize the operands, using 11483 // pre-order DFS traversal order. If the operands were not vectorized, repeat 11484 // the same procedure considering each operand as a possible root of the 11485 // horizontal reduction. 11486 // Interrupt the process if the Root instruction itself was vectorized or all 11487 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized. 11488 // Skip the analysis of CmpInsts. Compiler implements postanalysis of the 11489 // CmpInsts so we can skip extra attempts in 11490 // tryToVectorizeHorReductionOrInstOperands and save compile time. 11491 std::queue<std::pair<Instruction *, unsigned>> Stack; 11492 Stack.emplace(Root, 0); 11493 SmallPtrSet<Value *, 8> VisitedInstrs; 11494 SmallVector<WeakTrackingVH> PostponedInsts; 11495 bool Res = false; 11496 auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst, 11497 Value *&B0, 11498 Value *&B1) -> Value * { 11499 if (R.isAnalyzedReductionRoot(Inst)) 11500 return nullptr; 11501 bool IsBinop = matchRdxBop(Inst, B0, B1); 11502 bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value())); 11503 if (IsBinop || IsSelect) { 11504 HorizontalReduction HorRdx; 11505 if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI)) 11506 return HorRdx.tryToReduce(R, TTI); 11507 } 11508 return nullptr; 11509 }; 11510 while (!Stack.empty()) { 11511 Instruction *Inst; 11512 unsigned Level; 11513 std::tie(Inst, Level) = Stack.front(); 11514 Stack.pop(); 11515 // Do not try to analyze instruction that has already been vectorized. 11516 // This may happen when we vectorize instruction operands on a previous 11517 // iteration while stack was populated before that happened. 11518 if (R.isDeleted(Inst)) 11519 continue; 11520 Value *B0 = nullptr, *B1 = nullptr; 11521 if (Value *V = TryToReduce(Inst, B0, B1)) { 11522 Res = true; 11523 // Set P to nullptr to avoid re-analysis of phi node in 11524 // matchAssociativeReduction function unless this is the root node. 11525 P = nullptr; 11526 if (auto *I = dyn_cast<Instruction>(V)) { 11527 // Try to find another reduction. 11528 Stack.emplace(I, Level); 11529 continue; 11530 } 11531 } else { 11532 bool IsBinop = B0 && B1; 11533 if (P && IsBinop) { 11534 Inst = dyn_cast<Instruction>(B0); 11535 if (Inst == P) 11536 Inst = dyn_cast<Instruction>(B1); 11537 if (!Inst) { 11538 // Set P to nullptr to avoid re-analysis of phi node in 11539 // matchAssociativeReduction function unless this is the root node. 11540 P = nullptr; 11541 continue; 11542 } 11543 } 11544 // Set P to nullptr to avoid re-analysis of phi node in 11545 // matchAssociativeReduction function unless this is the root node. 11546 P = nullptr; 11547 // Do not try to vectorize CmpInst operands, this is done separately. 11548 // Final attempt for binop args vectorization should happen after the loop 11549 // to try to find reductions. 11550 if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst)) 11551 PostponedInsts.push_back(Inst); 11552 } 11553 11554 // Try to vectorize operands. 11555 // Continue analysis for the instruction from the same basic block only to 11556 // save compile time. 11557 if (++Level < RecursionMaxDepth) 11558 for (auto *Op : Inst->operand_values()) 11559 if (VisitedInstrs.insert(Op).second) 11560 if (auto *I = dyn_cast<Instruction>(Op)) 11561 // Do not try to vectorize CmpInst operands, this is done 11562 // separately. 11563 if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) && 11564 !R.isDeleted(I) && I->getParent() == BB) 11565 Stack.emplace(I, Level); 11566 } 11567 // Try to vectorized binops where reductions were not found. 11568 for (Value *V : PostponedInsts) 11569 if (auto *Inst = dyn_cast<Instruction>(V)) 11570 if (!R.isDeleted(Inst)) 11571 Res |= Vectorize(Inst, R); 11572 return Res; 11573 } 11574 11575 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V, 11576 BasicBlock *BB, BoUpSLP &R, 11577 TargetTransformInfo *TTI) { 11578 auto *I = dyn_cast_or_null<Instruction>(V); 11579 if (!I) 11580 return false; 11581 11582 if (!isa<BinaryOperator>(I)) 11583 P = nullptr; 11584 // Try to match and vectorize a horizontal reduction. 11585 auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool { 11586 return tryToVectorize(I, R); 11587 }; 11588 return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL, 11589 *TLI, ExtraVectorization); 11590 } 11591 11592 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI, 11593 BasicBlock *BB, BoUpSLP &R) { 11594 const DataLayout &DL = BB->getModule()->getDataLayout(); 11595 if (!R.canMapToVector(IVI->getType(), DL)) 11596 return false; 11597 11598 SmallVector<Value *, 16> BuildVectorOpds; 11599 SmallVector<Value *, 16> BuildVectorInsts; 11600 if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts)) 11601 return false; 11602 11603 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n"); 11604 // Aggregate value is unlikely to be processed in vector register. 11605 return tryToVectorizeList(BuildVectorOpds, R); 11606 } 11607 11608 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI, 11609 BasicBlock *BB, BoUpSLP &R) { 11610 SmallVector<Value *, 16> BuildVectorInsts; 11611 SmallVector<Value *, 16> BuildVectorOpds; 11612 SmallVector<int> Mask; 11613 if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) || 11614 (llvm::all_of( 11615 BuildVectorOpds, 11616 [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) && 11617 isFixedVectorShuffle(BuildVectorOpds, Mask))) 11618 return false; 11619 11620 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n"); 11621 return tryToVectorizeList(BuildVectorInsts, R); 11622 } 11623 11624 template <typename T> 11625 static bool 11626 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming, 11627 function_ref<unsigned(T *)> Limit, 11628 function_ref<bool(T *, T *)> Comparator, 11629 function_ref<bool(T *, T *)> AreCompatible, 11630 function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper, 11631 bool LimitForRegisterSize) { 11632 bool Changed = false; 11633 // Sort by type, parent, operands. 11634 stable_sort(Incoming, Comparator); 11635 11636 // Try to vectorize elements base on their type. 11637 SmallVector<T *> Candidates; 11638 for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) { 11639 // Look for the next elements with the same type, parent and operand 11640 // kinds. 11641 auto *SameTypeIt = IncIt; 11642 while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt)) 11643 ++SameTypeIt; 11644 11645 // Try to vectorize them. 11646 unsigned NumElts = (SameTypeIt - IncIt); 11647 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes (" 11648 << NumElts << ")\n"); 11649 // The vectorization is a 3-state attempt: 11650 // 1. Try to vectorize instructions with the same/alternate opcodes with the 11651 // size of maximal register at first. 11652 // 2. Try to vectorize remaining instructions with the same type, if 11653 // possible. This may result in the better vectorization results rather than 11654 // if we try just to vectorize instructions with the same/alternate opcodes. 11655 // 3. Final attempt to try to vectorize all instructions with the 11656 // same/alternate ops only, this may result in some extra final 11657 // vectorization. 11658 if (NumElts > 1 && 11659 TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) { 11660 // Success start over because instructions might have been changed. 11661 Changed = true; 11662 } else if (NumElts < Limit(*IncIt) && 11663 (Candidates.empty() || 11664 Candidates.front()->getType() == (*IncIt)->getType())) { 11665 Candidates.append(IncIt, std::next(IncIt, NumElts)); 11666 } 11667 // Final attempt to vectorize instructions with the same types. 11668 if (Candidates.size() > 1 && 11669 (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) { 11670 if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) { 11671 // Success start over because instructions might have been changed. 11672 Changed = true; 11673 } else if (LimitForRegisterSize) { 11674 // Try to vectorize using small vectors. 11675 for (auto *It = Candidates.begin(), *End = Candidates.end(); 11676 It != End;) { 11677 auto *SameTypeIt = It; 11678 while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It)) 11679 ++SameTypeIt; 11680 unsigned NumElts = (SameTypeIt - It); 11681 if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts), 11682 /*LimitForRegisterSize=*/false)) 11683 Changed = true; 11684 It = SameTypeIt; 11685 } 11686 } 11687 Candidates.clear(); 11688 } 11689 11690 // Start over at the next instruction of a different type (or the end). 11691 IncIt = SameTypeIt; 11692 } 11693 return Changed; 11694 } 11695 11696 /// Compare two cmp instructions. If IsCompatibility is true, function returns 11697 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding 11698 /// operands. If IsCompatibility is false, function implements strict weak 11699 /// ordering relation between two cmp instructions, returning true if the first 11700 /// instruction is "less" than the second, i.e. its predicate is less than the 11701 /// predicate of the second or the operands IDs are less than the operands IDs 11702 /// of the second cmp instruction. 11703 template <bool IsCompatibility> 11704 static bool compareCmp(Value *V, Value *V2, 11705 function_ref<bool(Instruction *)> IsDeleted) { 11706 auto *CI1 = cast<CmpInst>(V); 11707 auto *CI2 = cast<CmpInst>(V2); 11708 if (IsDeleted(CI2) || !isValidElementType(CI2->getType())) 11709 return false; 11710 if (CI1->getOperand(0)->getType()->getTypeID() < 11711 CI2->getOperand(0)->getType()->getTypeID()) 11712 return !IsCompatibility; 11713 if (CI1->getOperand(0)->getType()->getTypeID() > 11714 CI2->getOperand(0)->getType()->getTypeID()) 11715 return false; 11716 CmpInst::Predicate Pred1 = CI1->getPredicate(); 11717 CmpInst::Predicate Pred2 = CI2->getPredicate(); 11718 CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1); 11719 CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2); 11720 CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1); 11721 CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2); 11722 if (BasePred1 < BasePred2) 11723 return !IsCompatibility; 11724 if (BasePred1 > BasePred2) 11725 return false; 11726 // Compare operands. 11727 bool LEPreds = Pred1 <= Pred2; 11728 bool GEPreds = Pred1 >= Pred2; 11729 for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) { 11730 auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1); 11731 auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1); 11732 if (Op1->getValueID() < Op2->getValueID()) 11733 return !IsCompatibility; 11734 if (Op1->getValueID() > Op2->getValueID()) 11735 return false; 11736 if (auto *I1 = dyn_cast<Instruction>(Op1)) 11737 if (auto *I2 = dyn_cast<Instruction>(Op2)) { 11738 if (I1->getParent() != I2->getParent()) 11739 return false; 11740 InstructionsState S = getSameOpcode({I1, I2}); 11741 if (S.getOpcode()) 11742 continue; 11743 return false; 11744 } 11745 } 11746 return IsCompatibility; 11747 } 11748 11749 bool SLPVectorizerPass::vectorizeSimpleInstructions( 11750 SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R, 11751 bool AtTerminator) { 11752 bool OpsChanged = false; 11753 SmallVector<Instruction *, 4> PostponedCmps; 11754 for (auto *I : reverse(Instructions)) { 11755 if (R.isDeleted(I)) 11756 continue; 11757 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) { 11758 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R); 11759 } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) { 11760 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R); 11761 } else if (isa<CmpInst>(I)) { 11762 PostponedCmps.push_back(I); 11763 continue; 11764 } 11765 // Try to find reductions in buildvector sequnces. 11766 OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI); 11767 } 11768 if (AtTerminator) { 11769 // Try to find reductions first. 11770 for (Instruction *I : PostponedCmps) { 11771 if (R.isDeleted(I)) 11772 continue; 11773 for (Value *Op : I->operands()) 11774 OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI); 11775 } 11776 // Try to vectorize operands as vector bundles. 11777 for (Instruction *I : PostponedCmps) { 11778 if (R.isDeleted(I)) 11779 continue; 11780 OpsChanged |= tryToVectorize(I, R); 11781 } 11782 // Try to vectorize list of compares. 11783 // Sort by type, compare predicate, etc. 11784 auto &&CompareSorter = [&R](Value *V, Value *V2) { 11785 return compareCmp<false>(V, V2, 11786 [&R](Instruction *I) { return R.isDeleted(I); }); 11787 }; 11788 11789 auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) { 11790 if (V1 == V2) 11791 return true; 11792 return compareCmp<true>(V1, V2, 11793 [&R](Instruction *I) { return R.isDeleted(I); }); 11794 }; 11795 auto Limit = [&R](Value *V) { 11796 unsigned EltSize = R.getVectorElementSize(V); 11797 return std::max(2U, R.getMaxVecRegSize() / EltSize); 11798 }; 11799 11800 SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end()); 11801 OpsChanged |= tryToVectorizeSequence<Value>( 11802 Vals, Limit, CompareSorter, AreCompatibleCompares, 11803 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 11804 // Exclude possible reductions from other blocks. 11805 bool ArePossiblyReducedInOtherBlock = 11806 any_of(Candidates, [](Value *V) { 11807 return any_of(V->users(), [V](User *U) { 11808 return isa<SelectInst>(U) && 11809 cast<SelectInst>(U)->getParent() != 11810 cast<Instruction>(V)->getParent(); 11811 }); 11812 }); 11813 if (ArePossiblyReducedInOtherBlock) 11814 return false; 11815 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 11816 }, 11817 /*LimitForRegisterSize=*/true); 11818 Instructions.clear(); 11819 } else { 11820 // Insert in reverse order since the PostponedCmps vector was filled in 11821 // reverse order. 11822 Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend()); 11823 } 11824 return OpsChanged; 11825 } 11826 11827 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { 11828 bool Changed = false; 11829 SmallVector<Value *, 4> Incoming; 11830 SmallPtrSet<Value *, 16> VisitedInstrs; 11831 // Maps phi nodes to the non-phi nodes found in the use tree for each phi 11832 // node. Allows better to identify the chains that can be vectorized in the 11833 // better way. 11834 DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes; 11835 auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) { 11836 assert(isValidElementType(V1->getType()) && 11837 isValidElementType(V2->getType()) && 11838 "Expected vectorizable types only."); 11839 // It is fine to compare type IDs here, since we expect only vectorizable 11840 // types, like ints, floats and pointers, we don't care about other type. 11841 if (V1->getType()->getTypeID() < V2->getType()->getTypeID()) 11842 return true; 11843 if (V1->getType()->getTypeID() > V2->getType()->getTypeID()) 11844 return false; 11845 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 11846 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 11847 if (Opcodes1.size() < Opcodes2.size()) 11848 return true; 11849 if (Opcodes1.size() > Opcodes2.size()) 11850 return false; 11851 Optional<bool> ConstOrder; 11852 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 11853 // Undefs are compatible with any other value. 11854 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) { 11855 if (!ConstOrder) 11856 ConstOrder = 11857 !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]); 11858 continue; 11859 } 11860 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 11861 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 11862 DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent()); 11863 DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent()); 11864 if (!NodeI1) 11865 return NodeI2 != nullptr; 11866 if (!NodeI2) 11867 return false; 11868 assert((NodeI1 == NodeI2) == 11869 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 11870 "Different nodes should have different DFS numbers"); 11871 if (NodeI1 != NodeI2) 11872 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 11873 InstructionsState S = getSameOpcode({I1, I2}); 11874 if (S.getOpcode()) 11875 continue; 11876 return I1->getOpcode() < I2->getOpcode(); 11877 } 11878 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) { 11879 if (!ConstOrder) 11880 ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID(); 11881 continue; 11882 } 11883 if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID()) 11884 return true; 11885 if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID()) 11886 return false; 11887 } 11888 return ConstOrder && *ConstOrder; 11889 }; 11890 auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) { 11891 if (V1 == V2) 11892 return true; 11893 if (V1->getType() != V2->getType()) 11894 return false; 11895 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 11896 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 11897 if (Opcodes1.size() != Opcodes2.size()) 11898 return false; 11899 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 11900 // Undefs are compatible with any other value. 11901 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) 11902 continue; 11903 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 11904 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 11905 if (I1->getParent() != I2->getParent()) 11906 return false; 11907 InstructionsState S = getSameOpcode({I1, I2}); 11908 if (S.getOpcode()) 11909 continue; 11910 return false; 11911 } 11912 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) 11913 continue; 11914 if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID()) 11915 return false; 11916 } 11917 return true; 11918 }; 11919 auto Limit = [&R](Value *V) { 11920 unsigned EltSize = R.getVectorElementSize(V); 11921 return std::max(2U, R.getMaxVecRegSize() / EltSize); 11922 }; 11923 11924 bool HaveVectorizedPhiNodes = false; 11925 do { 11926 // Collect the incoming values from the PHIs. 11927 Incoming.clear(); 11928 for (Instruction &I : *BB) { 11929 PHINode *P = dyn_cast<PHINode>(&I); 11930 if (!P) 11931 break; 11932 11933 // No need to analyze deleted, vectorized and non-vectorizable 11934 // instructions. 11935 if (!VisitedInstrs.count(P) && !R.isDeleted(P) && 11936 isValidElementType(P->getType())) 11937 Incoming.push_back(P); 11938 } 11939 11940 // Find the corresponding non-phi nodes for better matching when trying to 11941 // build the tree. 11942 for (Value *V : Incoming) { 11943 SmallVectorImpl<Value *> &Opcodes = 11944 PHIToOpcodes.try_emplace(V).first->getSecond(); 11945 if (!Opcodes.empty()) 11946 continue; 11947 SmallVector<Value *, 4> Nodes(1, V); 11948 SmallPtrSet<Value *, 4> Visited; 11949 while (!Nodes.empty()) { 11950 auto *PHI = cast<PHINode>(Nodes.pop_back_val()); 11951 if (!Visited.insert(PHI).second) 11952 continue; 11953 for (Value *V : PHI->incoming_values()) { 11954 if (auto *PHI1 = dyn_cast<PHINode>((V))) { 11955 Nodes.push_back(PHI1); 11956 continue; 11957 } 11958 Opcodes.emplace_back(V); 11959 } 11960 } 11961 } 11962 11963 HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>( 11964 Incoming, Limit, PHICompare, AreCompatiblePHIs, 11965 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 11966 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 11967 }, 11968 /*LimitForRegisterSize=*/true); 11969 Changed |= HaveVectorizedPhiNodes; 11970 VisitedInstrs.insert(Incoming.begin(), Incoming.end()); 11971 } while (HaveVectorizedPhiNodes); 11972 11973 VisitedInstrs.clear(); 11974 11975 SmallVector<Instruction *, 8> PostProcessInstructions; 11976 SmallDenseSet<Instruction *, 4> KeyNodes; 11977 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 11978 // Skip instructions with scalable type. The num of elements is unknown at 11979 // compile-time for scalable type. 11980 if (isa<ScalableVectorType>(it->getType())) 11981 continue; 11982 11983 // Skip instructions marked for the deletion. 11984 if (R.isDeleted(&*it)) 11985 continue; 11986 // We may go through BB multiple times so skip the one we have checked. 11987 if (!VisitedInstrs.insert(&*it).second) { 11988 if (it->use_empty() && KeyNodes.contains(&*it) && 11989 vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 11990 it->isTerminator())) { 11991 // We would like to start over since some instructions are deleted 11992 // and the iterator may become invalid value. 11993 Changed = true; 11994 it = BB->begin(); 11995 e = BB->end(); 11996 } 11997 continue; 11998 } 11999 12000 if (isa<DbgInfoIntrinsic>(it)) 12001 continue; 12002 12003 // Try to vectorize reductions that use PHINodes. 12004 if (PHINode *P = dyn_cast<PHINode>(it)) { 12005 // Check that the PHI is a reduction PHI. 12006 if (P->getNumIncomingValues() == 2) { 12007 // Try to match and vectorize a horizontal reduction. 12008 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R, 12009 TTI)) { 12010 Changed = true; 12011 it = BB->begin(); 12012 e = BB->end(); 12013 continue; 12014 } 12015 } 12016 // Try to vectorize the incoming values of the PHI, to catch reductions 12017 // that feed into PHIs. 12018 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) { 12019 // Skip if the incoming block is the current BB for now. Also, bypass 12020 // unreachable IR for efficiency and to avoid crashing. 12021 // TODO: Collect the skipped incoming values and try to vectorize them 12022 // after processing BB. 12023 if (BB == P->getIncomingBlock(I) || 12024 !DT->isReachableFromEntry(P->getIncomingBlock(I))) 12025 continue; 12026 12027 Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I), 12028 P->getIncomingBlock(I), R, TTI); 12029 } 12030 continue; 12031 } 12032 12033 // Ran into an instruction without users, like terminator, or function call 12034 // with ignored return value, store. Ignore unused instructions (basing on 12035 // instruction type, except for CallInst and InvokeInst). 12036 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) || 12037 isa<InvokeInst>(it))) { 12038 KeyNodes.insert(&*it); 12039 bool OpsChanged = false; 12040 if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) { 12041 for (auto *V : it->operand_values()) { 12042 // Try to match and vectorize a horizontal reduction. 12043 OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI); 12044 } 12045 } 12046 // Start vectorization of post-process list of instructions from the 12047 // top-tree instructions to try to vectorize as many instructions as 12048 // possible. 12049 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 12050 it->isTerminator()); 12051 if (OpsChanged) { 12052 // We would like to start over since some instructions are deleted 12053 // and the iterator may become invalid value. 12054 Changed = true; 12055 it = BB->begin(); 12056 e = BB->end(); 12057 continue; 12058 } 12059 } 12060 12061 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) || 12062 isa<InsertValueInst>(it)) 12063 PostProcessInstructions.push_back(&*it); 12064 } 12065 12066 return Changed; 12067 } 12068 12069 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) { 12070 auto Changed = false; 12071 for (auto &Entry : GEPs) { 12072 // If the getelementptr list has fewer than two elements, there's nothing 12073 // to do. 12074 if (Entry.second.size() < 2) 12075 continue; 12076 12077 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length " 12078 << Entry.second.size() << ".\n"); 12079 12080 // Process the GEP list in chunks suitable for the target's supported 12081 // vector size. If a vector register can't hold 1 element, we are done. We 12082 // are trying to vectorize the index computations, so the maximum number of 12083 // elements is based on the size of the index expression, rather than the 12084 // size of the GEP itself (the target's pointer size). 12085 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 12086 unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin()); 12087 if (MaxVecRegSize < EltSize) 12088 continue; 12089 12090 unsigned MaxElts = MaxVecRegSize / EltSize; 12091 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) { 12092 auto Len = std::min<unsigned>(BE - BI, MaxElts); 12093 ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len); 12094 12095 // Initialize a set a candidate getelementptrs. Note that we use a 12096 // SetVector here to preserve program order. If the index computations 12097 // are vectorizable and begin with loads, we want to minimize the chance 12098 // of having to reorder them later. 12099 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end()); 12100 12101 // Some of the candidates may have already been vectorized after we 12102 // initially collected them. If so, they are marked as deleted, so remove 12103 // them from the set of candidates. 12104 Candidates.remove_if( 12105 [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); }); 12106 12107 // Remove from the set of candidates all pairs of getelementptrs with 12108 // constant differences. Such getelementptrs are likely not good 12109 // candidates for vectorization in a bottom-up phase since one can be 12110 // computed from the other. We also ensure all candidate getelementptr 12111 // indices are unique. 12112 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) { 12113 auto *GEPI = GEPList[I]; 12114 if (!Candidates.count(GEPI)) 12115 continue; 12116 auto *SCEVI = SE->getSCEV(GEPList[I]); 12117 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) { 12118 auto *GEPJ = GEPList[J]; 12119 auto *SCEVJ = SE->getSCEV(GEPList[J]); 12120 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) { 12121 Candidates.remove(GEPI); 12122 Candidates.remove(GEPJ); 12123 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) { 12124 Candidates.remove(GEPJ); 12125 } 12126 } 12127 } 12128 12129 // We break out of the above computation as soon as we know there are 12130 // fewer than two candidates remaining. 12131 if (Candidates.size() < 2) 12132 continue; 12133 12134 // Add the single, non-constant index of each candidate to the bundle. We 12135 // ensured the indices met these constraints when we originally collected 12136 // the getelementptrs. 12137 SmallVector<Value *, 16> Bundle(Candidates.size()); 12138 auto BundleIndex = 0u; 12139 for (auto *V : Candidates) { 12140 auto *GEP = cast<GetElementPtrInst>(V); 12141 auto *GEPIdx = GEP->idx_begin()->get(); 12142 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)); 12143 Bundle[BundleIndex++] = GEPIdx; 12144 } 12145 12146 // Try and vectorize the indices. We are currently only interested in 12147 // gather-like cases of the form: 12148 // 12149 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ... 12150 // 12151 // where the loads of "a", the loads of "b", and the subtractions can be 12152 // performed in parallel. It's likely that detecting this pattern in a 12153 // bottom-up phase will be simpler and less costly than building a 12154 // full-blown top-down phase beginning at the consecutive loads. 12155 Changed |= tryToVectorizeList(Bundle, R); 12156 } 12157 } 12158 return Changed; 12159 } 12160 12161 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) { 12162 bool Changed = false; 12163 // Sort by type, base pointers and values operand. Value operands must be 12164 // compatible (have the same opcode, same parent), otherwise it is 12165 // definitely not profitable to try to vectorize them. 12166 auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) { 12167 if (V->getPointerOperandType()->getTypeID() < 12168 V2->getPointerOperandType()->getTypeID()) 12169 return true; 12170 if (V->getPointerOperandType()->getTypeID() > 12171 V2->getPointerOperandType()->getTypeID()) 12172 return false; 12173 // UndefValues are compatible with all other values. 12174 if (isa<UndefValue>(V->getValueOperand()) || 12175 isa<UndefValue>(V2->getValueOperand())) 12176 return false; 12177 if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand())) 12178 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 12179 DomTreeNodeBase<llvm::BasicBlock> *NodeI1 = 12180 DT->getNode(I1->getParent()); 12181 DomTreeNodeBase<llvm::BasicBlock> *NodeI2 = 12182 DT->getNode(I2->getParent()); 12183 assert(NodeI1 && "Should only process reachable instructions"); 12184 assert(NodeI2 && "Should only process reachable instructions"); 12185 assert((NodeI1 == NodeI2) == 12186 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 12187 "Different nodes should have different DFS numbers"); 12188 if (NodeI1 != NodeI2) 12189 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 12190 InstructionsState S = getSameOpcode({I1, I2}); 12191 if (S.getOpcode()) 12192 return false; 12193 return I1->getOpcode() < I2->getOpcode(); 12194 } 12195 if (isa<Constant>(V->getValueOperand()) && 12196 isa<Constant>(V2->getValueOperand())) 12197 return false; 12198 return V->getValueOperand()->getValueID() < 12199 V2->getValueOperand()->getValueID(); 12200 }; 12201 12202 auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) { 12203 if (V1 == V2) 12204 return true; 12205 if (V1->getPointerOperandType() != V2->getPointerOperandType()) 12206 return false; 12207 // Undefs are compatible with any other value. 12208 if (isa<UndefValue>(V1->getValueOperand()) || 12209 isa<UndefValue>(V2->getValueOperand())) 12210 return true; 12211 if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand())) 12212 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 12213 if (I1->getParent() != I2->getParent()) 12214 return false; 12215 InstructionsState S = getSameOpcode({I1, I2}); 12216 return S.getOpcode() > 0; 12217 } 12218 if (isa<Constant>(V1->getValueOperand()) && 12219 isa<Constant>(V2->getValueOperand())) 12220 return true; 12221 return V1->getValueOperand()->getValueID() == 12222 V2->getValueOperand()->getValueID(); 12223 }; 12224 auto Limit = [&R, this](StoreInst *SI) { 12225 unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType()); 12226 return R.getMinVF(EltSize); 12227 }; 12228 12229 // Attempt to sort and vectorize each of the store-groups. 12230 for (auto &Pair : Stores) { 12231 if (Pair.second.size() < 2) 12232 continue; 12233 12234 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " 12235 << Pair.second.size() << ".\n"); 12236 12237 if (!isValidElementType(Pair.second.front()->getValueOperand()->getType())) 12238 continue; 12239 12240 Changed |= tryToVectorizeSequence<StoreInst>( 12241 Pair.second, Limit, StoreSorter, AreCompatibleStores, 12242 [this, &R](ArrayRef<StoreInst *> Candidates, bool) { 12243 return vectorizeStores(Candidates, R); 12244 }, 12245 /*LimitForRegisterSize=*/false); 12246 } 12247 return Changed; 12248 } 12249 12250 char SLPVectorizer::ID = 0; 12251 12252 static const char lv_name[] = "SLP Vectorizer"; 12253 12254 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false) 12255 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 12256 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 12257 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12258 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 12259 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 12260 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) 12261 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 12262 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy) 12263 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) 12264 12265 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); } 12266