1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive 10 // stores that can be put together into vector-stores. Next, it attempts to 11 // construct vectorizable tree using the use-def chains. If a profitable tree 12 // was found, the SLP vectorizer performs vectorization on the tree. 13 // 14 // The pass is inspired by the work described in the paper: 15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/DenseSet.h" 22 #include "llvm/ADT/Optional.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/PriorityQueue.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SetOperations.h" 27 #include "llvm/ADT/SetVector.h" 28 #include "llvm/ADT/SmallBitVector.h" 29 #include "llvm/ADT/SmallPtrSet.h" 30 #include "llvm/ADT/SmallSet.h" 31 #include "llvm/ADT/SmallString.h" 32 #include "llvm/ADT/Statistic.h" 33 #include "llvm/ADT/iterator.h" 34 #include "llvm/ADT/iterator_range.h" 35 #include "llvm/Analysis/AliasAnalysis.h" 36 #include "llvm/Analysis/AssumptionCache.h" 37 #include "llvm/Analysis/CodeMetrics.h" 38 #include "llvm/Analysis/DemandedBits.h" 39 #include "llvm/Analysis/GlobalsModRef.h" 40 #include "llvm/Analysis/IVDescriptors.h" 41 #include "llvm/Analysis/LoopAccessAnalysis.h" 42 #include "llvm/Analysis/LoopInfo.h" 43 #include "llvm/Analysis/MemoryLocation.h" 44 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 45 #include "llvm/Analysis/ScalarEvolution.h" 46 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 47 #include "llvm/Analysis/TargetLibraryInfo.h" 48 #include "llvm/Analysis/TargetTransformInfo.h" 49 #include "llvm/Analysis/ValueTracking.h" 50 #include "llvm/Analysis/VectorUtils.h" 51 #include "llvm/IR/Attributes.h" 52 #include "llvm/IR/BasicBlock.h" 53 #include "llvm/IR/Constant.h" 54 #include "llvm/IR/Constants.h" 55 #include "llvm/IR/DataLayout.h" 56 #include "llvm/IR/DerivedTypes.h" 57 #include "llvm/IR/Dominators.h" 58 #include "llvm/IR/Function.h" 59 #include "llvm/IR/IRBuilder.h" 60 #include "llvm/IR/InstrTypes.h" 61 #include "llvm/IR/Instruction.h" 62 #include "llvm/IR/Instructions.h" 63 #include "llvm/IR/IntrinsicInst.h" 64 #include "llvm/IR/Intrinsics.h" 65 #include "llvm/IR/Module.h" 66 #include "llvm/IR/Operator.h" 67 #include "llvm/IR/PatternMatch.h" 68 #include "llvm/IR/Type.h" 69 #include "llvm/IR/Use.h" 70 #include "llvm/IR/User.h" 71 #include "llvm/IR/Value.h" 72 #include "llvm/IR/ValueHandle.h" 73 #ifdef EXPENSIVE_CHECKS 74 #include "llvm/IR/Verifier.h" 75 #endif 76 #include "llvm/Pass.h" 77 #include "llvm/Support/Casting.h" 78 #include "llvm/Support/CommandLine.h" 79 #include "llvm/Support/Compiler.h" 80 #include "llvm/Support/DOTGraphTraits.h" 81 #include "llvm/Support/Debug.h" 82 #include "llvm/Support/ErrorHandling.h" 83 #include "llvm/Support/GraphWriter.h" 84 #include "llvm/Support/InstructionCost.h" 85 #include "llvm/Support/KnownBits.h" 86 #include "llvm/Support/MathExtras.h" 87 #include "llvm/Support/raw_ostream.h" 88 #include "llvm/Transforms/Utils/InjectTLIMappings.h" 89 #include "llvm/Transforms/Utils/Local.h" 90 #include "llvm/Transforms/Utils/LoopUtils.h" 91 #include "llvm/Transforms/Vectorize.h" 92 #include <algorithm> 93 #include <cassert> 94 #include <cstdint> 95 #include <iterator> 96 #include <memory> 97 #include <set> 98 #include <string> 99 #include <tuple> 100 #include <utility> 101 #include <vector> 102 103 using namespace llvm; 104 using namespace llvm::PatternMatch; 105 using namespace slpvectorizer; 106 107 #define SV_NAME "slp-vectorizer" 108 #define DEBUG_TYPE "SLP" 109 110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated"); 111 112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden, 113 cl::desc("Run the SLP vectorization passes")); 114 115 static cl::opt<int> 116 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden, 117 cl::desc("Only vectorize if you gain more than this " 118 "number ")); 119 120 static cl::opt<bool> 121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden, 122 cl::desc("Attempt to vectorize horizontal reductions")); 123 124 static cl::opt<bool> ShouldStartVectorizeHorAtStore( 125 "slp-vectorize-hor-store", cl::init(false), cl::Hidden, 126 cl::desc( 127 "Attempt to vectorize horizontal reductions feeding into a store")); 128 129 static cl::opt<int> 130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden, 131 cl::desc("Attempt to vectorize for this register size in bits")); 132 133 static cl::opt<unsigned> 134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden, 135 cl::desc("Maximum SLP vectorization factor (0=unlimited)")); 136 137 static cl::opt<int> 138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden, 139 cl::desc("Maximum depth of the lookup for consecutive stores.")); 140 141 /// Limits the size of scheduling regions in a block. 142 /// It avoid long compile times for _very_ large blocks where vector 143 /// instructions are spread over a wide range. 144 /// This limit is way higher than needed by real-world functions. 145 static cl::opt<int> 146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden, 147 cl::desc("Limit the size of the SLP scheduling region per block")); 148 149 static cl::opt<int> MinVectorRegSizeOption( 150 "slp-min-reg-size", cl::init(128), cl::Hidden, 151 cl::desc("Attempt to vectorize for this register size in bits")); 152 153 static cl::opt<unsigned> RecursionMaxDepth( 154 "slp-recursion-max-depth", cl::init(12), cl::Hidden, 155 cl::desc("Limit the recursion depth when building a vectorizable tree")); 156 157 static cl::opt<unsigned> MinTreeSize( 158 "slp-min-tree-size", cl::init(3), cl::Hidden, 159 cl::desc("Only vectorize small trees if they are fully vectorizable")); 160 161 // The maximum depth that the look-ahead score heuristic will explore. 162 // The higher this value, the higher the compilation time overhead. 163 static cl::opt<int> LookAheadMaxDepth( 164 "slp-max-look-ahead-depth", cl::init(2), cl::Hidden, 165 cl::desc("The maximum look-ahead depth for operand reordering scores")); 166 167 // The maximum depth that the look-ahead score heuristic will explore 168 // when it probing among candidates for vectorization tree roots. 169 // The higher this value, the higher the compilation time overhead but unlike 170 // similar limit for operands ordering this is less frequently used, hence 171 // impact of higher value is less noticeable. 172 static cl::opt<int> RootLookAheadMaxDepth( 173 "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden, 174 cl::desc("The maximum look-ahead depth for searching best rooting option")); 175 176 static cl::opt<bool> 177 ViewSLPTree("view-slp-tree", cl::Hidden, 178 cl::desc("Display the SLP trees with Graphviz")); 179 180 // Limit the number of alias checks. The limit is chosen so that 181 // it has no negative effect on the llvm benchmarks. 182 static const unsigned AliasedCheckLimit = 10; 183 184 // Another limit for the alias checks: The maximum distance between load/store 185 // instructions where alias checks are done. 186 // This limit is useful for very large basic blocks. 187 static const unsigned MaxMemDepDistance = 160; 188 189 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling 190 /// regions to be handled. 191 static const int MinScheduleRegionSize = 16; 192 193 /// Predicate for the element types that the SLP vectorizer supports. 194 /// 195 /// The most important thing to filter here are types which are invalid in LLVM 196 /// vectors. We also filter target specific types which have absolutely no 197 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just 198 /// avoids spending time checking the cost model and realizing that they will 199 /// be inevitably scalarized. 200 static bool isValidElementType(Type *Ty) { 201 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() && 202 !Ty->isPPC_FP128Ty(); 203 } 204 205 /// \returns True if the value is a constant (but not globals/constant 206 /// expressions). 207 static bool isConstant(Value *V) { 208 return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V); 209 } 210 211 /// Checks if \p V is one of vector-like instructions, i.e. undef, 212 /// insertelement/extractelement with constant indices for fixed vector type or 213 /// extractvalue instruction. 214 static bool isVectorLikeInstWithConstOps(Value *V) { 215 if (!isa<InsertElementInst, ExtractElementInst>(V) && 216 !isa<ExtractValueInst, UndefValue>(V)) 217 return false; 218 auto *I = dyn_cast<Instruction>(V); 219 if (!I || isa<ExtractValueInst>(I)) 220 return true; 221 if (!isa<FixedVectorType>(I->getOperand(0)->getType())) 222 return false; 223 if (isa<ExtractElementInst>(I)) 224 return isConstant(I->getOperand(1)); 225 assert(isa<InsertElementInst>(V) && "Expected only insertelement."); 226 return isConstant(I->getOperand(2)); 227 } 228 229 /// \returns true if all of the instructions in \p VL are in the same block or 230 /// false otherwise. 231 static bool allSameBlock(ArrayRef<Value *> VL) { 232 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 233 if (!I0) 234 return false; 235 if (all_of(VL, isVectorLikeInstWithConstOps)) 236 return true; 237 238 BasicBlock *BB = I0->getParent(); 239 for (int I = 1, E = VL.size(); I < E; I++) { 240 auto *II = dyn_cast<Instruction>(VL[I]); 241 if (!II) 242 return false; 243 244 if (BB != II->getParent()) 245 return false; 246 } 247 return true; 248 } 249 250 /// \returns True if all of the values in \p VL are constants (but not 251 /// globals/constant expressions). 252 static bool allConstant(ArrayRef<Value *> VL) { 253 // Constant expressions and globals can't be vectorized like normal integer/FP 254 // constants. 255 return all_of(VL, isConstant); 256 } 257 258 /// \returns True if all of the values in \p VL are identical or some of them 259 /// are UndefValue. 260 static bool isSplat(ArrayRef<Value *> VL) { 261 Value *FirstNonUndef = nullptr; 262 for (Value *V : VL) { 263 if (isa<UndefValue>(V)) 264 continue; 265 if (!FirstNonUndef) { 266 FirstNonUndef = V; 267 continue; 268 } 269 if (V != FirstNonUndef) 270 return false; 271 } 272 return FirstNonUndef != nullptr; 273 } 274 275 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator. 276 static bool isCommutative(Instruction *I) { 277 if (auto *Cmp = dyn_cast<CmpInst>(I)) 278 return Cmp->isCommutative(); 279 if (auto *BO = dyn_cast<BinaryOperator>(I)) 280 return BO->isCommutative(); 281 // TODO: This should check for generic Instruction::isCommutative(), but 282 // we need to confirm that the caller code correctly handles Intrinsics 283 // for example (does not have 2 operands). 284 return false; 285 } 286 287 /// Checks if the given value is actually an undefined constant vector. 288 static bool isUndefVector(const Value *V) { 289 if (isa<UndefValue>(V)) 290 return true; 291 auto *C = dyn_cast<Constant>(V); 292 if (!C) 293 return false; 294 if (!C->containsUndefOrPoisonElement()) 295 return false; 296 auto *VecTy = dyn_cast<FixedVectorType>(C->getType()); 297 if (!VecTy) 298 return false; 299 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) { 300 if (Constant *Elem = C->getAggregateElement(I)) 301 if (!isa<UndefValue>(Elem)) 302 return false; 303 } 304 return true; 305 } 306 307 /// Checks if the vector of instructions can be represented as a shuffle, like: 308 /// %x0 = extractelement <4 x i8> %x, i32 0 309 /// %x3 = extractelement <4 x i8> %x, i32 3 310 /// %y1 = extractelement <4 x i8> %y, i32 1 311 /// %y2 = extractelement <4 x i8> %y, i32 2 312 /// %x0x0 = mul i8 %x0, %x0 313 /// %x3x3 = mul i8 %x3, %x3 314 /// %y1y1 = mul i8 %y1, %y1 315 /// %y2y2 = mul i8 %y2, %y2 316 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0 317 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1 318 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2 319 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3 320 /// ret <4 x i8> %ins4 321 /// can be transformed into: 322 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5, 323 /// i32 6> 324 /// %2 = mul <4 x i8> %1, %1 325 /// ret <4 x i8> %2 326 /// We convert this initially to something like: 327 /// %x0 = extractelement <4 x i8> %x, i32 0 328 /// %x3 = extractelement <4 x i8> %x, i32 3 329 /// %y1 = extractelement <4 x i8> %y, i32 1 330 /// %y2 = extractelement <4 x i8> %y, i32 2 331 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0 332 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1 333 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2 334 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3 335 /// %5 = mul <4 x i8> %4, %4 336 /// %6 = extractelement <4 x i8> %5, i32 0 337 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0 338 /// %7 = extractelement <4 x i8> %5, i32 1 339 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1 340 /// %8 = extractelement <4 x i8> %5, i32 2 341 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2 342 /// %9 = extractelement <4 x i8> %5, i32 3 343 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3 344 /// ret <4 x i8> %ins4 345 /// InstCombiner transforms this into a shuffle and vector mul 346 /// Mask will return the Shuffle Mask equivalent to the extracted elements. 347 /// TODO: Can we split off and reuse the shuffle mask detection from 348 /// TargetTransformInfo::getInstructionThroughput? 349 static Optional<TargetTransformInfo::ShuffleKind> 350 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) { 351 const auto *It = 352 find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); }); 353 if (It == VL.end()) 354 return None; 355 auto *EI0 = cast<ExtractElementInst>(*It); 356 if (isa<ScalableVectorType>(EI0->getVectorOperandType())) 357 return None; 358 unsigned Size = 359 cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements(); 360 Value *Vec1 = nullptr; 361 Value *Vec2 = nullptr; 362 enum ShuffleMode { Unknown, Select, Permute }; 363 ShuffleMode CommonShuffleMode = Unknown; 364 Mask.assign(VL.size(), UndefMaskElem); 365 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 366 // Undef can be represented as an undef element in a vector. 367 if (isa<UndefValue>(VL[I])) 368 continue; 369 auto *EI = cast<ExtractElementInst>(VL[I]); 370 if (isa<ScalableVectorType>(EI->getVectorOperandType())) 371 return None; 372 auto *Vec = EI->getVectorOperand(); 373 // We can extractelement from undef or poison vector. 374 if (isUndefVector(Vec)) 375 continue; 376 // All vector operands must have the same number of vector elements. 377 if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size) 378 return None; 379 if (isa<UndefValue>(EI->getIndexOperand())) 380 continue; 381 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand()); 382 if (!Idx) 383 return None; 384 // Undefined behavior if Idx is negative or >= Size. 385 if (Idx->getValue().uge(Size)) 386 continue; 387 unsigned IntIdx = Idx->getValue().getZExtValue(); 388 Mask[I] = IntIdx; 389 // For correct shuffling we have to have at most 2 different vector operands 390 // in all extractelement instructions. 391 if (!Vec1 || Vec1 == Vec) { 392 Vec1 = Vec; 393 } else if (!Vec2 || Vec2 == Vec) { 394 Vec2 = Vec; 395 Mask[I] += Size; 396 } else { 397 return None; 398 } 399 if (CommonShuffleMode == Permute) 400 continue; 401 // If the extract index is not the same as the operation number, it is a 402 // permutation. 403 if (IntIdx != I) { 404 CommonShuffleMode = Permute; 405 continue; 406 } 407 CommonShuffleMode = Select; 408 } 409 // If we're not crossing lanes in different vectors, consider it as blending. 410 if (CommonShuffleMode == Select && Vec2) 411 return TargetTransformInfo::SK_Select; 412 // If Vec2 was never used, we have a permutation of a single vector, otherwise 413 // we have permutation of 2 vectors. 414 return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc 415 : TargetTransformInfo::SK_PermuteSingleSrc; 416 } 417 418 namespace { 419 420 /// Main data required for vectorization of instructions. 421 struct InstructionsState { 422 /// The very first instruction in the list with the main opcode. 423 Value *OpValue = nullptr; 424 425 /// The main/alternate instruction. 426 Instruction *MainOp = nullptr; 427 Instruction *AltOp = nullptr; 428 429 /// The main/alternate opcodes for the list of instructions. 430 unsigned getOpcode() const { 431 return MainOp ? MainOp->getOpcode() : 0; 432 } 433 434 unsigned getAltOpcode() const { 435 return AltOp ? AltOp->getOpcode() : 0; 436 } 437 438 /// Some of the instructions in the list have alternate opcodes. 439 bool isAltShuffle() const { return AltOp != MainOp; } 440 441 bool isOpcodeOrAlt(Instruction *I) const { 442 unsigned CheckedOpcode = I->getOpcode(); 443 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode; 444 } 445 446 InstructionsState() = delete; 447 InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp) 448 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {} 449 }; 450 451 } // end anonymous namespace 452 453 /// Chooses the correct key for scheduling data. If \p Op has the same (or 454 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p 455 /// OpValue. 456 static Value *isOneOf(const InstructionsState &S, Value *Op) { 457 auto *I = dyn_cast<Instruction>(Op); 458 if (I && S.isOpcodeOrAlt(I)) 459 return Op; 460 return S.OpValue; 461 } 462 463 /// \returns true if \p Opcode is allowed as part of of the main/alternate 464 /// instruction for SLP vectorization. 465 /// 466 /// Example of unsupported opcode is SDIV that can potentially cause UB if the 467 /// "shuffled out" lane would result in division by zero. 468 static bool isValidForAlternation(unsigned Opcode) { 469 if (Instruction::isIntDivRem(Opcode)) 470 return false; 471 472 return true; 473 } 474 475 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 476 unsigned BaseIndex = 0); 477 478 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e. 479 /// compatible instructions or constants, or just some other regular values. 480 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0, 481 Value *Op1) { 482 return (isConstant(BaseOp0) && isConstant(Op0)) || 483 (isConstant(BaseOp1) && isConstant(Op1)) || 484 (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) && 485 !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) || 486 getSameOpcode({BaseOp0, Op0}).getOpcode() || 487 getSameOpcode({BaseOp1, Op1}).getOpcode(); 488 } 489 490 /// \returns analysis of the Instructions in \p VL described in 491 /// InstructionsState, the Opcode that we suppose the whole list 492 /// could be vectorized even if its structure is diverse. 493 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 494 unsigned BaseIndex) { 495 // Make sure these are all Instructions. 496 if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); })) 497 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 498 499 bool IsCastOp = isa<CastInst>(VL[BaseIndex]); 500 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]); 501 bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]); 502 CmpInst::Predicate BasePred = 503 IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate() 504 : CmpInst::BAD_ICMP_PREDICATE; 505 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode(); 506 unsigned AltOpcode = Opcode; 507 unsigned AltIndex = BaseIndex; 508 509 // Check for one alternate opcode from another BinaryOperator. 510 // TODO - generalize to support all operators (types, calls etc.). 511 for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) { 512 unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode(); 513 if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) { 514 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 515 continue; 516 if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) && 517 isValidForAlternation(Opcode)) { 518 AltOpcode = InstOpcode; 519 AltIndex = Cnt; 520 continue; 521 } 522 } else if (IsCastOp && isa<CastInst>(VL[Cnt])) { 523 Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType(); 524 Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType(); 525 if (Ty0 == Ty1) { 526 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 527 continue; 528 if (Opcode == AltOpcode) { 529 assert(isValidForAlternation(Opcode) && 530 isValidForAlternation(InstOpcode) && 531 "Cast isn't safe for alternation, logic needs to be updated!"); 532 AltOpcode = InstOpcode; 533 AltIndex = Cnt; 534 continue; 535 } 536 } 537 } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) { 538 auto *BaseInst = cast<Instruction>(VL[BaseIndex]); 539 auto *Inst = cast<Instruction>(VL[Cnt]); 540 Type *Ty0 = BaseInst->getOperand(0)->getType(); 541 Type *Ty1 = Inst->getOperand(0)->getType(); 542 if (Ty0 == Ty1) { 543 Value *BaseOp0 = BaseInst->getOperand(0); 544 Value *BaseOp1 = BaseInst->getOperand(1); 545 Value *Op0 = Inst->getOperand(0); 546 Value *Op1 = Inst->getOperand(1); 547 CmpInst::Predicate CurrentPred = 548 cast<CmpInst>(VL[Cnt])->getPredicate(); 549 CmpInst::Predicate SwappedCurrentPred = 550 CmpInst::getSwappedPredicate(CurrentPred); 551 // Check for compatible operands. If the corresponding operands are not 552 // compatible - need to perform alternate vectorization. 553 if (InstOpcode == Opcode) { 554 if (BasePred == CurrentPred && 555 areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1)) 556 continue; 557 if (BasePred == SwappedCurrentPred && 558 areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0)) 559 continue; 560 if (E == 2 && 561 (BasePred == CurrentPred || BasePred == SwappedCurrentPred)) 562 continue; 563 auto *AltInst = cast<CmpInst>(VL[AltIndex]); 564 CmpInst::Predicate AltPred = AltInst->getPredicate(); 565 Value *AltOp0 = AltInst->getOperand(0); 566 Value *AltOp1 = AltInst->getOperand(1); 567 // Check if operands are compatible with alternate operands. 568 if (AltPred == CurrentPred && 569 areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1)) 570 continue; 571 if (AltPred == SwappedCurrentPred && 572 areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0)) 573 continue; 574 } 575 if (BaseIndex == AltIndex && BasePred != CurrentPred) { 576 assert(isValidForAlternation(Opcode) && 577 isValidForAlternation(InstOpcode) && 578 "Cast isn't safe for alternation, logic needs to be updated!"); 579 AltIndex = Cnt; 580 continue; 581 } 582 auto *AltInst = cast<CmpInst>(VL[AltIndex]); 583 CmpInst::Predicate AltPred = AltInst->getPredicate(); 584 if (BasePred == CurrentPred || BasePred == SwappedCurrentPred || 585 AltPred == CurrentPred || AltPred == SwappedCurrentPred) 586 continue; 587 } 588 } else if (InstOpcode == Opcode || InstOpcode == AltOpcode) 589 continue; 590 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 591 } 592 593 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]), 594 cast<Instruction>(VL[AltIndex])); 595 } 596 597 /// \returns true if all of the values in \p VL have the same type or false 598 /// otherwise. 599 static bool allSameType(ArrayRef<Value *> VL) { 600 Type *Ty = VL[0]->getType(); 601 for (int i = 1, e = VL.size(); i < e; i++) 602 if (VL[i]->getType() != Ty) 603 return false; 604 605 return true; 606 } 607 608 /// \returns True if Extract{Value,Element} instruction extracts element Idx. 609 static Optional<unsigned> getExtractIndex(Instruction *E) { 610 unsigned Opcode = E->getOpcode(); 611 assert((Opcode == Instruction::ExtractElement || 612 Opcode == Instruction::ExtractValue) && 613 "Expected extractelement or extractvalue instruction."); 614 if (Opcode == Instruction::ExtractElement) { 615 auto *CI = dyn_cast<ConstantInt>(E->getOperand(1)); 616 if (!CI) 617 return None; 618 return CI->getZExtValue(); 619 } 620 ExtractValueInst *EI = cast<ExtractValueInst>(E); 621 if (EI->getNumIndices() != 1) 622 return None; 623 return *EI->idx_begin(); 624 } 625 626 /// \returns True if in-tree use also needs extract. This refers to 627 /// possible scalar operand in vectorized instruction. 628 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, 629 TargetLibraryInfo *TLI) { 630 unsigned Opcode = UserInst->getOpcode(); 631 switch (Opcode) { 632 case Instruction::Load: { 633 LoadInst *LI = cast<LoadInst>(UserInst); 634 return (LI->getPointerOperand() == Scalar); 635 } 636 case Instruction::Store: { 637 StoreInst *SI = cast<StoreInst>(UserInst); 638 return (SI->getPointerOperand() == Scalar); 639 } 640 case Instruction::Call: { 641 CallInst *CI = cast<CallInst>(UserInst); 642 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 643 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 644 if (isVectorIntrinsicWithScalarOpAtArg(ID, i)) 645 return (CI->getArgOperand(i) == Scalar); 646 } 647 LLVM_FALLTHROUGH; 648 } 649 default: 650 return false; 651 } 652 } 653 654 /// \returns the AA location that is being access by the instruction. 655 static MemoryLocation getLocation(Instruction *I) { 656 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 657 return MemoryLocation::get(SI); 658 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 659 return MemoryLocation::get(LI); 660 return MemoryLocation(); 661 } 662 663 /// \returns True if the instruction is not a volatile or atomic load/store. 664 static bool isSimple(Instruction *I) { 665 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 666 return LI->isSimple(); 667 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 668 return SI->isSimple(); 669 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) 670 return !MI->isVolatile(); 671 return true; 672 } 673 674 /// Shuffles \p Mask in accordance with the given \p SubMask. 675 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) { 676 if (SubMask.empty()) 677 return; 678 if (Mask.empty()) { 679 Mask.append(SubMask.begin(), SubMask.end()); 680 return; 681 } 682 SmallVector<int> NewMask(SubMask.size(), UndefMaskElem); 683 int TermValue = std::min(Mask.size(), SubMask.size()); 684 for (int I = 0, E = SubMask.size(); I < E; ++I) { 685 if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem || 686 Mask[SubMask[I]] >= TermValue) 687 continue; 688 NewMask[I] = Mask[SubMask[I]]; 689 } 690 Mask.swap(NewMask); 691 } 692 693 /// Order may have elements assigned special value (size) which is out of 694 /// bounds. Such indices only appear on places which correspond to undef values 695 /// (see canReuseExtract for details) and used in order to avoid undef values 696 /// have effect on operands ordering. 697 /// The first loop below simply finds all unused indices and then the next loop 698 /// nest assigns these indices for undef values positions. 699 /// As an example below Order has two undef positions and they have assigned 700 /// values 3 and 7 respectively: 701 /// before: 6 9 5 4 9 2 1 0 702 /// after: 6 3 5 4 7 2 1 0 703 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) { 704 const unsigned Sz = Order.size(); 705 SmallBitVector UnusedIndices(Sz, /*t=*/true); 706 SmallBitVector MaskedIndices(Sz); 707 for (unsigned I = 0; I < Sz; ++I) { 708 if (Order[I] < Sz) 709 UnusedIndices.reset(Order[I]); 710 else 711 MaskedIndices.set(I); 712 } 713 if (MaskedIndices.none()) 714 return; 715 assert(UnusedIndices.count() == MaskedIndices.count() && 716 "Non-synced masked/available indices."); 717 int Idx = UnusedIndices.find_first(); 718 int MIdx = MaskedIndices.find_first(); 719 while (MIdx >= 0) { 720 assert(Idx >= 0 && "Indices must be synced."); 721 Order[MIdx] = Idx; 722 Idx = UnusedIndices.find_next(Idx); 723 MIdx = MaskedIndices.find_next(MIdx); 724 } 725 } 726 727 namespace llvm { 728 729 static void inversePermutation(ArrayRef<unsigned> Indices, 730 SmallVectorImpl<int> &Mask) { 731 Mask.clear(); 732 const unsigned E = Indices.size(); 733 Mask.resize(E, UndefMaskElem); 734 for (unsigned I = 0; I < E; ++I) 735 Mask[Indices[I]] = I; 736 } 737 738 /// \returns inserting index of InsertElement or InsertValue instruction, 739 /// using Offset as base offset for index. 740 static Optional<unsigned> getInsertIndex(const Value *InsertInst, 741 unsigned Offset = 0) { 742 int Index = Offset; 743 if (const auto *IE = dyn_cast<InsertElementInst>(InsertInst)) { 744 if (const auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) { 745 auto *VT = cast<FixedVectorType>(IE->getType()); 746 if (CI->getValue().uge(VT->getNumElements())) 747 return None; 748 Index *= VT->getNumElements(); 749 Index += CI->getZExtValue(); 750 return Index; 751 } 752 return None; 753 } 754 755 const auto *IV = cast<InsertValueInst>(InsertInst); 756 Type *CurrentType = IV->getType(); 757 for (unsigned I : IV->indices()) { 758 if (const auto *ST = dyn_cast<StructType>(CurrentType)) { 759 Index *= ST->getNumElements(); 760 CurrentType = ST->getElementType(I); 761 } else if (const auto *AT = dyn_cast<ArrayType>(CurrentType)) { 762 Index *= AT->getNumElements(); 763 CurrentType = AT->getElementType(); 764 } else { 765 return None; 766 } 767 Index += I; 768 } 769 return Index; 770 } 771 772 /// Reorders the list of scalars in accordance with the given \p Mask. 773 static void reorderScalars(SmallVectorImpl<Value *> &Scalars, 774 ArrayRef<int> Mask) { 775 assert(!Mask.empty() && "Expected non-empty mask."); 776 SmallVector<Value *> Prev(Scalars.size(), 777 UndefValue::get(Scalars.front()->getType())); 778 Prev.swap(Scalars); 779 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 780 if (Mask[I] != UndefMaskElem) 781 Scalars[Mask[I]] = Prev[I]; 782 } 783 784 /// Checks if the provided value does not require scheduling. It does not 785 /// require scheduling if this is not an instruction or it is an instruction 786 /// that does not read/write memory and all operands are either not instructions 787 /// or phi nodes or instructions from different blocks. 788 static bool areAllOperandsNonInsts(Value *V) { 789 auto *I = dyn_cast<Instruction>(V); 790 if (!I) 791 return true; 792 return !mayHaveNonDefUseDependency(*I) && 793 all_of(I->operands(), [I](Value *V) { 794 auto *IO = dyn_cast<Instruction>(V); 795 if (!IO) 796 return true; 797 return isa<PHINode>(IO) || IO->getParent() != I->getParent(); 798 }); 799 } 800 801 /// Checks if the provided value does not require scheduling. It does not 802 /// require scheduling if this is not an instruction or it is an instruction 803 /// that does not read/write memory and all users are phi nodes or instructions 804 /// from the different blocks. 805 static bool isUsedOutsideBlock(Value *V) { 806 auto *I = dyn_cast<Instruction>(V); 807 if (!I) 808 return true; 809 // Limits the number of uses to save compile time. 810 constexpr int UsesLimit = 8; 811 return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) && 812 all_of(I->users(), [I](User *U) { 813 auto *IU = dyn_cast<Instruction>(U); 814 if (!IU) 815 return true; 816 return IU->getParent() != I->getParent() || isa<PHINode>(IU); 817 }); 818 } 819 820 /// Checks if the specified value does not require scheduling. It does not 821 /// require scheduling if all operands and all users do not need to be scheduled 822 /// in the current basic block. 823 static bool doesNotNeedToBeScheduled(Value *V) { 824 return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V); 825 } 826 827 /// Checks if the specified array of instructions does not require scheduling. 828 /// It is so if all either instructions have operands that do not require 829 /// scheduling or their users do not require scheduling since they are phis or 830 /// in other basic blocks. 831 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) { 832 return !VL.empty() && 833 (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts)); 834 } 835 836 namespace slpvectorizer { 837 838 /// Bottom Up SLP Vectorizer. 839 class BoUpSLP { 840 struct TreeEntry; 841 struct ScheduleData; 842 843 public: 844 using ValueList = SmallVector<Value *, 8>; 845 using InstrList = SmallVector<Instruction *, 16>; 846 using ValueSet = SmallPtrSet<Value *, 16>; 847 using StoreList = SmallVector<StoreInst *, 8>; 848 using ExtraValueToDebugLocsMap = 849 MapVector<Value *, SmallVector<Instruction *, 2>>; 850 using OrdersType = SmallVector<unsigned, 4>; 851 852 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, 853 TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li, 854 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB, 855 const DataLayout *DL, OptimizationRemarkEmitter *ORE) 856 : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li), 857 DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) { 858 CodeMetrics::collectEphemeralValues(F, AC, EphValues); 859 // Use the vector register size specified by the target unless overridden 860 // by a command-line option. 861 // TODO: It would be better to limit the vectorization factor based on 862 // data type rather than just register size. For example, x86 AVX has 863 // 256-bit registers, but it does not support integer operations 864 // at that width (that requires AVX2). 865 if (MaxVectorRegSizeOption.getNumOccurrences()) 866 MaxVecRegSize = MaxVectorRegSizeOption; 867 else 868 MaxVecRegSize = 869 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) 870 .getFixedSize(); 871 872 if (MinVectorRegSizeOption.getNumOccurrences()) 873 MinVecRegSize = MinVectorRegSizeOption; 874 else 875 MinVecRegSize = TTI->getMinVectorRegisterBitWidth(); 876 } 877 878 /// Vectorize the tree that starts with the elements in \p VL. 879 /// Returns the vectorized root. 880 Value *vectorizeTree(); 881 882 /// Vectorize the tree but with the list of externally used values \p 883 /// ExternallyUsedValues. Values in this MapVector can be replaced but the 884 /// generated extractvalue instructions. 885 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues); 886 887 /// \returns the cost incurred by unwanted spills and fills, caused by 888 /// holding live values over call sites. 889 InstructionCost getSpillCost() const; 890 891 /// \returns the vectorization cost of the subtree that starts at \p VL. 892 /// A negative number means that this is profitable. 893 InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None); 894 895 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for 896 /// the purpose of scheduling and extraction in the \p UserIgnoreLst. 897 void buildTree(ArrayRef<Value *> Roots, 898 const SmallDenseSet<Value *> &UserIgnoreLst); 899 900 /// Construct a vectorizable tree that starts at \p Roots. 901 void buildTree(ArrayRef<Value *> Roots); 902 903 /// Builds external uses of the vectorized scalars, i.e. the list of 904 /// vectorized scalars to be extracted, their lanes and their scalar users. \p 905 /// ExternallyUsedValues contains additional list of external uses to handle 906 /// vectorization of reductions. 907 void 908 buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {}); 909 910 /// Clear the internal data structures that are created by 'buildTree'. 911 void deleteTree() { 912 VectorizableTree.clear(); 913 ScalarToTreeEntry.clear(); 914 MustGather.clear(); 915 ExternalUses.clear(); 916 for (auto &Iter : BlocksSchedules) { 917 BlockScheduling *BS = Iter.second.get(); 918 BS->clear(); 919 } 920 MinBWs.clear(); 921 InstrElementSize.clear(); 922 UserIgnoreList = nullptr; 923 } 924 925 unsigned getTreeSize() const { return VectorizableTree.size(); } 926 927 /// Perform LICM and CSE on the newly generated gather sequences. 928 void optimizeGatherSequence(); 929 930 /// Checks if the specified gather tree entry \p TE can be represented as a 931 /// shuffled vector entry + (possibly) permutation with other gathers. It 932 /// implements the checks only for possibly ordered scalars (Loads, 933 /// ExtractElement, ExtractValue), which can be part of the graph. 934 Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE); 935 936 /// Sort loads into increasing pointers offsets to allow greater clustering. 937 Optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE); 938 939 /// Gets reordering data for the given tree entry. If the entry is vectorized 940 /// - just return ReorderIndices, otherwise check if the scalars can be 941 /// reordered and return the most optimal order. 942 /// \param TopToBottom If true, include the order of vectorized stores and 943 /// insertelement nodes, otherwise skip them. 944 Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom); 945 946 /// Reorders the current graph to the most profitable order starting from the 947 /// root node to the leaf nodes. The best order is chosen only from the nodes 948 /// of the same size (vectorization factor). Smaller nodes are considered 949 /// parts of subgraph with smaller VF and they are reordered independently. We 950 /// can make it because we still need to extend smaller nodes to the wider VF 951 /// and we can merge reordering shuffles with the widening shuffles. 952 void reorderTopToBottom(); 953 954 /// Reorders the current graph to the most profitable order starting from 955 /// leaves to the root. It allows to rotate small subgraphs and reduce the 956 /// number of reshuffles if the leaf nodes use the same order. In this case we 957 /// can merge the orders and just shuffle user node instead of shuffling its 958 /// operands. Plus, even the leaf nodes have different orders, it allows to 959 /// sink reordering in the graph closer to the root node and merge it later 960 /// during analysis. 961 void reorderBottomToTop(bool IgnoreReorder = false); 962 963 /// \return The vector element size in bits to use when vectorizing the 964 /// expression tree ending at \p V. If V is a store, the size is the width of 965 /// the stored value. Otherwise, the size is the width of the largest loaded 966 /// value reaching V. This method is used by the vectorizer to calculate 967 /// vectorization factors. 968 unsigned getVectorElementSize(Value *V); 969 970 /// Compute the minimum type sizes required to represent the entries in a 971 /// vectorizable tree. 972 void computeMinimumValueSizes(); 973 974 // \returns maximum vector register size as set by TTI or overridden by cl::opt. 975 unsigned getMaxVecRegSize() const { 976 return MaxVecRegSize; 977 } 978 979 // \returns minimum vector register size as set by cl::opt. 980 unsigned getMinVecRegSize() const { 981 return MinVecRegSize; 982 } 983 984 unsigned getMinVF(unsigned Sz) const { 985 return std::max(2U, getMinVecRegSize() / Sz); 986 } 987 988 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const { 989 unsigned MaxVF = MaxVFOption.getNumOccurrences() ? 990 MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode); 991 return MaxVF ? MaxVF : UINT_MAX; 992 } 993 994 /// Check if homogeneous aggregate is isomorphic to some VectorType. 995 /// Accepts homogeneous multidimensional aggregate of scalars/vectors like 996 /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> }, 997 /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on. 998 /// 999 /// \returns number of elements in vector if isomorphism exists, 0 otherwise. 1000 unsigned canMapToVector(Type *T, const DataLayout &DL) const; 1001 1002 /// \returns True if the VectorizableTree is both tiny and not fully 1003 /// vectorizable. We do not vectorize such trees. 1004 bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const; 1005 1006 /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values 1007 /// can be load combined in the backend. Load combining may not be allowed in 1008 /// the IR optimizer, so we do not want to alter the pattern. For example, 1009 /// partially transforming a scalar bswap() pattern into vector code is 1010 /// effectively impossible for the backend to undo. 1011 /// TODO: If load combining is allowed in the IR optimizer, this analysis 1012 /// may not be necessary. 1013 bool isLoadCombineReductionCandidate(RecurKind RdxKind) const; 1014 1015 /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values 1016 /// can be load combined in the backend. Load combining may not be allowed in 1017 /// the IR optimizer, so we do not want to alter the pattern. For example, 1018 /// partially transforming a scalar bswap() pattern into vector code is 1019 /// effectively impossible for the backend to undo. 1020 /// TODO: If load combining is allowed in the IR optimizer, this analysis 1021 /// may not be necessary. 1022 bool isLoadCombineCandidate() const; 1023 1024 OptimizationRemarkEmitter *getORE() { return ORE; } 1025 1026 /// This structure holds any data we need about the edges being traversed 1027 /// during buildTree_rec(). We keep track of: 1028 /// (i) the user TreeEntry index, and 1029 /// (ii) the index of the edge. 1030 struct EdgeInfo { 1031 EdgeInfo() = default; 1032 EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx) 1033 : UserTE(UserTE), EdgeIdx(EdgeIdx) {} 1034 /// The user TreeEntry. 1035 TreeEntry *UserTE = nullptr; 1036 /// The operand index of the use. 1037 unsigned EdgeIdx = UINT_MAX; 1038 #ifndef NDEBUG 1039 friend inline raw_ostream &operator<<(raw_ostream &OS, 1040 const BoUpSLP::EdgeInfo &EI) { 1041 EI.dump(OS); 1042 return OS; 1043 } 1044 /// Debug print. 1045 void dump(raw_ostream &OS) const { 1046 OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null") 1047 << " EdgeIdx:" << EdgeIdx << "}"; 1048 } 1049 LLVM_DUMP_METHOD void dump() const { dump(dbgs()); } 1050 #endif 1051 }; 1052 1053 /// A helper class used for scoring candidates for two consecutive lanes. 1054 class LookAheadHeuristics { 1055 const DataLayout &DL; 1056 ScalarEvolution &SE; 1057 const BoUpSLP &R; 1058 int NumLanes; // Total number of lanes (aka vectorization factor). 1059 int MaxLevel; // The maximum recursion depth for accumulating score. 1060 1061 public: 1062 LookAheadHeuristics(const DataLayout &DL, ScalarEvolution &SE, 1063 const BoUpSLP &R, int NumLanes, int MaxLevel) 1064 : DL(DL), SE(SE), R(R), NumLanes(NumLanes), MaxLevel(MaxLevel) {} 1065 1066 // The hard-coded scores listed here are not very important, though it shall 1067 // be higher for better matches to improve the resulting cost. When 1068 // computing the scores of matching one sub-tree with another, we are 1069 // basically counting the number of values that are matching. So even if all 1070 // scores are set to 1, we would still get a decent matching result. 1071 // However, sometimes we have to break ties. For example we may have to 1072 // choose between matching loads vs matching opcodes. This is what these 1073 // scores are helping us with: they provide the order of preference. Also, 1074 // this is important if the scalar is externally used or used in another 1075 // tree entry node in the different lane. 1076 1077 /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]). 1078 static const int ScoreConsecutiveLoads = 4; 1079 /// The same load multiple times. This should have a better score than 1080 /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it 1081 /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for 1082 /// a vector load and 1.0 for a broadcast. 1083 static const int ScoreSplatLoads = 3; 1084 /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]). 1085 static const int ScoreReversedLoads = 3; 1086 /// ExtractElementInst from same vector and consecutive indexes. 1087 static const int ScoreConsecutiveExtracts = 4; 1088 /// ExtractElementInst from same vector and reversed indices. 1089 static const int ScoreReversedExtracts = 3; 1090 /// Constants. 1091 static const int ScoreConstants = 2; 1092 /// Instructions with the same opcode. 1093 static const int ScoreSameOpcode = 2; 1094 /// Instructions with alt opcodes (e.g, add + sub). 1095 static const int ScoreAltOpcodes = 1; 1096 /// Identical instructions (a.k.a. splat or broadcast). 1097 static const int ScoreSplat = 1; 1098 /// Matching with an undef is preferable to failing. 1099 static const int ScoreUndef = 1; 1100 /// Score for failing to find a decent match. 1101 static const int ScoreFail = 0; 1102 /// Score if all users are vectorized. 1103 static const int ScoreAllUserVectorized = 1; 1104 1105 /// \returns the score of placing \p V1 and \p V2 in consecutive lanes. 1106 /// \p U1 and \p U2 are the users of \p V1 and \p V2. 1107 /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p 1108 /// MainAltOps. 1109 int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2, 1110 ArrayRef<Value *> MainAltOps) const { 1111 if (V1 == V2) { 1112 if (isa<LoadInst>(V1)) { 1113 // Retruns true if the users of V1 and V2 won't need to be extracted. 1114 auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) { 1115 // Bail out if we have too many uses to save compilation time. 1116 static constexpr unsigned Limit = 8; 1117 if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit)) 1118 return false; 1119 1120 auto AllUsersVectorized = [U1, U2, this](Value *V) { 1121 return llvm::all_of(V->users(), [U1, U2, this](Value *U) { 1122 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr; 1123 }); 1124 }; 1125 return AllUsersVectorized(V1) && AllUsersVectorized(V2); 1126 }; 1127 // A broadcast of a load can be cheaper on some targets. 1128 if (R.TTI->isLegalBroadcastLoad(V1->getType(), 1129 ElementCount::getFixed(NumLanes)) && 1130 ((int)V1->getNumUses() == NumLanes || 1131 AllUsersAreInternal(V1, V2))) 1132 return LookAheadHeuristics::ScoreSplatLoads; 1133 } 1134 return LookAheadHeuristics::ScoreSplat; 1135 } 1136 1137 auto *LI1 = dyn_cast<LoadInst>(V1); 1138 auto *LI2 = dyn_cast<LoadInst>(V2); 1139 if (LI1 && LI2) { 1140 if (LI1->getParent() != LI2->getParent()) 1141 return LookAheadHeuristics::ScoreFail; 1142 1143 Optional<int> Dist = getPointersDiff( 1144 LI1->getType(), LI1->getPointerOperand(), LI2->getType(), 1145 LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true); 1146 if (!Dist || *Dist == 0) 1147 return LookAheadHeuristics::ScoreFail; 1148 // The distance is too large - still may be profitable to use masked 1149 // loads/gathers. 1150 if (std::abs(*Dist) > NumLanes / 2) 1151 return LookAheadHeuristics::ScoreAltOpcodes; 1152 // This still will detect consecutive loads, but we might have "holes" 1153 // in some cases. It is ok for non-power-2 vectorization and may produce 1154 // better results. It should not affect current vectorization. 1155 return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads 1156 : LookAheadHeuristics::ScoreReversedLoads; 1157 } 1158 1159 auto *C1 = dyn_cast<Constant>(V1); 1160 auto *C2 = dyn_cast<Constant>(V2); 1161 if (C1 && C2) 1162 return LookAheadHeuristics::ScoreConstants; 1163 1164 // Extracts from consecutive indexes of the same vector better score as 1165 // the extracts could be optimized away. 1166 Value *EV1; 1167 ConstantInt *Ex1Idx; 1168 if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) { 1169 // Undefs are always profitable for extractelements. 1170 if (isa<UndefValue>(V2)) 1171 return LookAheadHeuristics::ScoreConsecutiveExtracts; 1172 Value *EV2 = nullptr; 1173 ConstantInt *Ex2Idx = nullptr; 1174 if (match(V2, 1175 m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx), 1176 m_Undef())))) { 1177 // Undefs are always profitable for extractelements. 1178 if (!Ex2Idx) 1179 return LookAheadHeuristics::ScoreConsecutiveExtracts; 1180 if (isUndefVector(EV2) && EV2->getType() == EV1->getType()) 1181 return LookAheadHeuristics::ScoreConsecutiveExtracts; 1182 if (EV2 == EV1) { 1183 int Idx1 = Ex1Idx->getZExtValue(); 1184 int Idx2 = Ex2Idx->getZExtValue(); 1185 int Dist = Idx2 - Idx1; 1186 // The distance is too large - still may be profitable to use 1187 // shuffles. 1188 if (std::abs(Dist) == 0) 1189 return LookAheadHeuristics::ScoreSplat; 1190 if (std::abs(Dist) > NumLanes / 2) 1191 return LookAheadHeuristics::ScoreSameOpcode; 1192 return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts 1193 : LookAheadHeuristics::ScoreReversedExtracts; 1194 } 1195 return LookAheadHeuristics::ScoreAltOpcodes; 1196 } 1197 return LookAheadHeuristics::ScoreFail; 1198 } 1199 1200 auto *I1 = dyn_cast<Instruction>(V1); 1201 auto *I2 = dyn_cast<Instruction>(V2); 1202 if (I1 && I2) { 1203 if (I1->getParent() != I2->getParent()) 1204 return LookAheadHeuristics::ScoreFail; 1205 SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end()); 1206 Ops.push_back(I1); 1207 Ops.push_back(I2); 1208 InstructionsState S = getSameOpcode(Ops); 1209 // Note: Only consider instructions with <= 2 operands to avoid 1210 // complexity explosion. 1211 if (S.getOpcode() && 1212 (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() || 1213 !S.isAltShuffle()) && 1214 all_of(Ops, [&S](Value *V) { 1215 return cast<Instruction>(V)->getNumOperands() == 1216 S.MainOp->getNumOperands(); 1217 })) 1218 return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes 1219 : LookAheadHeuristics::ScoreSameOpcode; 1220 } 1221 1222 if (isa<UndefValue>(V2)) 1223 return LookAheadHeuristics::ScoreUndef; 1224 1225 return LookAheadHeuristics::ScoreFail; 1226 } 1227 1228 /// Go through the operands of \p LHS and \p RHS recursively until 1229 /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are 1230 /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands 1231 /// of \p U1 and \p U2), except at the beginning of the recursion where 1232 /// these are set to nullptr. 1233 /// 1234 /// For example: 1235 /// \verbatim 1236 /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1] 1237 /// \ / \ / \ / \ / 1238 /// + + + + 1239 /// G1 G2 G3 G4 1240 /// \endverbatim 1241 /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at 1242 /// each level recursively, accumulating the score. It starts from matching 1243 /// the additions at level 0, then moves on to the loads (level 1). The 1244 /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and 1245 /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while 1246 /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail. 1247 /// Please note that the order of the operands does not matter, as we 1248 /// evaluate the score of all profitable combinations of operands. In 1249 /// other words the score of G1 and G4 is the same as G1 and G2. This 1250 /// heuristic is based on ideas described in: 1251 /// Look-ahead SLP: Auto-vectorization in the presence of commutative 1252 /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha, 1253 /// Luís F. W. Góes 1254 int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1, 1255 Instruction *U2, int CurrLevel, 1256 ArrayRef<Value *> MainAltOps) const { 1257 1258 // Get the shallow score of V1 and V2. 1259 int ShallowScoreAtThisLevel = 1260 getShallowScore(LHS, RHS, U1, U2, MainAltOps); 1261 1262 // If reached MaxLevel, 1263 // or if V1 and V2 are not instructions, 1264 // or if they are SPLAT, 1265 // or if they are not consecutive, 1266 // or if profitable to vectorize loads or extractelements, early return 1267 // the current cost. 1268 auto *I1 = dyn_cast<Instruction>(LHS); 1269 auto *I2 = dyn_cast<Instruction>(RHS); 1270 if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 || 1271 ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail || 1272 (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) || 1273 (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) || 1274 (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) && 1275 ShallowScoreAtThisLevel)) 1276 return ShallowScoreAtThisLevel; 1277 assert(I1 && I2 && "Should have early exited."); 1278 1279 // Contains the I2 operand indexes that got matched with I1 operands. 1280 SmallSet<unsigned, 4> Op2Used; 1281 1282 // Recursion towards the operands of I1 and I2. We are trying all possible 1283 // operand pairs, and keeping track of the best score. 1284 for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands(); 1285 OpIdx1 != NumOperands1; ++OpIdx1) { 1286 // Try to pair op1I with the best operand of I2. 1287 int MaxTmpScore = 0; 1288 unsigned MaxOpIdx2 = 0; 1289 bool FoundBest = false; 1290 // If I2 is commutative try all combinations. 1291 unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1; 1292 unsigned ToIdx = isCommutative(I2) 1293 ? I2->getNumOperands() 1294 : std::min(I2->getNumOperands(), OpIdx1 + 1); 1295 assert(FromIdx <= ToIdx && "Bad index"); 1296 for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) { 1297 // Skip operands already paired with OpIdx1. 1298 if (Op2Used.count(OpIdx2)) 1299 continue; 1300 // Recursively calculate the cost at each level 1301 int TmpScore = 1302 getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2), 1303 I1, I2, CurrLevel + 1, None); 1304 // Look for the best score. 1305 if (TmpScore > LookAheadHeuristics::ScoreFail && 1306 TmpScore > MaxTmpScore) { 1307 MaxTmpScore = TmpScore; 1308 MaxOpIdx2 = OpIdx2; 1309 FoundBest = true; 1310 } 1311 } 1312 if (FoundBest) { 1313 // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it. 1314 Op2Used.insert(MaxOpIdx2); 1315 ShallowScoreAtThisLevel += MaxTmpScore; 1316 } 1317 } 1318 return ShallowScoreAtThisLevel; 1319 } 1320 }; 1321 /// A helper data structure to hold the operands of a vector of instructions. 1322 /// This supports a fixed vector length for all operand vectors. 1323 class VLOperands { 1324 /// For each operand we need (i) the value, and (ii) the opcode that it 1325 /// would be attached to if the expression was in a left-linearized form. 1326 /// This is required to avoid illegal operand reordering. 1327 /// For example: 1328 /// \verbatim 1329 /// 0 Op1 1330 /// |/ 1331 /// Op1 Op2 Linearized + Op2 1332 /// \ / ----------> |/ 1333 /// - - 1334 /// 1335 /// Op1 - Op2 (0 + Op1) - Op2 1336 /// \endverbatim 1337 /// 1338 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'. 1339 /// 1340 /// Another way to think of this is to track all the operations across the 1341 /// path from the operand all the way to the root of the tree and to 1342 /// calculate the operation that corresponds to this path. For example, the 1343 /// path from Op2 to the root crosses the RHS of the '-', therefore the 1344 /// corresponding operation is a '-' (which matches the one in the 1345 /// linearized tree, as shown above). 1346 /// 1347 /// For lack of a better term, we refer to this operation as Accumulated 1348 /// Path Operation (APO). 1349 struct OperandData { 1350 OperandData() = default; 1351 OperandData(Value *V, bool APO, bool IsUsed) 1352 : V(V), APO(APO), IsUsed(IsUsed) {} 1353 /// The operand value. 1354 Value *V = nullptr; 1355 /// TreeEntries only allow a single opcode, or an alternate sequence of 1356 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the 1357 /// APO. It is set to 'true' if 'V' is attached to an inverse operation 1358 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise 1359 /// (e.g., Add/Mul) 1360 bool APO = false; 1361 /// Helper data for the reordering function. 1362 bool IsUsed = false; 1363 }; 1364 1365 /// During operand reordering, we are trying to select the operand at lane 1366 /// that matches best with the operand at the neighboring lane. Our 1367 /// selection is based on the type of value we are looking for. For example, 1368 /// if the neighboring lane has a load, we need to look for a load that is 1369 /// accessing a consecutive address. These strategies are summarized in the 1370 /// 'ReorderingMode' enumerator. 1371 enum class ReorderingMode { 1372 Load, ///< Matching loads to consecutive memory addresses 1373 Opcode, ///< Matching instructions based on opcode (same or alternate) 1374 Constant, ///< Matching constants 1375 Splat, ///< Matching the same instruction multiple times (broadcast) 1376 Failed, ///< We failed to create a vectorizable group 1377 }; 1378 1379 using OperandDataVec = SmallVector<OperandData, 2>; 1380 1381 /// A vector of operand vectors. 1382 SmallVector<OperandDataVec, 4> OpsVec; 1383 1384 const DataLayout &DL; 1385 ScalarEvolution &SE; 1386 const BoUpSLP &R; 1387 1388 /// \returns the operand data at \p OpIdx and \p Lane. 1389 OperandData &getData(unsigned OpIdx, unsigned Lane) { 1390 return OpsVec[OpIdx][Lane]; 1391 } 1392 1393 /// \returns the operand data at \p OpIdx and \p Lane. Const version. 1394 const OperandData &getData(unsigned OpIdx, unsigned Lane) const { 1395 return OpsVec[OpIdx][Lane]; 1396 } 1397 1398 /// Clears the used flag for all entries. 1399 void clearUsed() { 1400 for (unsigned OpIdx = 0, NumOperands = getNumOperands(); 1401 OpIdx != NumOperands; ++OpIdx) 1402 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes; 1403 ++Lane) 1404 OpsVec[OpIdx][Lane].IsUsed = false; 1405 } 1406 1407 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2. 1408 void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) { 1409 std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]); 1410 } 1411 1412 /// \param Lane lane of the operands under analysis. 1413 /// \param OpIdx operand index in \p Lane lane we're looking the best 1414 /// candidate for. 1415 /// \param Idx operand index of the current candidate value. 1416 /// \returns The additional score due to possible broadcasting of the 1417 /// elements in the lane. It is more profitable to have power-of-2 unique 1418 /// elements in the lane, it will be vectorized with higher probability 1419 /// after removing duplicates. Currently the SLP vectorizer supports only 1420 /// vectorization of the power-of-2 number of unique scalars. 1421 int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { 1422 Value *IdxLaneV = getData(Idx, Lane).V; 1423 if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V) 1424 return 0; 1425 SmallPtrSet<Value *, 4> Uniques; 1426 for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) { 1427 if (Ln == Lane) 1428 continue; 1429 Value *OpIdxLnV = getData(OpIdx, Ln).V; 1430 if (!isa<Instruction>(OpIdxLnV)) 1431 return 0; 1432 Uniques.insert(OpIdxLnV); 1433 } 1434 int UniquesCount = Uniques.size(); 1435 int UniquesCntWithIdxLaneV = 1436 Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1; 1437 Value *OpIdxLaneV = getData(OpIdx, Lane).V; 1438 int UniquesCntWithOpIdxLaneV = 1439 Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1; 1440 if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV) 1441 return 0; 1442 return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) - 1443 UniquesCntWithOpIdxLaneV) - 1444 (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV); 1445 } 1446 1447 /// \param Lane lane of the operands under analysis. 1448 /// \param OpIdx operand index in \p Lane lane we're looking the best 1449 /// candidate for. 1450 /// \param Idx operand index of the current candidate value. 1451 /// \returns The additional score for the scalar which users are all 1452 /// vectorized. 1453 int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { 1454 Value *IdxLaneV = getData(Idx, Lane).V; 1455 Value *OpIdxLaneV = getData(OpIdx, Lane).V; 1456 // Do not care about number of uses for vector-like instructions 1457 // (extractelement/extractvalue with constant indices), they are extracts 1458 // themselves and already externally used. Vectorization of such 1459 // instructions does not add extra extractelement instruction, just may 1460 // remove it. 1461 if (isVectorLikeInstWithConstOps(IdxLaneV) && 1462 isVectorLikeInstWithConstOps(OpIdxLaneV)) 1463 return LookAheadHeuristics::ScoreAllUserVectorized; 1464 auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV); 1465 if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV)) 1466 return 0; 1467 return R.areAllUsersVectorized(IdxLaneI, None) 1468 ? LookAheadHeuristics::ScoreAllUserVectorized 1469 : 0; 1470 } 1471 1472 /// Score scaling factor for fully compatible instructions but with 1473 /// different number of external uses. Allows better selection of the 1474 /// instructions with less external uses. 1475 static const int ScoreScaleFactor = 10; 1476 1477 /// \Returns the look-ahead score, which tells us how much the sub-trees 1478 /// rooted at \p LHS and \p RHS match, the more they match the higher the 1479 /// score. This helps break ties in an informed way when we cannot decide on 1480 /// the order of the operands by just considering the immediate 1481 /// predecessors. 1482 int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps, 1483 int Lane, unsigned OpIdx, unsigned Idx, 1484 bool &IsUsed) { 1485 LookAheadHeuristics LookAhead(DL, SE, R, getNumLanes(), 1486 LookAheadMaxDepth); 1487 // Keep track of the instruction stack as we recurse into the operands 1488 // during the look-ahead score exploration. 1489 int Score = 1490 LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr, 1491 /*CurrLevel=*/1, MainAltOps); 1492 if (Score) { 1493 int SplatScore = getSplatScore(Lane, OpIdx, Idx); 1494 if (Score <= -SplatScore) { 1495 // Set the minimum score for splat-like sequence to avoid setting 1496 // failed state. 1497 Score = 1; 1498 } else { 1499 Score += SplatScore; 1500 // Scale score to see the difference between different operands 1501 // and similar operands but all vectorized/not all vectorized 1502 // uses. It does not affect actual selection of the best 1503 // compatible operand in general, just allows to select the 1504 // operand with all vectorized uses. 1505 Score *= ScoreScaleFactor; 1506 Score += getExternalUseScore(Lane, OpIdx, Idx); 1507 IsUsed = true; 1508 } 1509 } 1510 return Score; 1511 } 1512 1513 /// Best defined scores per lanes between the passes. Used to choose the 1514 /// best operand (with the highest score) between the passes. 1515 /// The key - {Operand Index, Lane}. 1516 /// The value - the best score between the passes for the lane and the 1517 /// operand. 1518 SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8> 1519 BestScoresPerLanes; 1520 1521 // Search all operands in Ops[*][Lane] for the one that matches best 1522 // Ops[OpIdx][LastLane] and return its opreand index. 1523 // If no good match can be found, return None. 1524 Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane, 1525 ArrayRef<ReorderingMode> ReorderingModes, 1526 ArrayRef<Value *> MainAltOps) { 1527 unsigned NumOperands = getNumOperands(); 1528 1529 // The operand of the previous lane at OpIdx. 1530 Value *OpLastLane = getData(OpIdx, LastLane).V; 1531 1532 // Our strategy mode for OpIdx. 1533 ReorderingMode RMode = ReorderingModes[OpIdx]; 1534 if (RMode == ReorderingMode::Failed) 1535 return None; 1536 1537 // The linearized opcode of the operand at OpIdx, Lane. 1538 bool OpIdxAPO = getData(OpIdx, Lane).APO; 1539 1540 // The best operand index and its score. 1541 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we 1542 // are using the score to differentiate between the two. 1543 struct BestOpData { 1544 Optional<unsigned> Idx = None; 1545 unsigned Score = 0; 1546 } BestOp; 1547 BestOp.Score = 1548 BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0) 1549 .first->second; 1550 1551 // Track if the operand must be marked as used. If the operand is set to 1552 // Score 1 explicitly (because of non power-of-2 unique scalars, we may 1553 // want to reestimate the operands again on the following iterations). 1554 bool IsUsed = 1555 RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant; 1556 // Iterate through all unused operands and look for the best. 1557 for (unsigned Idx = 0; Idx != NumOperands; ++Idx) { 1558 // Get the operand at Idx and Lane. 1559 OperandData &OpData = getData(Idx, Lane); 1560 Value *Op = OpData.V; 1561 bool OpAPO = OpData.APO; 1562 1563 // Skip already selected operands. 1564 if (OpData.IsUsed) 1565 continue; 1566 1567 // Skip if we are trying to move the operand to a position with a 1568 // different opcode in the linearized tree form. This would break the 1569 // semantics. 1570 if (OpAPO != OpIdxAPO) 1571 continue; 1572 1573 // Look for an operand that matches the current mode. 1574 switch (RMode) { 1575 case ReorderingMode::Load: 1576 case ReorderingMode::Constant: 1577 case ReorderingMode::Opcode: { 1578 bool LeftToRight = Lane > LastLane; 1579 Value *OpLeft = (LeftToRight) ? OpLastLane : Op; 1580 Value *OpRight = (LeftToRight) ? Op : OpLastLane; 1581 int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane, 1582 OpIdx, Idx, IsUsed); 1583 if (Score > static_cast<int>(BestOp.Score)) { 1584 BestOp.Idx = Idx; 1585 BestOp.Score = Score; 1586 BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score; 1587 } 1588 break; 1589 } 1590 case ReorderingMode::Splat: 1591 if (Op == OpLastLane) 1592 BestOp.Idx = Idx; 1593 break; 1594 case ReorderingMode::Failed: 1595 llvm_unreachable("Not expected Failed reordering mode."); 1596 } 1597 } 1598 1599 if (BestOp.Idx) { 1600 getData(*BestOp.Idx, Lane).IsUsed = IsUsed; 1601 return BestOp.Idx; 1602 } 1603 // If we could not find a good match return None. 1604 return None; 1605 } 1606 1607 /// Helper for reorderOperandVecs. 1608 /// \returns the lane that we should start reordering from. This is the one 1609 /// which has the least number of operands that can freely move about or 1610 /// less profitable because it already has the most optimal set of operands. 1611 unsigned getBestLaneToStartReordering() const { 1612 unsigned Min = UINT_MAX; 1613 unsigned SameOpNumber = 0; 1614 // std::pair<unsigned, unsigned> is used to implement a simple voting 1615 // algorithm and choose the lane with the least number of operands that 1616 // can freely move about or less profitable because it already has the 1617 // most optimal set of operands. The first unsigned is a counter for 1618 // voting, the second unsigned is the counter of lanes with instructions 1619 // with same/alternate opcodes and same parent basic block. 1620 MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap; 1621 // Try to be closer to the original results, if we have multiple lanes 1622 // with same cost. If 2 lanes have the same cost, use the one with the 1623 // lowest index. 1624 for (int I = getNumLanes(); I > 0; --I) { 1625 unsigned Lane = I - 1; 1626 OperandsOrderData NumFreeOpsHash = 1627 getMaxNumOperandsThatCanBeReordered(Lane); 1628 // Compare the number of operands that can move and choose the one with 1629 // the least number. 1630 if (NumFreeOpsHash.NumOfAPOs < Min) { 1631 Min = NumFreeOpsHash.NumOfAPOs; 1632 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; 1633 HashMap.clear(); 1634 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1635 } else if (NumFreeOpsHash.NumOfAPOs == Min && 1636 NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) { 1637 // Select the most optimal lane in terms of number of operands that 1638 // should be moved around. 1639 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; 1640 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1641 } else if (NumFreeOpsHash.NumOfAPOs == Min && 1642 NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) { 1643 auto It = HashMap.find(NumFreeOpsHash.Hash); 1644 if (It == HashMap.end()) 1645 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1646 else 1647 ++It->second.first; 1648 } 1649 } 1650 // Select the lane with the minimum counter. 1651 unsigned BestLane = 0; 1652 unsigned CntMin = UINT_MAX; 1653 for (const auto &Data : reverse(HashMap)) { 1654 if (Data.second.first < CntMin) { 1655 CntMin = Data.second.first; 1656 BestLane = Data.second.second; 1657 } 1658 } 1659 return BestLane; 1660 } 1661 1662 /// Data structure that helps to reorder operands. 1663 struct OperandsOrderData { 1664 /// The best number of operands with the same APOs, which can be 1665 /// reordered. 1666 unsigned NumOfAPOs = UINT_MAX; 1667 /// Number of operands with the same/alternate instruction opcode and 1668 /// parent. 1669 unsigned NumOpsWithSameOpcodeParent = 0; 1670 /// Hash for the actual operands ordering. 1671 /// Used to count operands, actually their position id and opcode 1672 /// value. It is used in the voting mechanism to find the lane with the 1673 /// least number of operands that can freely move about or less profitable 1674 /// because it already has the most optimal set of operands. Can be 1675 /// replaced with SmallVector<unsigned> instead but hash code is faster 1676 /// and requires less memory. 1677 unsigned Hash = 0; 1678 }; 1679 /// \returns the maximum number of operands that are allowed to be reordered 1680 /// for \p Lane and the number of compatible instructions(with the same 1681 /// parent/opcode). This is used as a heuristic for selecting the first lane 1682 /// to start operand reordering. 1683 OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const { 1684 unsigned CntTrue = 0; 1685 unsigned NumOperands = getNumOperands(); 1686 // Operands with the same APO can be reordered. We therefore need to count 1687 // how many of them we have for each APO, like this: Cnt[APO] = x. 1688 // Since we only have two APOs, namely true and false, we can avoid using 1689 // a map. Instead we can simply count the number of operands that 1690 // correspond to one of them (in this case the 'true' APO), and calculate 1691 // the other by subtracting it from the total number of operands. 1692 // Operands with the same instruction opcode and parent are more 1693 // profitable since we don't need to move them in many cases, with a high 1694 // probability such lane already can be vectorized effectively. 1695 bool AllUndefs = true; 1696 unsigned NumOpsWithSameOpcodeParent = 0; 1697 Instruction *OpcodeI = nullptr; 1698 BasicBlock *Parent = nullptr; 1699 unsigned Hash = 0; 1700 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1701 const OperandData &OpData = getData(OpIdx, Lane); 1702 if (OpData.APO) 1703 ++CntTrue; 1704 // Use Boyer-Moore majority voting for finding the majority opcode and 1705 // the number of times it occurs. 1706 if (auto *I = dyn_cast<Instruction>(OpData.V)) { 1707 if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() || 1708 I->getParent() != Parent) { 1709 if (NumOpsWithSameOpcodeParent == 0) { 1710 NumOpsWithSameOpcodeParent = 1; 1711 OpcodeI = I; 1712 Parent = I->getParent(); 1713 } else { 1714 --NumOpsWithSameOpcodeParent; 1715 } 1716 } else { 1717 ++NumOpsWithSameOpcodeParent; 1718 } 1719 } 1720 Hash = hash_combine( 1721 Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1))); 1722 AllUndefs = AllUndefs && isa<UndefValue>(OpData.V); 1723 } 1724 if (AllUndefs) 1725 return {}; 1726 OperandsOrderData Data; 1727 Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue); 1728 Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent; 1729 Data.Hash = Hash; 1730 return Data; 1731 } 1732 1733 /// Go through the instructions in VL and append their operands. 1734 void appendOperandsOfVL(ArrayRef<Value *> VL) { 1735 assert(!VL.empty() && "Bad VL"); 1736 assert((empty() || VL.size() == getNumLanes()) && 1737 "Expected same number of lanes"); 1738 assert(isa<Instruction>(VL[0]) && "Expected instruction"); 1739 unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands(); 1740 OpsVec.resize(NumOperands); 1741 unsigned NumLanes = VL.size(); 1742 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1743 OpsVec[OpIdx].resize(NumLanes); 1744 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 1745 assert(isa<Instruction>(VL[Lane]) && "Expected instruction"); 1746 // Our tree has just 3 nodes: the root and two operands. 1747 // It is therefore trivial to get the APO. We only need to check the 1748 // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or 1749 // RHS operand. The LHS operand of both add and sub is never attached 1750 // to an inversese operation in the linearized form, therefore its APO 1751 // is false. The RHS is true only if VL[Lane] is an inverse operation. 1752 1753 // Since operand reordering is performed on groups of commutative 1754 // operations or alternating sequences (e.g., +, -), we can safely 1755 // tell the inverse operations by checking commutativity. 1756 bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane])); 1757 bool APO = (OpIdx == 0) ? false : IsInverseOperation; 1758 OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx), 1759 APO, false}; 1760 } 1761 } 1762 } 1763 1764 /// \returns the number of operands. 1765 unsigned getNumOperands() const { return OpsVec.size(); } 1766 1767 /// \returns the number of lanes. 1768 unsigned getNumLanes() const { return OpsVec[0].size(); } 1769 1770 /// \returns the operand value at \p OpIdx and \p Lane. 1771 Value *getValue(unsigned OpIdx, unsigned Lane) const { 1772 return getData(OpIdx, Lane).V; 1773 } 1774 1775 /// \returns true if the data structure is empty. 1776 bool empty() const { return OpsVec.empty(); } 1777 1778 /// Clears the data. 1779 void clear() { OpsVec.clear(); } 1780 1781 /// \Returns true if there are enough operands identical to \p Op to fill 1782 /// the whole vector. 1783 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow. 1784 bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) { 1785 bool OpAPO = getData(OpIdx, Lane).APO; 1786 for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) { 1787 if (Ln == Lane) 1788 continue; 1789 // This is set to true if we found a candidate for broadcast at Lane. 1790 bool FoundCandidate = false; 1791 for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) { 1792 OperandData &Data = getData(OpI, Ln); 1793 if (Data.APO != OpAPO || Data.IsUsed) 1794 continue; 1795 if (Data.V == Op) { 1796 FoundCandidate = true; 1797 Data.IsUsed = true; 1798 break; 1799 } 1800 } 1801 if (!FoundCandidate) 1802 return false; 1803 } 1804 return true; 1805 } 1806 1807 public: 1808 /// Initialize with all the operands of the instruction vector \p RootVL. 1809 VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL, 1810 ScalarEvolution &SE, const BoUpSLP &R) 1811 : DL(DL), SE(SE), R(R) { 1812 // Append all the operands of RootVL. 1813 appendOperandsOfVL(RootVL); 1814 } 1815 1816 /// \Returns a value vector with the operands across all lanes for the 1817 /// opearnd at \p OpIdx. 1818 ValueList getVL(unsigned OpIdx) const { 1819 ValueList OpVL(OpsVec[OpIdx].size()); 1820 assert(OpsVec[OpIdx].size() == getNumLanes() && 1821 "Expected same num of lanes across all operands"); 1822 for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane) 1823 OpVL[Lane] = OpsVec[OpIdx][Lane].V; 1824 return OpVL; 1825 } 1826 1827 // Performs operand reordering for 2 or more operands. 1828 // The original operands are in OrigOps[OpIdx][Lane]. 1829 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'. 1830 void reorder() { 1831 unsigned NumOperands = getNumOperands(); 1832 unsigned NumLanes = getNumLanes(); 1833 // Each operand has its own mode. We are using this mode to help us select 1834 // the instructions for each lane, so that they match best with the ones 1835 // we have selected so far. 1836 SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands); 1837 1838 // This is a greedy single-pass algorithm. We are going over each lane 1839 // once and deciding on the best order right away with no back-tracking. 1840 // However, in order to increase its effectiveness, we start with the lane 1841 // that has operands that can move the least. For example, given the 1842 // following lanes: 1843 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd 1844 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st 1845 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd 1846 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th 1847 // we will start at Lane 1, since the operands of the subtraction cannot 1848 // be reordered. Then we will visit the rest of the lanes in a circular 1849 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3. 1850 1851 // Find the first lane that we will start our search from. 1852 unsigned FirstLane = getBestLaneToStartReordering(); 1853 1854 // Initialize the modes. 1855 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1856 Value *OpLane0 = getValue(OpIdx, FirstLane); 1857 // Keep track if we have instructions with all the same opcode on one 1858 // side. 1859 if (isa<LoadInst>(OpLane0)) 1860 ReorderingModes[OpIdx] = ReorderingMode::Load; 1861 else if (isa<Instruction>(OpLane0)) { 1862 // Check if OpLane0 should be broadcast. 1863 if (shouldBroadcast(OpLane0, OpIdx, FirstLane)) 1864 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1865 else 1866 ReorderingModes[OpIdx] = ReorderingMode::Opcode; 1867 } 1868 else if (isa<Constant>(OpLane0)) 1869 ReorderingModes[OpIdx] = ReorderingMode::Constant; 1870 else if (isa<Argument>(OpLane0)) 1871 // Our best hope is a Splat. It may save some cost in some cases. 1872 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1873 else 1874 // NOTE: This should be unreachable. 1875 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1876 } 1877 1878 // Check that we don't have same operands. No need to reorder if operands 1879 // are just perfect diamond or shuffled diamond match. Do not do it only 1880 // for possible broadcasts or non-power of 2 number of scalars (just for 1881 // now). 1882 auto &&SkipReordering = [this]() { 1883 SmallPtrSet<Value *, 4> UniqueValues; 1884 ArrayRef<OperandData> Op0 = OpsVec.front(); 1885 for (const OperandData &Data : Op0) 1886 UniqueValues.insert(Data.V); 1887 for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) { 1888 if (any_of(Op, [&UniqueValues](const OperandData &Data) { 1889 return !UniqueValues.contains(Data.V); 1890 })) 1891 return false; 1892 } 1893 // TODO: Check if we can remove a check for non-power-2 number of 1894 // scalars after full support of non-power-2 vectorization. 1895 return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size()); 1896 }; 1897 1898 // If the initial strategy fails for any of the operand indexes, then we 1899 // perform reordering again in a second pass. This helps avoid assigning 1900 // high priority to the failed strategy, and should improve reordering for 1901 // the non-failed operand indexes. 1902 for (int Pass = 0; Pass != 2; ++Pass) { 1903 // Check if no need to reorder operands since they're are perfect or 1904 // shuffled diamond match. 1905 // Need to to do it to avoid extra external use cost counting for 1906 // shuffled matches, which may cause regressions. 1907 if (SkipReordering()) 1908 break; 1909 // Skip the second pass if the first pass did not fail. 1910 bool StrategyFailed = false; 1911 // Mark all operand data as free to use. 1912 clearUsed(); 1913 // We keep the original operand order for the FirstLane, so reorder the 1914 // rest of the lanes. We are visiting the nodes in a circular fashion, 1915 // using FirstLane as the center point and increasing the radius 1916 // distance. 1917 SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands); 1918 for (unsigned I = 0; I < NumOperands; ++I) 1919 MainAltOps[I].push_back(getData(I, FirstLane).V); 1920 1921 for (unsigned Distance = 1; Distance != NumLanes; ++Distance) { 1922 // Visit the lane on the right and then the lane on the left. 1923 for (int Direction : {+1, -1}) { 1924 int Lane = FirstLane + Direction * Distance; 1925 if (Lane < 0 || Lane >= (int)NumLanes) 1926 continue; 1927 int LastLane = Lane - Direction; 1928 assert(LastLane >= 0 && LastLane < (int)NumLanes && 1929 "Out of bounds"); 1930 // Look for a good match for each operand. 1931 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1932 // Search for the operand that matches SortedOps[OpIdx][Lane-1]. 1933 Optional<unsigned> BestIdx = getBestOperand( 1934 OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]); 1935 // By not selecting a value, we allow the operands that follow to 1936 // select a better matching value. We will get a non-null value in 1937 // the next run of getBestOperand(). 1938 if (BestIdx) { 1939 // Swap the current operand with the one returned by 1940 // getBestOperand(). 1941 swap(OpIdx, *BestIdx, Lane); 1942 } else { 1943 // We failed to find a best operand, set mode to 'Failed'. 1944 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1945 // Enable the second pass. 1946 StrategyFailed = true; 1947 } 1948 // Try to get the alternate opcode and follow it during analysis. 1949 if (MainAltOps[OpIdx].size() != 2) { 1950 OperandData &AltOp = getData(OpIdx, Lane); 1951 InstructionsState OpS = 1952 getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V}); 1953 if (OpS.getOpcode() && OpS.isAltShuffle()) 1954 MainAltOps[OpIdx].push_back(AltOp.V); 1955 } 1956 } 1957 } 1958 } 1959 // Skip second pass if the strategy did not fail. 1960 if (!StrategyFailed) 1961 break; 1962 } 1963 } 1964 1965 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1966 LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) { 1967 switch (RMode) { 1968 case ReorderingMode::Load: 1969 return "Load"; 1970 case ReorderingMode::Opcode: 1971 return "Opcode"; 1972 case ReorderingMode::Constant: 1973 return "Constant"; 1974 case ReorderingMode::Splat: 1975 return "Splat"; 1976 case ReorderingMode::Failed: 1977 return "Failed"; 1978 } 1979 llvm_unreachable("Unimplemented Reordering Type"); 1980 } 1981 1982 LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode, 1983 raw_ostream &OS) { 1984 return OS << getModeStr(RMode); 1985 } 1986 1987 /// Debug print. 1988 LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) { 1989 printMode(RMode, dbgs()); 1990 } 1991 1992 friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) { 1993 return printMode(RMode, OS); 1994 } 1995 1996 LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const { 1997 const unsigned Indent = 2; 1998 unsigned Cnt = 0; 1999 for (const OperandDataVec &OpDataVec : OpsVec) { 2000 OS << "Operand " << Cnt++ << "\n"; 2001 for (const OperandData &OpData : OpDataVec) { 2002 OS.indent(Indent) << "{"; 2003 if (Value *V = OpData.V) 2004 OS << *V; 2005 else 2006 OS << "null"; 2007 OS << ", APO:" << OpData.APO << "}\n"; 2008 } 2009 OS << "\n"; 2010 } 2011 return OS; 2012 } 2013 2014 /// Debug print. 2015 LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 2016 #endif 2017 }; 2018 2019 /// Evaluate each pair in \p Candidates and return index into \p Candidates 2020 /// for a pair which have highest score deemed to have best chance to form 2021 /// root of profitable tree to vectorize. Return None if no candidate scored 2022 /// above the LookAheadHeuristics::ScoreFail. 2023 /// \param Limit Lower limit of the cost, considered to be good enough score. 2024 Optional<int> 2025 findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates, 2026 int Limit = LookAheadHeuristics::ScoreFail) { 2027 LookAheadHeuristics LookAhead(*DL, *SE, *this, /*NumLanes=*/2, 2028 RootLookAheadMaxDepth); 2029 int BestScore = Limit; 2030 Optional<int> Index = None; 2031 for (int I : seq<int>(0, Candidates.size())) { 2032 int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first, 2033 Candidates[I].second, 2034 /*U1=*/nullptr, /*U2=*/nullptr, 2035 /*Level=*/1, None); 2036 if (Score > BestScore) { 2037 BestScore = Score; 2038 Index = I; 2039 } 2040 } 2041 return Index; 2042 } 2043 2044 /// Checks if the instruction is marked for deletion. 2045 bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); } 2046 2047 /// Removes an instruction from its block and eventually deletes it. 2048 /// It's like Instruction::eraseFromParent() except that the actual deletion 2049 /// is delayed until BoUpSLP is destructed. 2050 void eraseInstruction(Instruction *I) { 2051 DeletedInstructions.insert(I); 2052 } 2053 2054 /// Checks if the instruction was already analyzed for being possible 2055 /// reduction root. 2056 bool isAnalyzedReductionRoot(Instruction *I) const { 2057 return AnalyzedReductionsRoots.count(I); 2058 } 2059 /// Register given instruction as already analyzed for being possible 2060 /// reduction root. 2061 void analyzedReductionRoot(Instruction *I) { 2062 AnalyzedReductionsRoots.insert(I); 2063 } 2064 /// Checks if the provided list of reduced values was checked already for 2065 /// vectorization. 2066 bool areAnalyzedReductionVals(ArrayRef<Value *> VL) { 2067 return AnalyzedReductionVals.contains(hash_value(VL)); 2068 } 2069 /// Adds the list of reduced values to list of already checked values for the 2070 /// vectorization. 2071 void analyzedReductionVals(ArrayRef<Value *> VL) { 2072 AnalyzedReductionVals.insert(hash_value(VL)); 2073 } 2074 /// Clear the list of the analyzed reduction root instructions. 2075 void clearReductionData() { 2076 AnalyzedReductionsRoots.clear(); 2077 AnalyzedReductionVals.clear(); 2078 } 2079 /// Checks if the given value is gathered in one of the nodes. 2080 bool isAnyGathered(const SmallDenseSet<Value *> &Vals) const { 2081 return any_of(MustGather, [&](Value *V) { return Vals.contains(V); }); 2082 } 2083 2084 ~BoUpSLP(); 2085 2086 private: 2087 /// Check if the operands on the edges \p Edges of the \p UserTE allows 2088 /// reordering (i.e. the operands can be reordered because they have only one 2089 /// user and reordarable). 2090 /// \param ReorderableGathers List of all gather nodes that require reordering 2091 /// (e.g., gather of extractlements or partially vectorizable loads). 2092 /// \param GatherOps List of gather operand nodes for \p UserTE that require 2093 /// reordering, subset of \p NonVectorized. 2094 bool 2095 canReorderOperands(TreeEntry *UserTE, 2096 SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges, 2097 ArrayRef<TreeEntry *> ReorderableGathers, 2098 SmallVectorImpl<TreeEntry *> &GatherOps); 2099 2100 /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph, 2101 /// if any. If it is not vectorized (gather node), returns nullptr. 2102 TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) { 2103 ArrayRef<Value *> VL = UserTE->getOperand(OpIdx); 2104 TreeEntry *TE = nullptr; 2105 const auto *It = find_if(VL, [this, &TE](Value *V) { 2106 TE = getTreeEntry(V); 2107 return TE; 2108 }); 2109 if (It != VL.end() && TE->isSame(VL)) 2110 return TE; 2111 return nullptr; 2112 } 2113 2114 /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph, 2115 /// if any. If it is not vectorized (gather node), returns nullptr. 2116 const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE, 2117 unsigned OpIdx) const { 2118 return const_cast<BoUpSLP *>(this)->getVectorizedOperand( 2119 const_cast<TreeEntry *>(UserTE), OpIdx); 2120 } 2121 2122 /// Checks if all users of \p I are the part of the vectorization tree. 2123 bool areAllUsersVectorized(Instruction *I, 2124 ArrayRef<Value *> VectorizedVals) const; 2125 2126 /// \returns the cost of the vectorizable entry. 2127 InstructionCost getEntryCost(const TreeEntry *E, 2128 ArrayRef<Value *> VectorizedVals); 2129 2130 /// This is the recursive part of buildTree. 2131 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, 2132 const EdgeInfo &EI); 2133 2134 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can 2135 /// be vectorized to use the original vector (or aggregate "bitcast" to a 2136 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise 2137 /// returns false, setting \p CurrentOrder to either an empty vector or a 2138 /// non-identity permutation that allows to reuse extract instructions. 2139 bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 2140 SmallVectorImpl<unsigned> &CurrentOrder) const; 2141 2142 /// Vectorize a single entry in the tree. 2143 Value *vectorizeTree(TreeEntry *E); 2144 2145 /// Vectorize a single entry in the tree, starting in \p VL. 2146 Value *vectorizeTree(ArrayRef<Value *> VL); 2147 2148 /// Create a new vector from a list of scalar values. Produces a sequence 2149 /// which exploits values reused across lanes, and arranges the inserts 2150 /// for ease of later optimization. 2151 Value *createBuildVector(ArrayRef<Value *> VL); 2152 2153 /// \returns the scalarization cost for this type. Scalarization in this 2154 /// context means the creation of vectors from a group of scalars. If \p 2155 /// NeedToShuffle is true, need to add a cost of reshuffling some of the 2156 /// vector elements. 2157 InstructionCost getGatherCost(FixedVectorType *Ty, 2158 const APInt &ShuffledIndices, 2159 bool NeedToShuffle) const; 2160 2161 /// Checks if the gathered \p VL can be represented as shuffle(s) of previous 2162 /// tree entries. 2163 /// \returns ShuffleKind, if gathered values can be represented as shuffles of 2164 /// previous tree entries. \p Mask is filled with the shuffle mask. 2165 Optional<TargetTransformInfo::ShuffleKind> 2166 isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 2167 SmallVectorImpl<const TreeEntry *> &Entries); 2168 2169 /// \returns the scalarization cost for this list of values. Assuming that 2170 /// this subtree gets vectorized, we may need to extract the values from the 2171 /// roots. This method calculates the cost of extracting the values. 2172 InstructionCost getGatherCost(ArrayRef<Value *> VL) const; 2173 2174 /// Set the Builder insert point to one after the last instruction in 2175 /// the bundle 2176 void setInsertPointAfterBundle(const TreeEntry *E); 2177 2178 /// \returns a vector from a collection of scalars in \p VL. 2179 Value *gather(ArrayRef<Value *> VL); 2180 2181 /// \returns whether the VectorizableTree is fully vectorizable and will 2182 /// be beneficial even the tree height is tiny. 2183 bool isFullyVectorizableTinyTree(bool ForReduction) const; 2184 2185 /// Reorder commutative or alt operands to get better probability of 2186 /// generating vectorized code. 2187 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 2188 SmallVectorImpl<Value *> &Left, 2189 SmallVectorImpl<Value *> &Right, 2190 const DataLayout &DL, 2191 ScalarEvolution &SE, 2192 const BoUpSLP &R); 2193 2194 /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the 2195 /// users of \p TE and collects the stores. It returns the map from the store 2196 /// pointers to the collected stores. 2197 DenseMap<Value *, SmallVector<StoreInst *, 4>> 2198 collectUserStores(const BoUpSLP::TreeEntry *TE) const; 2199 2200 /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the 2201 /// stores in \p StoresVec can for a vector instruction. If so it returns true 2202 /// and populates \p ReorderIndices with the shuffle indices of the the stores 2203 /// when compared to the sorted vector. 2204 bool CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec, 2205 OrdersType &ReorderIndices) const; 2206 2207 /// Iterates through the users of \p TE, looking for scalar stores that can be 2208 /// potentially vectorized in a future SLP-tree. If found, it keeps track of 2209 /// their order and builds an order index vector for each store bundle. It 2210 /// returns all these order vectors found. 2211 /// We run this after the tree has formed, otherwise we may come across user 2212 /// instructions that are not yet in the tree. 2213 SmallVector<OrdersType, 1> 2214 findExternalStoreUsersReorderIndices(TreeEntry *TE) const; 2215 2216 struct TreeEntry { 2217 using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>; 2218 TreeEntry(VecTreeTy &Container) : Container(Container) {} 2219 2220 /// \returns true if the scalars in VL are equal to this entry. 2221 bool isSame(ArrayRef<Value *> VL) const { 2222 auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) { 2223 if (Mask.size() != VL.size() && VL.size() == Scalars.size()) 2224 return std::equal(VL.begin(), VL.end(), Scalars.begin()); 2225 return VL.size() == Mask.size() && 2226 std::equal(VL.begin(), VL.end(), Mask.begin(), 2227 [Scalars](Value *V, int Idx) { 2228 return (isa<UndefValue>(V) && 2229 Idx == UndefMaskElem) || 2230 (Idx != UndefMaskElem && V == Scalars[Idx]); 2231 }); 2232 }; 2233 if (!ReorderIndices.empty()) { 2234 // TODO: implement matching if the nodes are just reordered, still can 2235 // treat the vector as the same if the list of scalars matches VL 2236 // directly, without reordering. 2237 SmallVector<int> Mask; 2238 inversePermutation(ReorderIndices, Mask); 2239 if (VL.size() == Scalars.size()) 2240 return IsSame(Scalars, Mask); 2241 if (VL.size() == ReuseShuffleIndices.size()) { 2242 ::addMask(Mask, ReuseShuffleIndices); 2243 return IsSame(Scalars, Mask); 2244 } 2245 return false; 2246 } 2247 return IsSame(Scalars, ReuseShuffleIndices); 2248 } 2249 2250 /// \returns true if current entry has same operands as \p TE. 2251 bool hasEqualOperands(const TreeEntry &TE) const { 2252 if (TE.getNumOperands() != getNumOperands()) 2253 return false; 2254 SmallBitVector Used(getNumOperands()); 2255 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) { 2256 unsigned PrevCount = Used.count(); 2257 for (unsigned K = 0; K < E; ++K) { 2258 if (Used.test(K)) 2259 continue; 2260 if (getOperand(K) == TE.getOperand(I)) { 2261 Used.set(K); 2262 break; 2263 } 2264 } 2265 // Check if we actually found the matching operand. 2266 if (PrevCount == Used.count()) 2267 return false; 2268 } 2269 return true; 2270 } 2271 2272 /// \return Final vectorization factor for the node. Defined by the total 2273 /// number of vectorized scalars, including those, used several times in the 2274 /// entry and counted in the \a ReuseShuffleIndices, if any. 2275 unsigned getVectorFactor() const { 2276 if (!ReuseShuffleIndices.empty()) 2277 return ReuseShuffleIndices.size(); 2278 return Scalars.size(); 2279 }; 2280 2281 /// A vector of scalars. 2282 ValueList Scalars; 2283 2284 /// The Scalars are vectorized into this value. It is initialized to Null. 2285 Value *VectorizedValue = nullptr; 2286 2287 /// Do we need to gather this sequence or vectorize it 2288 /// (either with vector instruction or with scatter/gather 2289 /// intrinsics for store/load)? 2290 enum EntryState { Vectorize, ScatterVectorize, NeedToGather }; 2291 EntryState State; 2292 2293 /// Does this sequence require some shuffling? 2294 SmallVector<int, 4> ReuseShuffleIndices; 2295 2296 /// Does this entry require reordering? 2297 SmallVector<unsigned, 4> ReorderIndices; 2298 2299 /// Points back to the VectorizableTree. 2300 /// 2301 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has 2302 /// to be a pointer and needs to be able to initialize the child iterator. 2303 /// Thus we need a reference back to the container to translate the indices 2304 /// to entries. 2305 VecTreeTy &Container; 2306 2307 /// The TreeEntry index containing the user of this entry. We can actually 2308 /// have multiple users so the data structure is not truly a tree. 2309 SmallVector<EdgeInfo, 1> UserTreeIndices; 2310 2311 /// The index of this treeEntry in VectorizableTree. 2312 int Idx = -1; 2313 2314 private: 2315 /// The operands of each instruction in each lane Operands[op_index][lane]. 2316 /// Note: This helps avoid the replication of the code that performs the 2317 /// reordering of operands during buildTree_rec() and vectorizeTree(). 2318 SmallVector<ValueList, 2> Operands; 2319 2320 /// The main/alternate instruction. 2321 Instruction *MainOp = nullptr; 2322 Instruction *AltOp = nullptr; 2323 2324 public: 2325 /// Set this bundle's \p OpIdx'th operand to \p OpVL. 2326 void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) { 2327 if (Operands.size() < OpIdx + 1) 2328 Operands.resize(OpIdx + 1); 2329 assert(Operands[OpIdx].empty() && "Already resized?"); 2330 assert(OpVL.size() <= Scalars.size() && 2331 "Number of operands is greater than the number of scalars."); 2332 Operands[OpIdx].resize(OpVL.size()); 2333 copy(OpVL, Operands[OpIdx].begin()); 2334 } 2335 2336 /// Set the operands of this bundle in their original order. 2337 void setOperandsInOrder() { 2338 assert(Operands.empty() && "Already initialized?"); 2339 auto *I0 = cast<Instruction>(Scalars[0]); 2340 Operands.resize(I0->getNumOperands()); 2341 unsigned NumLanes = Scalars.size(); 2342 for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands(); 2343 OpIdx != NumOperands; ++OpIdx) { 2344 Operands[OpIdx].resize(NumLanes); 2345 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 2346 auto *I = cast<Instruction>(Scalars[Lane]); 2347 assert(I->getNumOperands() == NumOperands && 2348 "Expected same number of operands"); 2349 Operands[OpIdx][Lane] = I->getOperand(OpIdx); 2350 } 2351 } 2352 } 2353 2354 /// Reorders operands of the node to the given mask \p Mask. 2355 void reorderOperands(ArrayRef<int> Mask) { 2356 for (ValueList &Operand : Operands) 2357 reorderScalars(Operand, Mask); 2358 } 2359 2360 /// \returns the \p OpIdx operand of this TreeEntry. 2361 ValueList &getOperand(unsigned OpIdx) { 2362 assert(OpIdx < Operands.size() && "Off bounds"); 2363 return Operands[OpIdx]; 2364 } 2365 2366 /// \returns the \p OpIdx operand of this TreeEntry. 2367 ArrayRef<Value *> getOperand(unsigned OpIdx) const { 2368 assert(OpIdx < Operands.size() && "Off bounds"); 2369 return Operands[OpIdx]; 2370 } 2371 2372 /// \returns the number of operands. 2373 unsigned getNumOperands() const { return Operands.size(); } 2374 2375 /// \return the single \p OpIdx operand. 2376 Value *getSingleOperand(unsigned OpIdx) const { 2377 assert(OpIdx < Operands.size() && "Off bounds"); 2378 assert(!Operands[OpIdx].empty() && "No operand available"); 2379 return Operands[OpIdx][0]; 2380 } 2381 2382 /// Some of the instructions in the list have alternate opcodes. 2383 bool isAltShuffle() const { return MainOp != AltOp; } 2384 2385 bool isOpcodeOrAlt(Instruction *I) const { 2386 unsigned CheckedOpcode = I->getOpcode(); 2387 return (getOpcode() == CheckedOpcode || 2388 getAltOpcode() == CheckedOpcode); 2389 } 2390 2391 /// Chooses the correct key for scheduling data. If \p Op has the same (or 2392 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is 2393 /// \p OpValue. 2394 Value *isOneOf(Value *Op) const { 2395 auto *I = dyn_cast<Instruction>(Op); 2396 if (I && isOpcodeOrAlt(I)) 2397 return Op; 2398 return MainOp; 2399 } 2400 2401 void setOperations(const InstructionsState &S) { 2402 MainOp = S.MainOp; 2403 AltOp = S.AltOp; 2404 } 2405 2406 Instruction *getMainOp() const { 2407 return MainOp; 2408 } 2409 2410 Instruction *getAltOp() const { 2411 return AltOp; 2412 } 2413 2414 /// The main/alternate opcodes for the list of instructions. 2415 unsigned getOpcode() const { 2416 return MainOp ? MainOp->getOpcode() : 0; 2417 } 2418 2419 unsigned getAltOpcode() const { 2420 return AltOp ? AltOp->getOpcode() : 0; 2421 } 2422 2423 /// When ReuseReorderShuffleIndices is empty it just returns position of \p 2424 /// V within vector of Scalars. Otherwise, try to remap on its reuse index. 2425 int findLaneForValue(Value *V) const { 2426 unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V)); 2427 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 2428 if (!ReorderIndices.empty()) 2429 FoundLane = ReorderIndices[FoundLane]; 2430 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 2431 if (!ReuseShuffleIndices.empty()) { 2432 FoundLane = std::distance(ReuseShuffleIndices.begin(), 2433 find(ReuseShuffleIndices, FoundLane)); 2434 } 2435 return FoundLane; 2436 } 2437 2438 #ifndef NDEBUG 2439 /// Debug printer. 2440 LLVM_DUMP_METHOD void dump() const { 2441 dbgs() << Idx << ".\n"; 2442 for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) { 2443 dbgs() << "Operand " << OpI << ":\n"; 2444 for (const Value *V : Operands[OpI]) 2445 dbgs().indent(2) << *V << "\n"; 2446 } 2447 dbgs() << "Scalars: \n"; 2448 for (Value *V : Scalars) 2449 dbgs().indent(2) << *V << "\n"; 2450 dbgs() << "State: "; 2451 switch (State) { 2452 case Vectorize: 2453 dbgs() << "Vectorize\n"; 2454 break; 2455 case ScatterVectorize: 2456 dbgs() << "ScatterVectorize\n"; 2457 break; 2458 case NeedToGather: 2459 dbgs() << "NeedToGather\n"; 2460 break; 2461 } 2462 dbgs() << "MainOp: "; 2463 if (MainOp) 2464 dbgs() << *MainOp << "\n"; 2465 else 2466 dbgs() << "NULL\n"; 2467 dbgs() << "AltOp: "; 2468 if (AltOp) 2469 dbgs() << *AltOp << "\n"; 2470 else 2471 dbgs() << "NULL\n"; 2472 dbgs() << "VectorizedValue: "; 2473 if (VectorizedValue) 2474 dbgs() << *VectorizedValue << "\n"; 2475 else 2476 dbgs() << "NULL\n"; 2477 dbgs() << "ReuseShuffleIndices: "; 2478 if (ReuseShuffleIndices.empty()) 2479 dbgs() << "Empty"; 2480 else 2481 for (int ReuseIdx : ReuseShuffleIndices) 2482 dbgs() << ReuseIdx << ", "; 2483 dbgs() << "\n"; 2484 dbgs() << "ReorderIndices: "; 2485 for (unsigned ReorderIdx : ReorderIndices) 2486 dbgs() << ReorderIdx << ", "; 2487 dbgs() << "\n"; 2488 dbgs() << "UserTreeIndices: "; 2489 for (const auto &EInfo : UserTreeIndices) 2490 dbgs() << EInfo << ", "; 2491 dbgs() << "\n"; 2492 } 2493 #endif 2494 }; 2495 2496 #ifndef NDEBUG 2497 void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost, 2498 InstructionCost VecCost, 2499 InstructionCost ScalarCost) const { 2500 dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump(); 2501 dbgs() << "SLP: Costs:\n"; 2502 dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n"; 2503 dbgs() << "SLP: VectorCost = " << VecCost << "\n"; 2504 dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n"; 2505 dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = " << 2506 ReuseShuffleCost + VecCost - ScalarCost << "\n"; 2507 } 2508 #endif 2509 2510 /// Create a new VectorizableTree entry. 2511 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle, 2512 const InstructionsState &S, 2513 const EdgeInfo &UserTreeIdx, 2514 ArrayRef<int> ReuseShuffleIndices = None, 2515 ArrayRef<unsigned> ReorderIndices = None) { 2516 TreeEntry::EntryState EntryState = 2517 Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather; 2518 return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx, 2519 ReuseShuffleIndices, ReorderIndices); 2520 } 2521 2522 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, 2523 TreeEntry::EntryState EntryState, 2524 Optional<ScheduleData *> Bundle, 2525 const InstructionsState &S, 2526 const EdgeInfo &UserTreeIdx, 2527 ArrayRef<int> ReuseShuffleIndices = None, 2528 ArrayRef<unsigned> ReorderIndices = None) { 2529 assert(((!Bundle && EntryState == TreeEntry::NeedToGather) || 2530 (Bundle && EntryState != TreeEntry::NeedToGather)) && 2531 "Need to vectorize gather entry?"); 2532 VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree)); 2533 TreeEntry *Last = VectorizableTree.back().get(); 2534 Last->Idx = VectorizableTree.size() - 1; 2535 Last->State = EntryState; 2536 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(), 2537 ReuseShuffleIndices.end()); 2538 if (ReorderIndices.empty()) { 2539 Last->Scalars.assign(VL.begin(), VL.end()); 2540 Last->setOperations(S); 2541 } else { 2542 // Reorder scalars and build final mask. 2543 Last->Scalars.assign(VL.size(), nullptr); 2544 transform(ReorderIndices, Last->Scalars.begin(), 2545 [VL](unsigned Idx) -> Value * { 2546 if (Idx >= VL.size()) 2547 return UndefValue::get(VL.front()->getType()); 2548 return VL[Idx]; 2549 }); 2550 InstructionsState S = getSameOpcode(Last->Scalars); 2551 Last->setOperations(S); 2552 Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end()); 2553 } 2554 if (Last->State != TreeEntry::NeedToGather) { 2555 for (Value *V : VL) { 2556 assert(!getTreeEntry(V) && "Scalar already in tree!"); 2557 ScalarToTreeEntry[V] = Last; 2558 } 2559 // Update the scheduler bundle to point to this TreeEntry. 2560 ScheduleData *BundleMember = *Bundle; 2561 assert((BundleMember || isa<PHINode>(S.MainOp) || 2562 isVectorLikeInstWithConstOps(S.MainOp) || 2563 doesNotNeedToSchedule(VL)) && 2564 "Bundle and VL out of sync"); 2565 if (BundleMember) { 2566 for (Value *V : VL) { 2567 if (doesNotNeedToBeScheduled(V)) 2568 continue; 2569 assert(BundleMember && "Unexpected end of bundle."); 2570 BundleMember->TE = Last; 2571 BundleMember = BundleMember->NextInBundle; 2572 } 2573 } 2574 assert(!BundleMember && "Bundle and VL out of sync"); 2575 } else { 2576 MustGather.insert(VL.begin(), VL.end()); 2577 } 2578 2579 if (UserTreeIdx.UserTE) 2580 Last->UserTreeIndices.push_back(UserTreeIdx); 2581 2582 return Last; 2583 } 2584 2585 /// -- Vectorization State -- 2586 /// Holds all of the tree entries. 2587 TreeEntry::VecTreeTy VectorizableTree; 2588 2589 #ifndef NDEBUG 2590 /// Debug printer. 2591 LLVM_DUMP_METHOD void dumpVectorizableTree() const { 2592 for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) { 2593 VectorizableTree[Id]->dump(); 2594 dbgs() << "\n"; 2595 } 2596 } 2597 #endif 2598 2599 TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); } 2600 2601 const TreeEntry *getTreeEntry(Value *V) const { 2602 return ScalarToTreeEntry.lookup(V); 2603 } 2604 2605 /// Maps a specific scalar to its tree entry. 2606 SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry; 2607 2608 /// Maps a value to the proposed vectorizable size. 2609 SmallDenseMap<Value *, unsigned> InstrElementSize; 2610 2611 /// A list of scalars that we found that we need to keep as scalars. 2612 ValueSet MustGather; 2613 2614 /// This POD struct describes one external user in the vectorized tree. 2615 struct ExternalUser { 2616 ExternalUser(Value *S, llvm::User *U, int L) 2617 : Scalar(S), User(U), Lane(L) {} 2618 2619 // Which scalar in our function. 2620 Value *Scalar; 2621 2622 // Which user that uses the scalar. 2623 llvm::User *User; 2624 2625 // Which lane does the scalar belong to. 2626 int Lane; 2627 }; 2628 using UserList = SmallVector<ExternalUser, 16>; 2629 2630 /// Checks if two instructions may access the same memory. 2631 /// 2632 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it 2633 /// is invariant in the calling loop. 2634 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1, 2635 Instruction *Inst2) { 2636 // First check if the result is already in the cache. 2637 AliasCacheKey key = std::make_pair(Inst1, Inst2); 2638 Optional<bool> &result = AliasCache[key]; 2639 if (result.hasValue()) { 2640 return result.getValue(); 2641 } 2642 bool aliased = true; 2643 if (Loc1.Ptr && isSimple(Inst1)) 2644 aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1)); 2645 // Store the result in the cache. 2646 result = aliased; 2647 return aliased; 2648 } 2649 2650 using AliasCacheKey = std::pair<Instruction *, Instruction *>; 2651 2652 /// Cache for alias results. 2653 /// TODO: consider moving this to the AliasAnalysis itself. 2654 DenseMap<AliasCacheKey, Optional<bool>> AliasCache; 2655 2656 // Cache for pointerMayBeCaptured calls inside AA. This is preserved 2657 // globally through SLP because we don't perform any action which 2658 // invalidates capture results. 2659 BatchAAResults BatchAA; 2660 2661 /// Temporary store for deleted instructions. Instructions will be deleted 2662 /// eventually when the BoUpSLP is destructed. The deferral is required to 2663 /// ensure that there are no incorrect collisions in the AliasCache, which 2664 /// can happen if a new instruction is allocated at the same address as a 2665 /// previously deleted instruction. 2666 DenseSet<Instruction *> DeletedInstructions; 2667 2668 /// Set of the instruction, being analyzed already for reductions. 2669 SmallPtrSet<Instruction *, 16> AnalyzedReductionsRoots; 2670 2671 /// Set of hashes for the list of reduction values already being analyzed. 2672 DenseSet<size_t> AnalyzedReductionVals; 2673 2674 /// A list of values that need to extracted out of the tree. 2675 /// This list holds pairs of (Internal Scalar : External User). External User 2676 /// can be nullptr, it means that this Internal Scalar will be used later, 2677 /// after vectorization. 2678 UserList ExternalUses; 2679 2680 /// Values used only by @llvm.assume calls. 2681 SmallPtrSet<const Value *, 32> EphValues; 2682 2683 /// Holds all of the instructions that we gathered. 2684 SetVector<Instruction *> GatherShuffleSeq; 2685 2686 /// A list of blocks that we are going to CSE. 2687 SetVector<BasicBlock *> CSEBlocks; 2688 2689 /// Contains all scheduling relevant data for an instruction. 2690 /// A ScheduleData either represents a single instruction or a member of an 2691 /// instruction bundle (= a group of instructions which is combined into a 2692 /// vector instruction). 2693 struct ScheduleData { 2694 // The initial value for the dependency counters. It means that the 2695 // dependencies are not calculated yet. 2696 enum { InvalidDeps = -1 }; 2697 2698 ScheduleData() = default; 2699 2700 void init(int BlockSchedulingRegionID, Value *OpVal) { 2701 FirstInBundle = this; 2702 NextInBundle = nullptr; 2703 NextLoadStore = nullptr; 2704 IsScheduled = false; 2705 SchedulingRegionID = BlockSchedulingRegionID; 2706 clearDependencies(); 2707 OpValue = OpVal; 2708 TE = nullptr; 2709 } 2710 2711 /// Verify basic self consistency properties 2712 void verify() { 2713 if (hasValidDependencies()) { 2714 assert(UnscheduledDeps <= Dependencies && "invariant"); 2715 } else { 2716 assert(UnscheduledDeps == Dependencies && "invariant"); 2717 } 2718 2719 if (IsScheduled) { 2720 assert(isSchedulingEntity() && 2721 "unexpected scheduled state"); 2722 for (const ScheduleData *BundleMember = this; BundleMember; 2723 BundleMember = BundleMember->NextInBundle) { 2724 assert(BundleMember->hasValidDependencies() && 2725 BundleMember->UnscheduledDeps == 0 && 2726 "unexpected scheduled state"); 2727 assert((BundleMember == this || !BundleMember->IsScheduled) && 2728 "only bundle is marked scheduled"); 2729 } 2730 } 2731 2732 assert(Inst->getParent() == FirstInBundle->Inst->getParent() && 2733 "all bundle members must be in same basic block"); 2734 } 2735 2736 /// Returns true if the dependency information has been calculated. 2737 /// Note that depenendency validity can vary between instructions within 2738 /// a single bundle. 2739 bool hasValidDependencies() const { return Dependencies != InvalidDeps; } 2740 2741 /// Returns true for single instructions and for bundle representatives 2742 /// (= the head of a bundle). 2743 bool isSchedulingEntity() const { return FirstInBundle == this; } 2744 2745 /// Returns true if it represents an instruction bundle and not only a 2746 /// single instruction. 2747 bool isPartOfBundle() const { 2748 return NextInBundle != nullptr || FirstInBundle != this || TE; 2749 } 2750 2751 /// Returns true if it is ready for scheduling, i.e. it has no more 2752 /// unscheduled depending instructions/bundles. 2753 bool isReady() const { 2754 assert(isSchedulingEntity() && 2755 "can't consider non-scheduling entity for ready list"); 2756 return unscheduledDepsInBundle() == 0 && !IsScheduled; 2757 } 2758 2759 /// Modifies the number of unscheduled dependencies for this instruction, 2760 /// and returns the number of remaining dependencies for the containing 2761 /// bundle. 2762 int incrementUnscheduledDeps(int Incr) { 2763 assert(hasValidDependencies() && 2764 "increment of unscheduled deps would be meaningless"); 2765 UnscheduledDeps += Incr; 2766 return FirstInBundle->unscheduledDepsInBundle(); 2767 } 2768 2769 /// Sets the number of unscheduled dependencies to the number of 2770 /// dependencies. 2771 void resetUnscheduledDeps() { 2772 UnscheduledDeps = Dependencies; 2773 } 2774 2775 /// Clears all dependency information. 2776 void clearDependencies() { 2777 Dependencies = InvalidDeps; 2778 resetUnscheduledDeps(); 2779 MemoryDependencies.clear(); 2780 ControlDependencies.clear(); 2781 } 2782 2783 int unscheduledDepsInBundle() const { 2784 assert(isSchedulingEntity() && "only meaningful on the bundle"); 2785 int Sum = 0; 2786 for (const ScheduleData *BundleMember = this; BundleMember; 2787 BundleMember = BundleMember->NextInBundle) { 2788 if (BundleMember->UnscheduledDeps == InvalidDeps) 2789 return InvalidDeps; 2790 Sum += BundleMember->UnscheduledDeps; 2791 } 2792 return Sum; 2793 } 2794 2795 void dump(raw_ostream &os) const { 2796 if (!isSchedulingEntity()) { 2797 os << "/ " << *Inst; 2798 } else if (NextInBundle) { 2799 os << '[' << *Inst; 2800 ScheduleData *SD = NextInBundle; 2801 while (SD) { 2802 os << ';' << *SD->Inst; 2803 SD = SD->NextInBundle; 2804 } 2805 os << ']'; 2806 } else { 2807 os << *Inst; 2808 } 2809 } 2810 2811 Instruction *Inst = nullptr; 2812 2813 /// Opcode of the current instruction in the schedule data. 2814 Value *OpValue = nullptr; 2815 2816 /// The TreeEntry that this instruction corresponds to. 2817 TreeEntry *TE = nullptr; 2818 2819 /// Points to the head in an instruction bundle (and always to this for 2820 /// single instructions). 2821 ScheduleData *FirstInBundle = nullptr; 2822 2823 /// Single linked list of all instructions in a bundle. Null if it is a 2824 /// single instruction. 2825 ScheduleData *NextInBundle = nullptr; 2826 2827 /// Single linked list of all memory instructions (e.g. load, store, call) 2828 /// in the block - until the end of the scheduling region. 2829 ScheduleData *NextLoadStore = nullptr; 2830 2831 /// The dependent memory instructions. 2832 /// This list is derived on demand in calculateDependencies(). 2833 SmallVector<ScheduleData *, 4> MemoryDependencies; 2834 2835 /// List of instructions which this instruction could be control dependent 2836 /// on. Allowing such nodes to be scheduled below this one could introduce 2837 /// a runtime fault which didn't exist in the original program. 2838 /// ex: this is a load or udiv following a readonly call which inf loops 2839 SmallVector<ScheduleData *, 4> ControlDependencies; 2840 2841 /// This ScheduleData is in the current scheduling region if this matches 2842 /// the current SchedulingRegionID of BlockScheduling. 2843 int SchedulingRegionID = 0; 2844 2845 /// Used for getting a "good" final ordering of instructions. 2846 int SchedulingPriority = 0; 2847 2848 /// The number of dependencies. Constitutes of the number of users of the 2849 /// instruction plus the number of dependent memory instructions (if any). 2850 /// This value is calculated on demand. 2851 /// If InvalidDeps, the number of dependencies is not calculated yet. 2852 int Dependencies = InvalidDeps; 2853 2854 /// The number of dependencies minus the number of dependencies of scheduled 2855 /// instructions. As soon as this is zero, the instruction/bundle gets ready 2856 /// for scheduling. 2857 /// Note that this is negative as long as Dependencies is not calculated. 2858 int UnscheduledDeps = InvalidDeps; 2859 2860 /// True if this instruction is scheduled (or considered as scheduled in the 2861 /// dry-run). 2862 bool IsScheduled = false; 2863 }; 2864 2865 #ifndef NDEBUG 2866 friend inline raw_ostream &operator<<(raw_ostream &os, 2867 const BoUpSLP::ScheduleData &SD) { 2868 SD.dump(os); 2869 return os; 2870 } 2871 #endif 2872 2873 friend struct GraphTraits<BoUpSLP *>; 2874 friend struct DOTGraphTraits<BoUpSLP *>; 2875 2876 /// Contains all scheduling data for a basic block. 2877 /// It does not schedules instructions, which are not memory read/write 2878 /// instructions and their operands are either constants, or arguments, or 2879 /// phis, or instructions from others blocks, or their users are phis or from 2880 /// the other blocks. The resulting vector instructions can be placed at the 2881 /// beginning of the basic block without scheduling (if operands does not need 2882 /// to be scheduled) or at the end of the block (if users are outside of the 2883 /// block). It allows to save some compile time and memory used by the 2884 /// compiler. 2885 /// ScheduleData is assigned for each instruction in between the boundaries of 2886 /// the tree entry, even for those, which are not part of the graph. It is 2887 /// required to correctly follow the dependencies between the instructions and 2888 /// their correct scheduling. The ScheduleData is not allocated for the 2889 /// instructions, which do not require scheduling, like phis, nodes with 2890 /// extractelements/insertelements only or nodes with instructions, with 2891 /// uses/operands outside of the block. 2892 struct BlockScheduling { 2893 BlockScheduling(BasicBlock *BB) 2894 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {} 2895 2896 void clear() { 2897 ReadyInsts.clear(); 2898 ScheduleStart = nullptr; 2899 ScheduleEnd = nullptr; 2900 FirstLoadStoreInRegion = nullptr; 2901 LastLoadStoreInRegion = nullptr; 2902 RegionHasStackSave = false; 2903 2904 // Reduce the maximum schedule region size by the size of the 2905 // previous scheduling run. 2906 ScheduleRegionSizeLimit -= ScheduleRegionSize; 2907 if (ScheduleRegionSizeLimit < MinScheduleRegionSize) 2908 ScheduleRegionSizeLimit = MinScheduleRegionSize; 2909 ScheduleRegionSize = 0; 2910 2911 // Make a new scheduling region, i.e. all existing ScheduleData is not 2912 // in the new region yet. 2913 ++SchedulingRegionID; 2914 } 2915 2916 ScheduleData *getScheduleData(Instruction *I) { 2917 if (BB != I->getParent()) 2918 // Avoid lookup if can't possibly be in map. 2919 return nullptr; 2920 ScheduleData *SD = ScheduleDataMap.lookup(I); 2921 if (SD && isInSchedulingRegion(SD)) 2922 return SD; 2923 return nullptr; 2924 } 2925 2926 ScheduleData *getScheduleData(Value *V) { 2927 if (auto *I = dyn_cast<Instruction>(V)) 2928 return getScheduleData(I); 2929 return nullptr; 2930 } 2931 2932 ScheduleData *getScheduleData(Value *V, Value *Key) { 2933 if (V == Key) 2934 return getScheduleData(V); 2935 auto I = ExtraScheduleDataMap.find(V); 2936 if (I != ExtraScheduleDataMap.end()) { 2937 ScheduleData *SD = I->second.lookup(Key); 2938 if (SD && isInSchedulingRegion(SD)) 2939 return SD; 2940 } 2941 return nullptr; 2942 } 2943 2944 bool isInSchedulingRegion(ScheduleData *SD) const { 2945 return SD->SchedulingRegionID == SchedulingRegionID; 2946 } 2947 2948 /// Marks an instruction as scheduled and puts all dependent ready 2949 /// instructions into the ready-list. 2950 template <typename ReadyListType> 2951 void schedule(ScheduleData *SD, ReadyListType &ReadyList) { 2952 SD->IsScheduled = true; 2953 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n"); 2954 2955 for (ScheduleData *BundleMember = SD; BundleMember; 2956 BundleMember = BundleMember->NextInBundle) { 2957 if (BundleMember->Inst != BundleMember->OpValue) 2958 continue; 2959 2960 // Handle the def-use chain dependencies. 2961 2962 // Decrement the unscheduled counter and insert to ready list if ready. 2963 auto &&DecrUnsched = [this, &ReadyList](Instruction *I) { 2964 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) { 2965 if (OpDef && OpDef->hasValidDependencies() && 2966 OpDef->incrementUnscheduledDeps(-1) == 0) { 2967 // There are no more unscheduled dependencies after 2968 // decrementing, so we can put the dependent instruction 2969 // into the ready list. 2970 ScheduleData *DepBundle = OpDef->FirstInBundle; 2971 assert(!DepBundle->IsScheduled && 2972 "already scheduled bundle gets ready"); 2973 ReadyList.insert(DepBundle); 2974 LLVM_DEBUG(dbgs() 2975 << "SLP: gets ready (def): " << *DepBundle << "\n"); 2976 } 2977 }); 2978 }; 2979 2980 // If BundleMember is a vector bundle, its operands may have been 2981 // reordered during buildTree(). We therefore need to get its operands 2982 // through the TreeEntry. 2983 if (TreeEntry *TE = BundleMember->TE) { 2984 // Need to search for the lane since the tree entry can be reordered. 2985 int Lane = std::distance(TE->Scalars.begin(), 2986 find(TE->Scalars, BundleMember->Inst)); 2987 assert(Lane >= 0 && "Lane not set"); 2988 2989 // Since vectorization tree is being built recursively this assertion 2990 // ensures that the tree entry has all operands set before reaching 2991 // this code. Couple of exceptions known at the moment are extracts 2992 // where their second (immediate) operand is not added. Since 2993 // immediates do not affect scheduler behavior this is considered 2994 // okay. 2995 auto *In = BundleMember->Inst; 2996 assert(In && 2997 (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) || 2998 In->getNumOperands() == TE->getNumOperands()) && 2999 "Missed TreeEntry operands?"); 3000 (void)In; // fake use to avoid build failure when assertions disabled 3001 3002 for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands(); 3003 OpIdx != NumOperands; ++OpIdx) 3004 if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane])) 3005 DecrUnsched(I); 3006 } else { 3007 // If BundleMember is a stand-alone instruction, no operand reordering 3008 // has taken place, so we directly access its operands. 3009 for (Use &U : BundleMember->Inst->operands()) 3010 if (auto *I = dyn_cast<Instruction>(U.get())) 3011 DecrUnsched(I); 3012 } 3013 // Handle the memory dependencies. 3014 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) { 3015 if (MemoryDepSD->hasValidDependencies() && 3016 MemoryDepSD->incrementUnscheduledDeps(-1) == 0) { 3017 // There are no more unscheduled dependencies after decrementing, 3018 // so we can put the dependent instruction into the ready list. 3019 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle; 3020 assert(!DepBundle->IsScheduled && 3021 "already scheduled bundle gets ready"); 3022 ReadyList.insert(DepBundle); 3023 LLVM_DEBUG(dbgs() 3024 << "SLP: gets ready (mem): " << *DepBundle << "\n"); 3025 } 3026 } 3027 // Handle the control dependencies. 3028 for (ScheduleData *DepSD : BundleMember->ControlDependencies) { 3029 if (DepSD->incrementUnscheduledDeps(-1) == 0) { 3030 // There are no more unscheduled dependencies after decrementing, 3031 // so we can put the dependent instruction into the ready list. 3032 ScheduleData *DepBundle = DepSD->FirstInBundle; 3033 assert(!DepBundle->IsScheduled && 3034 "already scheduled bundle gets ready"); 3035 ReadyList.insert(DepBundle); 3036 LLVM_DEBUG(dbgs() 3037 << "SLP: gets ready (ctl): " << *DepBundle << "\n"); 3038 } 3039 } 3040 3041 } 3042 } 3043 3044 /// Verify basic self consistency properties of the data structure. 3045 void verify() { 3046 if (!ScheduleStart) 3047 return; 3048 3049 assert(ScheduleStart->getParent() == ScheduleEnd->getParent() && 3050 ScheduleStart->comesBefore(ScheduleEnd) && 3051 "Not a valid scheduling region?"); 3052 3053 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 3054 auto *SD = getScheduleData(I); 3055 if (!SD) 3056 continue; 3057 assert(isInSchedulingRegion(SD) && 3058 "primary schedule data not in window?"); 3059 assert(isInSchedulingRegion(SD->FirstInBundle) && 3060 "entire bundle in window!"); 3061 (void)SD; 3062 doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); }); 3063 } 3064 3065 for (auto *SD : ReadyInsts) { 3066 assert(SD->isSchedulingEntity() && SD->isReady() && 3067 "item in ready list not ready?"); 3068 (void)SD; 3069 } 3070 } 3071 3072 void doForAllOpcodes(Value *V, 3073 function_ref<void(ScheduleData *SD)> Action) { 3074 if (ScheduleData *SD = getScheduleData(V)) 3075 Action(SD); 3076 auto I = ExtraScheduleDataMap.find(V); 3077 if (I != ExtraScheduleDataMap.end()) 3078 for (auto &P : I->second) 3079 if (isInSchedulingRegion(P.second)) 3080 Action(P.second); 3081 } 3082 3083 /// Put all instructions into the ReadyList which are ready for scheduling. 3084 template <typename ReadyListType> 3085 void initialFillReadyList(ReadyListType &ReadyList) { 3086 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 3087 doForAllOpcodes(I, [&](ScheduleData *SD) { 3088 if (SD->isSchedulingEntity() && SD->hasValidDependencies() && 3089 SD->isReady()) { 3090 ReadyList.insert(SD); 3091 LLVM_DEBUG(dbgs() 3092 << "SLP: initially in ready list: " << *SD << "\n"); 3093 } 3094 }); 3095 } 3096 } 3097 3098 /// Build a bundle from the ScheduleData nodes corresponding to the 3099 /// scalar instruction for each lane. 3100 ScheduleData *buildBundle(ArrayRef<Value *> VL); 3101 3102 /// Checks if a bundle of instructions can be scheduled, i.e. has no 3103 /// cyclic dependencies. This is only a dry-run, no instructions are 3104 /// actually moved at this stage. 3105 /// \returns the scheduling bundle. The returned Optional value is non-None 3106 /// if \p VL is allowed to be scheduled. 3107 Optional<ScheduleData *> 3108 tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 3109 const InstructionsState &S); 3110 3111 /// Un-bundles a group of instructions. 3112 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue); 3113 3114 /// Allocates schedule data chunk. 3115 ScheduleData *allocateScheduleDataChunks(); 3116 3117 /// Extends the scheduling region so that V is inside the region. 3118 /// \returns true if the region size is within the limit. 3119 bool extendSchedulingRegion(Value *V, const InstructionsState &S); 3120 3121 /// Initialize the ScheduleData structures for new instructions in the 3122 /// scheduling region. 3123 void initScheduleData(Instruction *FromI, Instruction *ToI, 3124 ScheduleData *PrevLoadStore, 3125 ScheduleData *NextLoadStore); 3126 3127 /// Updates the dependency information of a bundle and of all instructions/ 3128 /// bundles which depend on the original bundle. 3129 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList, 3130 BoUpSLP *SLP); 3131 3132 /// Sets all instruction in the scheduling region to un-scheduled. 3133 void resetSchedule(); 3134 3135 BasicBlock *BB; 3136 3137 /// Simple memory allocation for ScheduleData. 3138 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks; 3139 3140 /// The size of a ScheduleData array in ScheduleDataChunks. 3141 int ChunkSize; 3142 3143 /// The allocator position in the current chunk, which is the last entry 3144 /// of ScheduleDataChunks. 3145 int ChunkPos; 3146 3147 /// Attaches ScheduleData to Instruction. 3148 /// Note that the mapping survives during all vectorization iterations, i.e. 3149 /// ScheduleData structures are recycled. 3150 DenseMap<Instruction *, ScheduleData *> ScheduleDataMap; 3151 3152 /// Attaches ScheduleData to Instruction with the leading key. 3153 DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>> 3154 ExtraScheduleDataMap; 3155 3156 /// The ready-list for scheduling (only used for the dry-run). 3157 SetVector<ScheduleData *> ReadyInsts; 3158 3159 /// The first instruction of the scheduling region. 3160 Instruction *ScheduleStart = nullptr; 3161 3162 /// The first instruction _after_ the scheduling region. 3163 Instruction *ScheduleEnd = nullptr; 3164 3165 /// The first memory accessing instruction in the scheduling region 3166 /// (can be null). 3167 ScheduleData *FirstLoadStoreInRegion = nullptr; 3168 3169 /// The last memory accessing instruction in the scheduling region 3170 /// (can be null). 3171 ScheduleData *LastLoadStoreInRegion = nullptr; 3172 3173 /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling 3174 /// region? Used to optimize the dependence calculation for the 3175 /// common case where there isn't. 3176 bool RegionHasStackSave = false; 3177 3178 /// The current size of the scheduling region. 3179 int ScheduleRegionSize = 0; 3180 3181 /// The maximum size allowed for the scheduling region. 3182 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget; 3183 3184 /// The ID of the scheduling region. For a new vectorization iteration this 3185 /// is incremented which "removes" all ScheduleData from the region. 3186 /// Make sure that the initial SchedulingRegionID is greater than the 3187 /// initial SchedulingRegionID in ScheduleData (which is 0). 3188 int SchedulingRegionID = 1; 3189 }; 3190 3191 /// Attaches the BlockScheduling structures to basic blocks. 3192 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules; 3193 3194 /// Performs the "real" scheduling. Done before vectorization is actually 3195 /// performed in a basic block. 3196 void scheduleBlock(BlockScheduling *BS); 3197 3198 /// List of users to ignore during scheduling and that don't need extracting. 3199 const SmallDenseSet<Value *> *UserIgnoreList = nullptr; 3200 3201 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of 3202 /// sorted SmallVectors of unsigned. 3203 struct OrdersTypeDenseMapInfo { 3204 static OrdersType getEmptyKey() { 3205 OrdersType V; 3206 V.push_back(~1U); 3207 return V; 3208 } 3209 3210 static OrdersType getTombstoneKey() { 3211 OrdersType V; 3212 V.push_back(~2U); 3213 return V; 3214 } 3215 3216 static unsigned getHashValue(const OrdersType &V) { 3217 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 3218 } 3219 3220 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) { 3221 return LHS == RHS; 3222 } 3223 }; 3224 3225 // Analysis and block reference. 3226 Function *F; 3227 ScalarEvolution *SE; 3228 TargetTransformInfo *TTI; 3229 TargetLibraryInfo *TLI; 3230 LoopInfo *LI; 3231 DominatorTree *DT; 3232 AssumptionCache *AC; 3233 DemandedBits *DB; 3234 const DataLayout *DL; 3235 OptimizationRemarkEmitter *ORE; 3236 3237 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt. 3238 unsigned MinVecRegSize; // Set by cl::opt (default: 128). 3239 3240 /// Instruction builder to construct the vectorized tree. 3241 IRBuilder<> Builder; 3242 3243 /// A map of scalar integer values to the smallest bit width with which they 3244 /// can legally be represented. The values map to (width, signed) pairs, 3245 /// where "width" indicates the minimum bit width and "signed" is True if the 3246 /// value must be signed-extended, rather than zero-extended, back to its 3247 /// original width. 3248 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs; 3249 }; 3250 3251 } // end namespace slpvectorizer 3252 3253 template <> struct GraphTraits<BoUpSLP *> { 3254 using TreeEntry = BoUpSLP::TreeEntry; 3255 3256 /// NodeRef has to be a pointer per the GraphWriter. 3257 using NodeRef = TreeEntry *; 3258 3259 using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy; 3260 3261 /// Add the VectorizableTree to the index iterator to be able to return 3262 /// TreeEntry pointers. 3263 struct ChildIteratorType 3264 : public iterator_adaptor_base< 3265 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> { 3266 ContainerTy &VectorizableTree; 3267 3268 ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W, 3269 ContainerTy &VT) 3270 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {} 3271 3272 NodeRef operator*() { return I->UserTE; } 3273 }; 3274 3275 static NodeRef getEntryNode(BoUpSLP &R) { 3276 return R.VectorizableTree[0].get(); 3277 } 3278 3279 static ChildIteratorType child_begin(NodeRef N) { 3280 return {N->UserTreeIndices.begin(), N->Container}; 3281 } 3282 3283 static ChildIteratorType child_end(NodeRef N) { 3284 return {N->UserTreeIndices.end(), N->Container}; 3285 } 3286 3287 /// For the node iterator we just need to turn the TreeEntry iterator into a 3288 /// TreeEntry* iterator so that it dereferences to NodeRef. 3289 class nodes_iterator { 3290 using ItTy = ContainerTy::iterator; 3291 ItTy It; 3292 3293 public: 3294 nodes_iterator(const ItTy &It2) : It(It2) {} 3295 NodeRef operator*() { return It->get(); } 3296 nodes_iterator operator++() { 3297 ++It; 3298 return *this; 3299 } 3300 bool operator!=(const nodes_iterator &N2) const { return N2.It != It; } 3301 }; 3302 3303 static nodes_iterator nodes_begin(BoUpSLP *R) { 3304 return nodes_iterator(R->VectorizableTree.begin()); 3305 } 3306 3307 static nodes_iterator nodes_end(BoUpSLP *R) { 3308 return nodes_iterator(R->VectorizableTree.end()); 3309 } 3310 3311 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); } 3312 }; 3313 3314 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits { 3315 using TreeEntry = BoUpSLP::TreeEntry; 3316 3317 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 3318 3319 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) { 3320 std::string Str; 3321 raw_string_ostream OS(Str); 3322 if (isSplat(Entry->Scalars)) 3323 OS << "<splat> "; 3324 for (auto V : Entry->Scalars) { 3325 OS << *V; 3326 if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) { 3327 return EU.Scalar == V; 3328 })) 3329 OS << " <extract>"; 3330 OS << "\n"; 3331 } 3332 return Str; 3333 } 3334 3335 static std::string getNodeAttributes(const TreeEntry *Entry, 3336 const BoUpSLP *) { 3337 if (Entry->State == TreeEntry::NeedToGather) 3338 return "color=red"; 3339 return ""; 3340 } 3341 }; 3342 3343 } // end namespace llvm 3344 3345 BoUpSLP::~BoUpSLP() { 3346 SmallVector<WeakTrackingVH> DeadInsts; 3347 for (auto *I : DeletedInstructions) { 3348 for (Use &U : I->operands()) { 3349 auto *Op = dyn_cast<Instruction>(U.get()); 3350 if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() && 3351 wouldInstructionBeTriviallyDead(Op, TLI)) 3352 DeadInsts.emplace_back(Op); 3353 } 3354 I->dropAllReferences(); 3355 } 3356 for (auto *I : DeletedInstructions) { 3357 assert(I->use_empty() && 3358 "trying to erase instruction with users."); 3359 I->eraseFromParent(); 3360 } 3361 3362 // Cleanup any dead scalar code feeding the vectorized instructions 3363 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI); 3364 3365 #ifdef EXPENSIVE_CHECKS 3366 // If we could guarantee that this call is not extremely slow, we could 3367 // remove the ifdef limitation (see PR47712). 3368 assert(!verifyFunction(*F, &dbgs())); 3369 #endif 3370 } 3371 3372 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses 3373 /// contains original mask for the scalars reused in the node. Procedure 3374 /// transform this mask in accordance with the given \p Mask. 3375 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) { 3376 assert(!Mask.empty() && Reuses.size() == Mask.size() && 3377 "Expected non-empty mask."); 3378 SmallVector<int> Prev(Reuses.begin(), Reuses.end()); 3379 Prev.swap(Reuses); 3380 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 3381 if (Mask[I] != UndefMaskElem) 3382 Reuses[Mask[I]] = Prev[I]; 3383 } 3384 3385 /// Reorders the given \p Order according to the given \p Mask. \p Order - is 3386 /// the original order of the scalars. Procedure transforms the provided order 3387 /// in accordance with the given \p Mask. If the resulting \p Order is just an 3388 /// identity order, \p Order is cleared. 3389 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) { 3390 assert(!Mask.empty() && "Expected non-empty mask."); 3391 SmallVector<int> MaskOrder; 3392 if (Order.empty()) { 3393 MaskOrder.resize(Mask.size()); 3394 std::iota(MaskOrder.begin(), MaskOrder.end(), 0); 3395 } else { 3396 inversePermutation(Order, MaskOrder); 3397 } 3398 reorderReuses(MaskOrder, Mask); 3399 if (ShuffleVectorInst::isIdentityMask(MaskOrder)) { 3400 Order.clear(); 3401 return; 3402 } 3403 Order.assign(Mask.size(), Mask.size()); 3404 for (unsigned I = 0, E = Mask.size(); I < E; ++I) 3405 if (MaskOrder[I] != UndefMaskElem) 3406 Order[MaskOrder[I]] = I; 3407 fixupOrderingIndices(Order); 3408 } 3409 3410 Optional<BoUpSLP::OrdersType> 3411 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) { 3412 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only."); 3413 unsigned NumScalars = TE.Scalars.size(); 3414 OrdersType CurrentOrder(NumScalars, NumScalars); 3415 SmallVector<int> Positions; 3416 SmallBitVector UsedPositions(NumScalars); 3417 const TreeEntry *STE = nullptr; 3418 // Try to find all gathered scalars that are gets vectorized in other 3419 // vectorize node. Here we can have only one single tree vector node to 3420 // correctly identify order of the gathered scalars. 3421 for (unsigned I = 0; I < NumScalars; ++I) { 3422 Value *V = TE.Scalars[I]; 3423 if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V)) 3424 continue; 3425 if (const auto *LocalSTE = getTreeEntry(V)) { 3426 if (!STE) 3427 STE = LocalSTE; 3428 else if (STE != LocalSTE) 3429 // Take the order only from the single vector node. 3430 return None; 3431 unsigned Lane = 3432 std::distance(STE->Scalars.begin(), find(STE->Scalars, V)); 3433 if (Lane >= NumScalars) 3434 return None; 3435 if (CurrentOrder[Lane] != NumScalars) { 3436 if (Lane != I) 3437 continue; 3438 UsedPositions.reset(CurrentOrder[Lane]); 3439 } 3440 // The partial identity (where only some elements of the gather node are 3441 // in the identity order) is good. 3442 CurrentOrder[Lane] = I; 3443 UsedPositions.set(I); 3444 } 3445 } 3446 // Need to keep the order if we have a vector entry and at least 2 scalars or 3447 // the vectorized entry has just 2 scalars. 3448 if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) { 3449 auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) { 3450 for (unsigned I = 0; I < NumScalars; ++I) 3451 if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars) 3452 return false; 3453 return true; 3454 }; 3455 if (IsIdentityOrder(CurrentOrder)) { 3456 CurrentOrder.clear(); 3457 return CurrentOrder; 3458 } 3459 auto *It = CurrentOrder.begin(); 3460 for (unsigned I = 0; I < NumScalars;) { 3461 if (UsedPositions.test(I)) { 3462 ++I; 3463 continue; 3464 } 3465 if (*It == NumScalars) { 3466 *It = I; 3467 ++I; 3468 } 3469 ++It; 3470 } 3471 return CurrentOrder; 3472 } 3473 return None; 3474 } 3475 3476 namespace { 3477 /// Tracks the state we can represent the loads in the given sequence. 3478 enum class LoadsState { Gather, Vectorize, ScatterVectorize }; 3479 } // anonymous namespace 3480 3481 /// Checks if the given array of loads can be represented as a vectorized, 3482 /// scatter or just simple gather. 3483 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0, 3484 const TargetTransformInfo &TTI, 3485 const DataLayout &DL, ScalarEvolution &SE, 3486 LoopInfo &LI, 3487 SmallVectorImpl<unsigned> &Order, 3488 SmallVectorImpl<Value *> &PointerOps) { 3489 // Check that a vectorized load would load the same memory as a scalar 3490 // load. For example, we don't want to vectorize loads that are smaller 3491 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 3492 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 3493 // from such a struct, we read/write packed bits disagreeing with the 3494 // unvectorized version. 3495 Type *ScalarTy = VL0->getType(); 3496 3497 if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy)) 3498 return LoadsState::Gather; 3499 3500 // Make sure all loads in the bundle are simple - we can't vectorize 3501 // atomic or volatile loads. 3502 PointerOps.clear(); 3503 PointerOps.resize(VL.size()); 3504 auto *POIter = PointerOps.begin(); 3505 for (Value *V : VL) { 3506 auto *L = cast<LoadInst>(V); 3507 if (!L->isSimple()) 3508 return LoadsState::Gather; 3509 *POIter = L->getPointerOperand(); 3510 ++POIter; 3511 } 3512 3513 Order.clear(); 3514 // Check the order of pointer operands or that all pointers are the same. 3515 bool IsSorted = sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order); 3516 if (IsSorted || all_of(PointerOps, [&PointerOps](Value *P) { 3517 if (getUnderlyingObject(P) != getUnderlyingObject(PointerOps.front())) 3518 return false; 3519 auto *GEP = dyn_cast<GetElementPtrInst>(P); 3520 if (!GEP) 3521 return false; 3522 auto *GEP0 = cast<GetElementPtrInst>(PointerOps.front()); 3523 return GEP->getNumOperands() == 2 && 3524 ((isConstant(GEP->getOperand(1)) && 3525 isConstant(GEP0->getOperand(1))) || 3526 getSameOpcode({GEP->getOperand(1), GEP0->getOperand(1)}) 3527 .getOpcode()); 3528 })) { 3529 if (IsSorted) { 3530 Value *Ptr0; 3531 Value *PtrN; 3532 if (Order.empty()) { 3533 Ptr0 = PointerOps.front(); 3534 PtrN = PointerOps.back(); 3535 } else { 3536 Ptr0 = PointerOps[Order.front()]; 3537 PtrN = PointerOps[Order.back()]; 3538 } 3539 Optional<int> Diff = 3540 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE); 3541 // Check that the sorted loads are consecutive. 3542 if (static_cast<unsigned>(*Diff) == VL.size() - 1) 3543 return LoadsState::Vectorize; 3544 } 3545 // TODO: need to improve analysis of the pointers, if not all of them are 3546 // GEPs or have > 2 operands, we end up with a gather node, which just 3547 // increases the cost. 3548 Loop *L = LI.getLoopFor(cast<LoadInst>(VL0)->getParent()); 3549 bool ProfitableGatherPointers = 3550 static_cast<unsigned>(count_if(PointerOps, [L](Value *V) { 3551 return L && L->isLoopInvariant(V); 3552 })) <= VL.size() / 2 && VL.size() > 2; 3553 if (ProfitableGatherPointers || all_of(PointerOps, [IsSorted](Value *P) { 3554 auto *GEP = dyn_cast<GetElementPtrInst>(P); 3555 return (IsSorted && !GEP && doesNotNeedToBeScheduled(P)) || 3556 (GEP && GEP->getNumOperands() == 2); 3557 })) { 3558 Align CommonAlignment = cast<LoadInst>(VL0)->getAlign(); 3559 for (Value *V : VL) 3560 CommonAlignment = 3561 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 3562 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 3563 if (TTI.isLegalMaskedGather(VecTy, CommonAlignment) && 3564 !TTI.forceScalarizeMaskedGather(VecTy, CommonAlignment)) 3565 return LoadsState::ScatterVectorize; 3566 } 3567 } 3568 3569 return LoadsState::Gather; 3570 } 3571 3572 bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy, 3573 const DataLayout &DL, ScalarEvolution &SE, 3574 SmallVectorImpl<unsigned> &SortedIndices) { 3575 assert(llvm::all_of( 3576 VL, [](const Value *V) { return V->getType()->isPointerTy(); }) && 3577 "Expected list of pointer operands."); 3578 // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each 3579 // Ptr into, sort and return the sorted indices with values next to one 3580 // another. 3581 MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases; 3582 Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U)); 3583 3584 unsigned Cnt = 1; 3585 for (Value *Ptr : VL.drop_front()) { 3586 bool Found = any_of(Bases, [&](auto &Base) { 3587 Optional<int> Diff = 3588 getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE, 3589 /*StrictCheck=*/true); 3590 if (!Diff) 3591 return false; 3592 3593 Base.second.emplace_back(Ptr, *Diff, Cnt++); 3594 return true; 3595 }); 3596 3597 if (!Found) { 3598 // If we haven't found enough to usefully cluster, return early. 3599 if (Bases.size() > VL.size() / 2 - 1) 3600 return false; 3601 3602 // Not found already - add a new Base 3603 Bases[Ptr].emplace_back(Ptr, 0, Cnt++); 3604 } 3605 } 3606 3607 // For each of the bases sort the pointers by Offset and check if any of the 3608 // base become consecutively allocated. 3609 bool AnyConsecutive = false; 3610 for (auto &Base : Bases) { 3611 auto &Vec = Base.second; 3612 if (Vec.size() > 1) { 3613 llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X, 3614 const std::tuple<Value *, int, unsigned> &Y) { 3615 return std::get<1>(X) < std::get<1>(Y); 3616 }); 3617 int InitialOffset = std::get<1>(Vec[0]); 3618 AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) { 3619 return std::get<1>(P.value()) == int(P.index()) + InitialOffset; 3620 }); 3621 } 3622 } 3623 3624 // Fill SortedIndices array only if it looks worth-while to sort the ptrs. 3625 SortedIndices.clear(); 3626 if (!AnyConsecutive) 3627 return false; 3628 3629 for (auto &Base : Bases) { 3630 for (auto &T : Base.second) 3631 SortedIndices.push_back(std::get<2>(T)); 3632 } 3633 3634 assert(SortedIndices.size() == VL.size() && 3635 "Expected SortedIndices to be the size of VL"); 3636 return true; 3637 } 3638 3639 Optional<BoUpSLP::OrdersType> 3640 BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) { 3641 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only."); 3642 Type *ScalarTy = TE.Scalars[0]->getType(); 3643 3644 SmallVector<Value *> Ptrs; 3645 Ptrs.reserve(TE.Scalars.size()); 3646 for (Value *V : TE.Scalars) { 3647 auto *L = dyn_cast<LoadInst>(V); 3648 if (!L || !L->isSimple()) 3649 return None; 3650 Ptrs.push_back(L->getPointerOperand()); 3651 } 3652 3653 BoUpSLP::OrdersType Order; 3654 if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order)) 3655 return Order; 3656 return None; 3657 } 3658 3659 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE, 3660 bool TopToBottom) { 3661 // No need to reorder if need to shuffle reuses, still need to shuffle the 3662 // node. 3663 if (!TE.ReuseShuffleIndices.empty()) 3664 return None; 3665 if (TE.State == TreeEntry::Vectorize && 3666 (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) || 3667 (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) && 3668 !TE.isAltShuffle()) 3669 return TE.ReorderIndices; 3670 if (TE.State == TreeEntry::NeedToGather) { 3671 // TODO: add analysis of other gather nodes with extractelement 3672 // instructions and other values/instructions, not only undefs. 3673 if (((TE.getOpcode() == Instruction::ExtractElement && 3674 !TE.isAltShuffle()) || 3675 (all_of(TE.Scalars, 3676 [](Value *V) { 3677 return isa<UndefValue, ExtractElementInst>(V); 3678 }) && 3679 any_of(TE.Scalars, 3680 [](Value *V) { return isa<ExtractElementInst>(V); }))) && 3681 all_of(TE.Scalars, 3682 [](Value *V) { 3683 auto *EE = dyn_cast<ExtractElementInst>(V); 3684 return !EE || isa<FixedVectorType>(EE->getVectorOperandType()); 3685 }) && 3686 allSameType(TE.Scalars)) { 3687 // Check that gather of extractelements can be represented as 3688 // just a shuffle of a single vector. 3689 OrdersType CurrentOrder; 3690 bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder); 3691 if (Reuse || !CurrentOrder.empty()) { 3692 if (!CurrentOrder.empty()) 3693 fixupOrderingIndices(CurrentOrder); 3694 return CurrentOrder; 3695 } 3696 } 3697 if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE)) 3698 return CurrentOrder; 3699 if (TE.Scalars.size() >= 4) 3700 if (Optional<OrdersType> Order = findPartiallyOrderedLoads(TE)) 3701 return Order; 3702 } 3703 return None; 3704 } 3705 3706 void BoUpSLP::reorderTopToBottom() { 3707 // Maps VF to the graph nodes. 3708 DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries; 3709 // ExtractElement gather nodes which can be vectorized and need to handle 3710 // their ordering. 3711 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3712 3713 // Maps a TreeEntry to the reorder indices of external users. 3714 DenseMap<const TreeEntry *, SmallVector<OrdersType, 1>> 3715 ExternalUserReorderMap; 3716 // Find all reorderable nodes with the given VF. 3717 // Currently the are vectorized stores,loads,extracts + some gathering of 3718 // extracts. 3719 for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders, 3720 &ExternalUserReorderMap]( 3721 const std::unique_ptr<TreeEntry> &TE) { 3722 // Look for external users that will probably be vectorized. 3723 SmallVector<OrdersType, 1> ExternalUserReorderIndices = 3724 findExternalStoreUsersReorderIndices(TE.get()); 3725 if (!ExternalUserReorderIndices.empty()) { 3726 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 3727 ExternalUserReorderMap.try_emplace(TE.get(), 3728 std::move(ExternalUserReorderIndices)); 3729 } 3730 3731 if (Optional<OrdersType> CurrentOrder = 3732 getReorderingData(*TE, /*TopToBottom=*/true)) { 3733 // Do not include ordering for nodes used in the alt opcode vectorization, 3734 // better to reorder them during bottom-to-top stage. If follow the order 3735 // here, it causes reordering of the whole graph though actually it is 3736 // profitable just to reorder the subgraph that starts from the alternate 3737 // opcode vectorization node. Such nodes already end-up with the shuffle 3738 // instruction and it is just enough to change this shuffle rather than 3739 // rotate the scalars for the whole graph. 3740 unsigned Cnt = 0; 3741 const TreeEntry *UserTE = TE.get(); 3742 while (UserTE && Cnt < RecursionMaxDepth) { 3743 if (UserTE->UserTreeIndices.size() != 1) 3744 break; 3745 if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) { 3746 return EI.UserTE->State == TreeEntry::Vectorize && 3747 EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0; 3748 })) 3749 return; 3750 UserTE = UserTE->UserTreeIndices.back().UserTE; 3751 ++Cnt; 3752 } 3753 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 3754 if (TE->State != TreeEntry::Vectorize) 3755 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3756 } 3757 }); 3758 3759 // Reorder the graph nodes according to their vectorization factor. 3760 for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1; 3761 VF /= 2) { 3762 auto It = VFToOrderedEntries.find(VF); 3763 if (It == VFToOrderedEntries.end()) 3764 continue; 3765 // Try to find the most profitable order. We just are looking for the most 3766 // used order and reorder scalar elements in the nodes according to this 3767 // mostly used order. 3768 ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef(); 3769 // All operands are reordered and used only in this node - propagate the 3770 // most used order to the user node. 3771 MapVector<OrdersType, unsigned, 3772 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3773 OrdersUses; 3774 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3775 for (const TreeEntry *OpTE : OrderedEntries) { 3776 // No need to reorder this nodes, still need to extend and to use shuffle, 3777 // just need to merge reordering shuffle and the reuse shuffle. 3778 if (!OpTE->ReuseShuffleIndices.empty()) 3779 continue; 3780 // Count number of orders uses. 3781 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3782 if (OpTE->State == TreeEntry::NeedToGather) { 3783 auto It = GathersToOrders.find(OpTE); 3784 if (It != GathersToOrders.end()) 3785 return It->second; 3786 } 3787 return OpTE->ReorderIndices; 3788 }(); 3789 // First consider the order of the external scalar users. 3790 auto It = ExternalUserReorderMap.find(OpTE); 3791 if (It != ExternalUserReorderMap.end()) { 3792 const auto &ExternalUserReorderIndices = It->second; 3793 for (const OrdersType &ExtOrder : ExternalUserReorderIndices) 3794 ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second; 3795 // No other useful reorder data in this entry. 3796 if (Order.empty()) 3797 continue; 3798 } 3799 // Stores actually store the mask, not the order, need to invert. 3800 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3801 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3802 SmallVector<int> Mask; 3803 inversePermutation(Order, Mask); 3804 unsigned E = Order.size(); 3805 OrdersType CurrentOrder(E, E); 3806 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3807 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3808 }); 3809 fixupOrderingIndices(CurrentOrder); 3810 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 3811 } else { 3812 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 3813 } 3814 } 3815 // Set order of the user node. 3816 if (OrdersUses.empty()) 3817 continue; 3818 // Choose the most used order. 3819 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3820 unsigned Cnt = OrdersUses.front().second; 3821 for (const auto &Pair : drop_begin(OrdersUses)) { 3822 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3823 BestOrder = Pair.first; 3824 Cnt = Pair.second; 3825 } 3826 } 3827 // Set order of the user node. 3828 if (BestOrder.empty()) 3829 continue; 3830 SmallVector<int> Mask; 3831 inversePermutation(BestOrder, Mask); 3832 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3833 unsigned E = BestOrder.size(); 3834 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3835 return I < E ? static_cast<int>(I) : UndefMaskElem; 3836 }); 3837 // Do an actual reordering, if profitable. 3838 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 3839 // Just do the reordering for the nodes with the given VF. 3840 if (TE->Scalars.size() != VF) { 3841 if (TE->ReuseShuffleIndices.size() == VF) { 3842 // Need to reorder the reuses masks of the operands with smaller VF to 3843 // be able to find the match between the graph nodes and scalar 3844 // operands of the given node during vectorization/cost estimation. 3845 assert(all_of(TE->UserTreeIndices, 3846 [VF, &TE](const EdgeInfo &EI) { 3847 return EI.UserTE->Scalars.size() == VF || 3848 EI.UserTE->Scalars.size() == 3849 TE->Scalars.size(); 3850 }) && 3851 "All users must be of VF size."); 3852 // Update ordering of the operands with the smaller VF than the given 3853 // one. 3854 reorderReuses(TE->ReuseShuffleIndices, Mask); 3855 } 3856 continue; 3857 } 3858 if (TE->State == TreeEntry::Vectorize && 3859 isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst, 3860 InsertElementInst>(TE->getMainOp()) && 3861 !TE->isAltShuffle()) { 3862 // Build correct orders for extract{element,value}, loads and 3863 // stores. 3864 reorderOrder(TE->ReorderIndices, Mask); 3865 if (isa<InsertElementInst, StoreInst>(TE->getMainOp())) 3866 TE->reorderOperands(Mask); 3867 } else { 3868 // Reorder the node and its operands. 3869 TE->reorderOperands(Mask); 3870 assert(TE->ReorderIndices.empty() && 3871 "Expected empty reorder sequence."); 3872 reorderScalars(TE->Scalars, Mask); 3873 } 3874 if (!TE->ReuseShuffleIndices.empty()) { 3875 // Apply reversed order to keep the original ordering of the reused 3876 // elements to avoid extra reorder indices shuffling. 3877 OrdersType CurrentOrder; 3878 reorderOrder(CurrentOrder, MaskOrder); 3879 SmallVector<int> NewReuses; 3880 inversePermutation(CurrentOrder, NewReuses); 3881 addMask(NewReuses, TE->ReuseShuffleIndices); 3882 TE->ReuseShuffleIndices.swap(NewReuses); 3883 } 3884 } 3885 } 3886 } 3887 3888 bool BoUpSLP::canReorderOperands( 3889 TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges, 3890 ArrayRef<TreeEntry *> ReorderableGathers, 3891 SmallVectorImpl<TreeEntry *> &GatherOps) { 3892 for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) { 3893 if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) { 3894 return OpData.first == I && 3895 OpData.second->State == TreeEntry::Vectorize; 3896 })) 3897 continue; 3898 if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) { 3899 // Do not reorder if operand node is used by many user nodes. 3900 if (any_of(TE->UserTreeIndices, 3901 [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; })) 3902 return false; 3903 // Add the node to the list of the ordered nodes with the identity 3904 // order. 3905 Edges.emplace_back(I, TE); 3906 // Add ScatterVectorize nodes to the list of operands, where just 3907 // reordering of the scalars is required. Similar to the gathers, so 3908 // simply add to the list of gathered ops. 3909 if (TE->State != TreeEntry::Vectorize) 3910 GatherOps.push_back(TE); 3911 continue; 3912 } 3913 ArrayRef<Value *> VL = UserTE->getOperand(I); 3914 TreeEntry *Gather = nullptr; 3915 if (count_if(ReorderableGathers, 3916 [VL, &Gather](TreeEntry *TE) { 3917 assert(TE->State != TreeEntry::Vectorize && 3918 "Only non-vectorized nodes are expected."); 3919 if (TE->isSame(VL)) { 3920 Gather = TE; 3921 return true; 3922 } 3923 return false; 3924 }) > 1 && 3925 !all_of(VL, isConstant)) 3926 return false; 3927 if (Gather) 3928 GatherOps.push_back(Gather); 3929 } 3930 return true; 3931 } 3932 3933 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) { 3934 SetVector<TreeEntry *> OrderedEntries; 3935 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3936 // Find all reorderable leaf nodes with the given VF. 3937 // Currently the are vectorized loads,extracts without alternate operands + 3938 // some gathering of extracts. 3939 SmallVector<TreeEntry *> NonVectorized; 3940 for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders, 3941 &NonVectorized]( 3942 const std::unique_ptr<TreeEntry> &TE) { 3943 if (TE->State != TreeEntry::Vectorize) 3944 NonVectorized.push_back(TE.get()); 3945 if (Optional<OrdersType> CurrentOrder = 3946 getReorderingData(*TE, /*TopToBottom=*/false)) { 3947 OrderedEntries.insert(TE.get()); 3948 if (TE->State != TreeEntry::Vectorize) 3949 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3950 } 3951 }); 3952 3953 // 1. Propagate order to the graph nodes, which use only reordered nodes. 3954 // I.e., if the node has operands, that are reordered, try to make at least 3955 // one operand order in the natural order and reorder others + reorder the 3956 // user node itself. 3957 SmallPtrSet<const TreeEntry *, 4> Visited; 3958 while (!OrderedEntries.empty()) { 3959 // 1. Filter out only reordered nodes. 3960 // 2. If the entry has multiple uses - skip it and jump to the next node. 3961 DenseMap<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users; 3962 SmallVector<TreeEntry *> Filtered; 3963 for (TreeEntry *TE : OrderedEntries) { 3964 if (!(TE->State == TreeEntry::Vectorize || 3965 (TE->State == TreeEntry::NeedToGather && 3966 GathersToOrders.count(TE))) || 3967 TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() || 3968 !all_of(drop_begin(TE->UserTreeIndices), 3969 [TE](const EdgeInfo &EI) { 3970 return EI.UserTE == TE->UserTreeIndices.front().UserTE; 3971 }) || 3972 !Visited.insert(TE).second) { 3973 Filtered.push_back(TE); 3974 continue; 3975 } 3976 // Build a map between user nodes and their operands order to speedup 3977 // search. The graph currently does not provide this dependency directly. 3978 for (EdgeInfo &EI : TE->UserTreeIndices) { 3979 TreeEntry *UserTE = EI.UserTE; 3980 auto It = Users.find(UserTE); 3981 if (It == Users.end()) 3982 It = Users.insert({UserTE, {}}).first; 3983 It->second.emplace_back(EI.EdgeIdx, TE); 3984 } 3985 } 3986 // Erase filtered entries. 3987 for_each(Filtered, 3988 [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); }); 3989 SmallVector< 3990 std::pair<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>>> 3991 UsersVec(Users.begin(), Users.end()); 3992 sort(UsersVec, [](const auto &Data1, const auto &Data2) { 3993 return Data1.first->Idx > Data2.first->Idx; 3994 }); 3995 for (auto &Data : UsersVec) { 3996 // Check that operands are used only in the User node. 3997 SmallVector<TreeEntry *> GatherOps; 3998 if (!canReorderOperands(Data.first, Data.second, NonVectorized, 3999 GatherOps)) { 4000 for_each(Data.second, 4001 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 4002 OrderedEntries.remove(Op.second); 4003 }); 4004 continue; 4005 } 4006 // All operands are reordered and used only in this node - propagate the 4007 // most used order to the user node. 4008 MapVector<OrdersType, unsigned, 4009 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 4010 OrdersUses; 4011 // Do the analysis for each tree entry only once, otherwise the order of 4012 // the same node my be considered several times, though might be not 4013 // profitable. 4014 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 4015 SmallPtrSet<const TreeEntry *, 4> VisitedUsers; 4016 for (const auto &Op : Data.second) { 4017 TreeEntry *OpTE = Op.second; 4018 if (!VisitedOps.insert(OpTE).second) 4019 continue; 4020 if (!OpTE->ReuseShuffleIndices.empty() || 4021 (IgnoreReorder && OpTE == VectorizableTree.front().get())) 4022 continue; 4023 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 4024 if (OpTE->State == TreeEntry::NeedToGather) 4025 return GathersToOrders.find(OpTE)->second; 4026 return OpTE->ReorderIndices; 4027 }(); 4028 unsigned NumOps = count_if( 4029 Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) { 4030 return P.second == OpTE; 4031 }); 4032 // Stores actually store the mask, not the order, need to invert. 4033 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 4034 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 4035 SmallVector<int> Mask; 4036 inversePermutation(Order, Mask); 4037 unsigned E = Order.size(); 4038 OrdersType CurrentOrder(E, E); 4039 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 4040 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 4041 }); 4042 fixupOrderingIndices(CurrentOrder); 4043 OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second += 4044 NumOps; 4045 } else { 4046 OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps; 4047 } 4048 auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0)); 4049 const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders]( 4050 const TreeEntry *TE) { 4051 if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() || 4052 (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) || 4053 (IgnoreReorder && TE->Idx == 0)) 4054 return true; 4055 if (TE->State == TreeEntry::NeedToGather) { 4056 auto It = GathersToOrders.find(TE); 4057 if (It != GathersToOrders.end()) 4058 return !It->second.empty(); 4059 return true; 4060 } 4061 return false; 4062 }; 4063 for (const EdgeInfo &EI : OpTE->UserTreeIndices) { 4064 TreeEntry *UserTE = EI.UserTE; 4065 if (!VisitedUsers.insert(UserTE).second) 4066 continue; 4067 // May reorder user node if it requires reordering, has reused 4068 // scalars, is an alternate op vectorize node or its op nodes require 4069 // reordering. 4070 if (AllowsReordering(UserTE)) 4071 continue; 4072 // Check if users allow reordering. 4073 // Currently look up just 1 level of operands to avoid increase of 4074 // the compile time. 4075 // Profitable to reorder if definitely more operands allow 4076 // reordering rather than those with natural order. 4077 ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE]; 4078 if (static_cast<unsigned>(count_if( 4079 Ops, [UserTE, &AllowsReordering]( 4080 const std::pair<unsigned, TreeEntry *> &Op) { 4081 return AllowsReordering(Op.second) && 4082 all_of(Op.second->UserTreeIndices, 4083 [UserTE](const EdgeInfo &EI) { 4084 return EI.UserTE == UserTE; 4085 }); 4086 })) <= Ops.size() / 2) 4087 ++Res.first->second; 4088 } 4089 } 4090 // If no orders - skip current nodes and jump to the next one, if any. 4091 if (OrdersUses.empty()) { 4092 for_each(Data.second, 4093 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 4094 OrderedEntries.remove(Op.second); 4095 }); 4096 continue; 4097 } 4098 // Choose the best order. 4099 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 4100 unsigned Cnt = OrdersUses.front().second; 4101 for (const auto &Pair : drop_begin(OrdersUses)) { 4102 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 4103 BestOrder = Pair.first; 4104 Cnt = Pair.second; 4105 } 4106 } 4107 // Set order of the user node (reordering of operands and user nodes). 4108 if (BestOrder.empty()) { 4109 for_each(Data.second, 4110 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 4111 OrderedEntries.remove(Op.second); 4112 }); 4113 continue; 4114 } 4115 // Erase operands from OrderedEntries list and adjust their orders. 4116 VisitedOps.clear(); 4117 SmallVector<int> Mask; 4118 inversePermutation(BestOrder, Mask); 4119 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 4120 unsigned E = BestOrder.size(); 4121 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 4122 return I < E ? static_cast<int>(I) : UndefMaskElem; 4123 }); 4124 for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) { 4125 TreeEntry *TE = Op.second; 4126 OrderedEntries.remove(TE); 4127 if (!VisitedOps.insert(TE).second) 4128 continue; 4129 if (TE->ReuseShuffleIndices.size() == BestOrder.size()) { 4130 // Just reorder reuses indices. 4131 reorderReuses(TE->ReuseShuffleIndices, Mask); 4132 continue; 4133 } 4134 // Gathers are processed separately. 4135 if (TE->State != TreeEntry::Vectorize) 4136 continue; 4137 assert((BestOrder.size() == TE->ReorderIndices.size() || 4138 TE->ReorderIndices.empty()) && 4139 "Non-matching sizes of user/operand entries."); 4140 reorderOrder(TE->ReorderIndices, Mask); 4141 } 4142 // For gathers just need to reorder its scalars. 4143 for (TreeEntry *Gather : GatherOps) { 4144 assert(Gather->ReorderIndices.empty() && 4145 "Unexpected reordering of gathers."); 4146 if (!Gather->ReuseShuffleIndices.empty()) { 4147 // Just reorder reuses indices. 4148 reorderReuses(Gather->ReuseShuffleIndices, Mask); 4149 continue; 4150 } 4151 reorderScalars(Gather->Scalars, Mask); 4152 OrderedEntries.remove(Gather); 4153 } 4154 // Reorder operands of the user node and set the ordering for the user 4155 // node itself. 4156 if (Data.first->State != TreeEntry::Vectorize || 4157 !isa<ExtractElementInst, ExtractValueInst, LoadInst>( 4158 Data.first->getMainOp()) || 4159 Data.first->isAltShuffle()) 4160 Data.first->reorderOperands(Mask); 4161 if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) || 4162 Data.first->isAltShuffle()) { 4163 reorderScalars(Data.first->Scalars, Mask); 4164 reorderOrder(Data.first->ReorderIndices, MaskOrder); 4165 if (Data.first->ReuseShuffleIndices.empty() && 4166 !Data.first->ReorderIndices.empty() && 4167 !Data.first->isAltShuffle()) { 4168 // Insert user node to the list to try to sink reordering deeper in 4169 // the graph. 4170 OrderedEntries.insert(Data.first); 4171 } 4172 } else { 4173 reorderOrder(Data.first->ReorderIndices, Mask); 4174 } 4175 } 4176 } 4177 // If the reordering is unnecessary, just remove the reorder. 4178 if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() && 4179 VectorizableTree.front()->ReuseShuffleIndices.empty()) 4180 VectorizableTree.front()->ReorderIndices.clear(); 4181 } 4182 4183 void BoUpSLP::buildExternalUses( 4184 const ExtraValueToDebugLocsMap &ExternallyUsedValues) { 4185 // Collect the values that we need to extract from the tree. 4186 for (auto &TEPtr : VectorizableTree) { 4187 TreeEntry *Entry = TEPtr.get(); 4188 4189 // No need to handle users of gathered values. 4190 if (Entry->State == TreeEntry::NeedToGather) 4191 continue; 4192 4193 // For each lane: 4194 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 4195 Value *Scalar = Entry->Scalars[Lane]; 4196 int FoundLane = Entry->findLaneForValue(Scalar); 4197 4198 // Check if the scalar is externally used as an extra arg. 4199 auto ExtI = ExternallyUsedValues.find(Scalar); 4200 if (ExtI != ExternallyUsedValues.end()) { 4201 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " 4202 << Lane << " from " << *Scalar << ".\n"); 4203 ExternalUses.emplace_back(Scalar, nullptr, FoundLane); 4204 } 4205 for (User *U : Scalar->users()) { 4206 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n"); 4207 4208 Instruction *UserInst = dyn_cast<Instruction>(U); 4209 if (!UserInst) 4210 continue; 4211 4212 if (isDeleted(UserInst)) 4213 continue; 4214 4215 // Skip in-tree scalars that become vectors 4216 if (TreeEntry *UseEntry = getTreeEntry(U)) { 4217 Value *UseScalar = UseEntry->Scalars[0]; 4218 // Some in-tree scalars will remain as scalar in vectorized 4219 // instructions. If that is the case, the one in Lane 0 will 4220 // be used. 4221 if (UseScalar != U || 4222 UseEntry->State == TreeEntry::ScatterVectorize || 4223 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) { 4224 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U 4225 << ".\n"); 4226 assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state"); 4227 continue; 4228 } 4229 } 4230 4231 // Ignore users in the user ignore list. 4232 if (UserIgnoreList && UserIgnoreList->contains(UserInst)) 4233 continue; 4234 4235 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " 4236 << Lane << " from " << *Scalar << ".\n"); 4237 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane)); 4238 } 4239 } 4240 } 4241 } 4242 4243 DenseMap<Value *, SmallVector<StoreInst *, 4>> 4244 BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const { 4245 DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap; 4246 for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) { 4247 Value *V = TE->Scalars[Lane]; 4248 // To save compilation time we don't visit if we have too many users. 4249 static constexpr unsigned UsersLimit = 4; 4250 if (V->hasNUsesOrMore(UsersLimit)) 4251 break; 4252 4253 // Collect stores per pointer object. 4254 for (User *U : V->users()) { 4255 auto *SI = dyn_cast<StoreInst>(U); 4256 if (SI == nullptr || !SI->isSimple() || 4257 !isValidElementType(SI->getValueOperand()->getType())) 4258 continue; 4259 // Skip entry if already 4260 if (getTreeEntry(U)) 4261 continue; 4262 4263 Value *Ptr = getUnderlyingObject(SI->getPointerOperand()); 4264 auto &StoresVec = PtrToStoresMap[Ptr]; 4265 // For now just keep one store per pointer object per lane. 4266 // TODO: Extend this to support multiple stores per pointer per lane 4267 if (StoresVec.size() > Lane) 4268 continue; 4269 // Skip if in different BBs. 4270 if (!StoresVec.empty() && 4271 SI->getParent() != StoresVec.back()->getParent()) 4272 continue; 4273 // Make sure that the stores are of the same type. 4274 if (!StoresVec.empty() && 4275 SI->getValueOperand()->getType() != 4276 StoresVec.back()->getValueOperand()->getType()) 4277 continue; 4278 StoresVec.push_back(SI); 4279 } 4280 } 4281 return PtrToStoresMap; 4282 } 4283 4284 bool BoUpSLP::CanFormVector(const SmallVector<StoreInst *, 4> &StoresVec, 4285 OrdersType &ReorderIndices) const { 4286 // We check whether the stores in StoreVec can form a vector by sorting them 4287 // and checking whether they are consecutive. 4288 4289 // To avoid calling getPointersDiff() while sorting we create a vector of 4290 // pairs {store, offset from first} and sort this instead. 4291 SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size()); 4292 StoreInst *S0 = StoresVec[0]; 4293 StoreOffsetVec[0] = {S0, 0}; 4294 Type *S0Ty = S0->getValueOperand()->getType(); 4295 Value *S0Ptr = S0->getPointerOperand(); 4296 for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) { 4297 StoreInst *SI = StoresVec[Idx]; 4298 Optional<int> Diff = 4299 getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(), 4300 SI->getPointerOperand(), *DL, *SE, 4301 /*StrictCheck=*/true); 4302 // We failed to compare the pointers so just abandon this StoresVec. 4303 if (!Diff) 4304 return false; 4305 StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff}; 4306 } 4307 4308 // Sort the vector based on the pointers. We create a copy because we may 4309 // need the original later for calculating the reorder (shuffle) indices. 4310 stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1, 4311 const std::pair<StoreInst *, int> &Pair2) { 4312 int Offset1 = Pair1.second; 4313 int Offset2 = Pair2.second; 4314 return Offset1 < Offset2; 4315 }); 4316 4317 // Check if the stores are consecutive by checking if their difference is 1. 4318 for (unsigned Idx : seq<unsigned>(1, StoreOffsetVec.size())) 4319 if (StoreOffsetVec[Idx].second != StoreOffsetVec[Idx-1].second + 1) 4320 return false; 4321 4322 // Calculate the shuffle indices according to their offset against the sorted 4323 // StoreOffsetVec. 4324 ReorderIndices.reserve(StoresVec.size()); 4325 for (StoreInst *SI : StoresVec) { 4326 unsigned Idx = find_if(StoreOffsetVec, 4327 [SI](const std::pair<StoreInst *, int> &Pair) { 4328 return Pair.first == SI; 4329 }) - 4330 StoreOffsetVec.begin(); 4331 ReorderIndices.push_back(Idx); 4332 } 4333 // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in 4334 // reorderTopToBottom() and reorderBottomToTop(), so we are following the 4335 // same convention here. 4336 auto IsIdentityOrder = [](const OrdersType &Order) { 4337 for (unsigned Idx : seq<unsigned>(0, Order.size())) 4338 if (Idx != Order[Idx]) 4339 return false; 4340 return true; 4341 }; 4342 if (IsIdentityOrder(ReorderIndices)) 4343 ReorderIndices.clear(); 4344 4345 return true; 4346 } 4347 4348 #ifndef NDEBUG 4349 LLVM_DUMP_METHOD static void dumpOrder(const BoUpSLP::OrdersType &Order) { 4350 for (unsigned Idx : Order) 4351 dbgs() << Idx << ", "; 4352 dbgs() << "\n"; 4353 } 4354 #endif 4355 4356 SmallVector<BoUpSLP::OrdersType, 1> 4357 BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const { 4358 unsigned NumLanes = TE->Scalars.size(); 4359 4360 DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap = 4361 collectUserStores(TE); 4362 4363 // Holds the reorder indices for each candidate store vector that is a user of 4364 // the current TreeEntry. 4365 SmallVector<OrdersType, 1> ExternalReorderIndices; 4366 4367 // Now inspect the stores collected per pointer and look for vectorization 4368 // candidates. For each candidate calculate the reorder index vector and push 4369 // it into `ExternalReorderIndices` 4370 for (const auto &Pair : PtrToStoresMap) { 4371 auto &StoresVec = Pair.second; 4372 // If we have fewer than NumLanes stores, then we can't form a vector. 4373 if (StoresVec.size() != NumLanes) 4374 continue; 4375 4376 // If the stores are not consecutive then abandon this StoresVec. 4377 OrdersType ReorderIndices; 4378 if (!CanFormVector(StoresVec, ReorderIndices)) 4379 continue; 4380 4381 // We now know that the scalars in StoresVec can form a vector instruction, 4382 // so set the reorder indices. 4383 ExternalReorderIndices.push_back(ReorderIndices); 4384 } 4385 return ExternalReorderIndices; 4386 } 4387 4388 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, 4389 const SmallDenseSet<Value *> &UserIgnoreLst) { 4390 deleteTree(); 4391 UserIgnoreList = &UserIgnoreLst; 4392 if (!allSameType(Roots)) 4393 return; 4394 buildTree_rec(Roots, 0, EdgeInfo()); 4395 } 4396 4397 void BoUpSLP::buildTree(ArrayRef<Value *> Roots) { 4398 deleteTree(); 4399 if (!allSameType(Roots)) 4400 return; 4401 buildTree_rec(Roots, 0, EdgeInfo()); 4402 } 4403 4404 /// \return true if the specified list of values has only one instruction that 4405 /// requires scheduling, false otherwise. 4406 #ifndef NDEBUG 4407 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) { 4408 Value *NeedsScheduling = nullptr; 4409 for (Value *V : VL) { 4410 if (doesNotNeedToBeScheduled(V)) 4411 continue; 4412 if (!NeedsScheduling) { 4413 NeedsScheduling = V; 4414 continue; 4415 } 4416 return false; 4417 } 4418 return NeedsScheduling; 4419 } 4420 #endif 4421 4422 /// Generates key/subkey pair for the given value to provide effective sorting 4423 /// of the values and better detection of the vectorizable values sequences. The 4424 /// keys/subkeys can be used for better sorting of the values themselves (keys) 4425 /// and in values subgroups (subkeys). 4426 static std::pair<size_t, size_t> generateKeySubkey( 4427 Value *V, const TargetLibraryInfo *TLI, 4428 function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator, 4429 bool AllowAlternate) { 4430 hash_code Key = hash_value(V->getValueID() + 2); 4431 hash_code SubKey = hash_value(0); 4432 // Sort the loads by the distance between the pointers. 4433 if (auto *LI = dyn_cast<LoadInst>(V)) { 4434 Key = hash_combine(hash_value(Instruction::Load), Key); 4435 if (LI->isSimple()) 4436 SubKey = hash_value(LoadsSubkeyGenerator(Key, LI)); 4437 else 4438 SubKey = hash_value(LI); 4439 } else if (isVectorLikeInstWithConstOps(V)) { 4440 // Sort extracts by the vector operands. 4441 if (isa<ExtractElementInst, UndefValue>(V)) 4442 Key = hash_value(Value::UndefValueVal + 1); 4443 if (auto *EI = dyn_cast<ExtractElementInst>(V)) { 4444 if (!isUndefVector(EI->getVectorOperand()) && 4445 !isa<UndefValue>(EI->getIndexOperand())) 4446 SubKey = hash_value(EI->getVectorOperand()); 4447 } 4448 } else if (auto *I = dyn_cast<Instruction>(V)) { 4449 // Sort other instructions just by the opcodes except for CMPInst. 4450 // For CMP also sort by the predicate kind. 4451 if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) && 4452 isValidForAlternation(I->getOpcode())) { 4453 if (AllowAlternate) 4454 Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0); 4455 else 4456 Key = hash_combine(hash_value(I->getOpcode()), Key); 4457 SubKey = hash_combine( 4458 hash_value(I->getOpcode()), hash_value(I->getType()), 4459 hash_value(isa<BinaryOperator>(I) 4460 ? I->getType() 4461 : cast<CastInst>(I)->getOperand(0)->getType())); 4462 // For casts, look through the only operand to improve compile time. 4463 if (isa<CastInst>(I)) { 4464 std::pair<size_t, size_t> OpVals = 4465 generateKeySubkey(I->getOperand(0), TLI, LoadsSubkeyGenerator, 4466 /*=AllowAlternate*/ true); 4467 Key = hash_combine(OpVals.first, Key); 4468 SubKey = hash_combine(OpVals.first, SubKey); 4469 } 4470 } else if (auto *CI = dyn_cast<CmpInst>(I)) { 4471 CmpInst::Predicate Pred = CI->getPredicate(); 4472 if (CI->isCommutative()) 4473 Pred = std::min(Pred, CmpInst::getInversePredicate(Pred)); 4474 CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred); 4475 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred), 4476 hash_value(SwapPred), 4477 hash_value(CI->getOperand(0)->getType())); 4478 } else if (auto *Call = dyn_cast<CallInst>(I)) { 4479 Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI); 4480 if (isTriviallyVectorizable(ID)) { 4481 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID)); 4482 } else if (!VFDatabase(*Call).getMappings(*Call).empty()) { 4483 SubKey = hash_combine(hash_value(I->getOpcode()), 4484 hash_value(Call->getCalledFunction())); 4485 } else { 4486 Key = hash_combine(hash_value(Call), Key); 4487 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call)); 4488 } 4489 for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos()) 4490 SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End), 4491 hash_value(Op.Tag), SubKey); 4492 } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) { 4493 if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1))) 4494 SubKey = hash_value(Gep->getPointerOperand()); 4495 else 4496 SubKey = hash_value(Gep); 4497 } else if (BinaryOperator::isIntDivRem(I->getOpcode()) && 4498 !isa<ConstantInt>(I->getOperand(1))) { 4499 // Do not try to vectorize instructions with potentially high cost. 4500 SubKey = hash_value(I); 4501 } else { 4502 SubKey = hash_value(I->getOpcode()); 4503 } 4504 Key = hash_combine(hash_value(I->getParent()), Key); 4505 } 4506 return std::make_pair(Key, SubKey); 4507 } 4508 4509 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth, 4510 const EdgeInfo &UserTreeIdx) { 4511 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!"); 4512 4513 SmallVector<int> ReuseShuffleIndicies; 4514 SmallVector<Value *> UniqueValues; 4515 auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues, 4516 &UserTreeIdx, 4517 this](const InstructionsState &S) { 4518 // Check that every instruction appears once in this bundle. 4519 DenseMap<Value *, unsigned> UniquePositions; 4520 for (Value *V : VL) { 4521 if (isConstant(V)) { 4522 ReuseShuffleIndicies.emplace_back( 4523 isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size()); 4524 UniqueValues.emplace_back(V); 4525 continue; 4526 } 4527 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 4528 ReuseShuffleIndicies.emplace_back(Res.first->second); 4529 if (Res.second) 4530 UniqueValues.emplace_back(V); 4531 } 4532 size_t NumUniqueScalarValues = UniqueValues.size(); 4533 if (NumUniqueScalarValues == VL.size()) { 4534 ReuseShuffleIndicies.clear(); 4535 } else { 4536 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n"); 4537 if (NumUniqueScalarValues <= 1 || 4538 (UniquePositions.size() == 1 && all_of(UniqueValues, 4539 [](Value *V) { 4540 return isa<UndefValue>(V) || 4541 !isConstant(V); 4542 })) || 4543 !llvm::isPowerOf2_32(NumUniqueScalarValues)) { 4544 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); 4545 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4546 return false; 4547 } 4548 VL = UniqueValues; 4549 } 4550 return true; 4551 }; 4552 4553 InstructionsState S = getSameOpcode(VL); 4554 if (Depth == RecursionMaxDepth) { 4555 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); 4556 if (TryToFindDuplicates(S)) 4557 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4558 ReuseShuffleIndicies); 4559 return; 4560 } 4561 4562 // Don't handle scalable vectors 4563 if (S.getOpcode() == Instruction::ExtractElement && 4564 isa<ScalableVectorType>( 4565 cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) { 4566 LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n"); 4567 if (TryToFindDuplicates(S)) 4568 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4569 ReuseShuffleIndicies); 4570 return; 4571 } 4572 4573 // Don't handle vectors. 4574 if (S.OpValue->getType()->isVectorTy() && 4575 !isa<InsertElementInst>(S.OpValue)) { 4576 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); 4577 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4578 return; 4579 } 4580 4581 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue)) 4582 if (SI->getValueOperand()->getType()->isVectorTy()) { 4583 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); 4584 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4585 return; 4586 } 4587 4588 // If all of the operands are identical or constant we have a simple solution. 4589 // If we deal with insert/extract instructions, they all must have constant 4590 // indices, otherwise we should gather them, not try to vectorize. 4591 // If alternate op node with 2 elements with gathered operands - do not 4592 // vectorize. 4593 auto &&NotProfitableForVectorization = [&S, this, 4594 Depth](ArrayRef<Value *> VL) { 4595 if (!S.getOpcode() || !S.isAltShuffle() || VL.size() > 2) 4596 return false; 4597 if (VectorizableTree.size() < MinTreeSize) 4598 return false; 4599 if (Depth >= RecursionMaxDepth - 1) 4600 return true; 4601 // Check if all operands are extracts, part of vector node or can build a 4602 // regular vectorize node. 4603 SmallVector<unsigned, 2> InstsCount(VL.size(), 0); 4604 for (Value *V : VL) { 4605 auto *I = cast<Instruction>(V); 4606 InstsCount.push_back(count_if(I->operand_values(), [](Value *Op) { 4607 return isa<Instruction>(Op) || isVectorLikeInstWithConstOps(Op); 4608 })); 4609 } 4610 bool IsCommutative = isCommutative(S.MainOp) || isCommutative(S.AltOp); 4611 if ((IsCommutative && 4612 std::accumulate(InstsCount.begin(), InstsCount.end(), 0) < 2) || 4613 (!IsCommutative && 4614 all_of(InstsCount, [](unsigned ICnt) { return ICnt < 2; }))) 4615 return true; 4616 assert(VL.size() == 2 && "Expected only 2 alternate op instructions."); 4617 SmallVector<SmallVector<std::pair<Value *, Value *>>> Candidates; 4618 auto *I1 = cast<Instruction>(VL.front()); 4619 auto *I2 = cast<Instruction>(VL.back()); 4620 for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op) 4621 Candidates.emplace_back().emplace_back(I1->getOperand(Op), 4622 I2->getOperand(Op)); 4623 if (static_cast<unsigned>(count_if( 4624 Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) { 4625 return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat); 4626 })) >= S.MainOp->getNumOperands() / 2) 4627 return false; 4628 if (S.MainOp->getNumOperands() > 2) 4629 return true; 4630 if (IsCommutative) { 4631 // Check permuted operands. 4632 Candidates.clear(); 4633 for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op) 4634 Candidates.emplace_back().emplace_back(I1->getOperand(Op), 4635 I2->getOperand((Op + 1) % E)); 4636 if (any_of( 4637 Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) { 4638 return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat); 4639 })) 4640 return false; 4641 } 4642 return true; 4643 }; 4644 SmallVector<unsigned> SortedIndices; 4645 BasicBlock *BB = nullptr; 4646 bool AreAllSameInsts = 4647 (S.getOpcode() && allSameBlock(VL)) || 4648 (S.OpValue->getType()->isPointerTy() && UserTreeIdx.UserTE && 4649 UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize && 4650 VL.size() > 2 && 4651 all_of(VL, 4652 [&BB](Value *V) { 4653 auto *I = dyn_cast<GetElementPtrInst>(V); 4654 if (!I) 4655 return doesNotNeedToBeScheduled(V); 4656 if (!BB) 4657 BB = I->getParent(); 4658 return BB == I->getParent() && I->getNumOperands() == 2; 4659 }) && 4660 BB && 4661 sortPtrAccesses(VL, UserTreeIdx.UserTE->getMainOp()->getType(), *DL, *SE, 4662 SortedIndices)); 4663 if (allConstant(VL) || isSplat(VL) || !AreAllSameInsts || 4664 (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>( 4665 S.OpValue) && 4666 !all_of(VL, isVectorLikeInstWithConstOps)) || 4667 NotProfitableForVectorization(VL)) { 4668 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O, small shuffle. \n"); 4669 if (TryToFindDuplicates(S)) 4670 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4671 ReuseShuffleIndicies); 4672 return; 4673 } 4674 4675 // We now know that this is a vector of instructions of the same type from 4676 // the same block. 4677 4678 // Don't vectorize ephemeral values. 4679 if (!EphValues.empty()) { 4680 for (Value *V : VL) { 4681 if (EphValues.count(V)) { 4682 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 4683 << ") is ephemeral.\n"); 4684 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4685 return; 4686 } 4687 } 4688 } 4689 4690 // Check if this is a duplicate of another entry. 4691 if (TreeEntry *E = getTreeEntry(S.OpValue)) { 4692 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n"); 4693 if (!E->isSame(VL)) { 4694 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); 4695 if (TryToFindDuplicates(S)) 4696 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4697 ReuseShuffleIndicies); 4698 return; 4699 } 4700 // Record the reuse of the tree node. FIXME, currently this is only used to 4701 // properly draw the graph rather than for the actual vectorization. 4702 E->UserTreeIndices.push_back(UserTreeIdx); 4703 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue 4704 << ".\n"); 4705 return; 4706 } 4707 4708 // Check that none of the instructions in the bundle are already in the tree. 4709 for (Value *V : VL) { 4710 auto *I = dyn_cast<Instruction>(V); 4711 if (!I) 4712 continue; 4713 if (getTreeEntry(I)) { 4714 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 4715 << ") is already in tree.\n"); 4716 if (TryToFindDuplicates(S)) 4717 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4718 ReuseShuffleIndicies); 4719 return; 4720 } 4721 } 4722 4723 // The reduction nodes (stored in UserIgnoreList) also should stay scalar. 4724 if (UserIgnoreList && !UserIgnoreList->empty()) { 4725 for (Value *V : VL) { 4726 if (UserIgnoreList && UserIgnoreList->contains(V)) { 4727 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n"); 4728 if (TryToFindDuplicates(S)) 4729 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4730 ReuseShuffleIndicies); 4731 return; 4732 } 4733 } 4734 } 4735 4736 // Special processing for sorted pointers for ScatterVectorize node with 4737 // constant indeces only. 4738 if (AreAllSameInsts && !(S.getOpcode() && allSameBlock(VL)) && 4739 UserTreeIdx.UserTE && 4740 UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize) { 4741 assert(S.OpValue->getType()->isPointerTy() && 4742 count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >= 4743 2 && 4744 "Expected pointers only."); 4745 // Reset S to make it GetElementPtr kind of node. 4746 const auto *It = find_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }); 4747 assert(It != VL.end() && "Expected at least one GEP."); 4748 S = getSameOpcode(*It); 4749 } 4750 4751 // Check that all of the users of the scalars that we want to vectorize are 4752 // schedulable. 4753 auto *VL0 = cast<Instruction>(S.OpValue); 4754 BB = VL0->getParent(); 4755 4756 if (!DT->isReachableFromEntry(BB)) { 4757 // Don't go into unreachable blocks. They may contain instructions with 4758 // dependency cycles which confuse the final scheduling. 4759 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n"); 4760 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4761 return; 4762 } 4763 4764 // Check that every instruction appears once in this bundle. 4765 if (!TryToFindDuplicates(S)) 4766 return; 4767 4768 auto &BSRef = BlocksSchedules[BB]; 4769 if (!BSRef) 4770 BSRef = std::make_unique<BlockScheduling>(BB); 4771 4772 BlockScheduling &BS = *BSRef; 4773 4774 Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S); 4775 #ifdef EXPENSIVE_CHECKS 4776 // Make sure we didn't break any internal invariants 4777 BS.verify(); 4778 #endif 4779 if (!Bundle) { 4780 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n"); 4781 assert((!BS.getScheduleData(VL0) || 4782 !BS.getScheduleData(VL0)->isPartOfBundle()) && 4783 "tryScheduleBundle should cancelScheduling on failure"); 4784 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4785 ReuseShuffleIndicies); 4786 return; 4787 } 4788 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); 4789 4790 unsigned ShuffleOrOp = S.isAltShuffle() ? 4791 (unsigned) Instruction::ShuffleVector : S.getOpcode(); 4792 switch (ShuffleOrOp) { 4793 case Instruction::PHI: { 4794 auto *PH = cast<PHINode>(VL0); 4795 4796 // Check for terminator values (e.g. invoke). 4797 for (Value *V : VL) 4798 for (Value *Incoming : cast<PHINode>(V)->incoming_values()) { 4799 Instruction *Term = dyn_cast<Instruction>(Incoming); 4800 if (Term && Term->isTerminator()) { 4801 LLVM_DEBUG(dbgs() 4802 << "SLP: Need to swizzle PHINodes (terminator use).\n"); 4803 BS.cancelScheduling(VL, VL0); 4804 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4805 ReuseShuffleIndicies); 4806 return; 4807 } 4808 } 4809 4810 TreeEntry *TE = 4811 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies); 4812 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); 4813 4814 // Keeps the reordered operands to avoid code duplication. 4815 SmallVector<ValueList, 2> OperandsVec; 4816 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 4817 if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) { 4818 ValueList Operands(VL.size(), PoisonValue::get(PH->getType())); 4819 TE->setOperand(I, Operands); 4820 OperandsVec.push_back(Operands); 4821 continue; 4822 } 4823 ValueList Operands; 4824 // Prepare the operand vector. 4825 for (Value *V : VL) 4826 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock( 4827 PH->getIncomingBlock(I))); 4828 TE->setOperand(I, Operands); 4829 OperandsVec.push_back(Operands); 4830 } 4831 for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx) 4832 buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx}); 4833 return; 4834 } 4835 case Instruction::ExtractValue: 4836 case Instruction::ExtractElement: { 4837 OrdersType CurrentOrder; 4838 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder); 4839 if (Reuse) { 4840 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n"); 4841 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4842 ReuseShuffleIndicies); 4843 // This is a special case, as it does not gather, but at the same time 4844 // we are not extending buildTree_rec() towards the operands. 4845 ValueList Op0; 4846 Op0.assign(VL.size(), VL0->getOperand(0)); 4847 VectorizableTree.back()->setOperand(0, Op0); 4848 return; 4849 } 4850 if (!CurrentOrder.empty()) { 4851 LLVM_DEBUG({ 4852 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " 4853 "with order"; 4854 for (unsigned Idx : CurrentOrder) 4855 dbgs() << " " << Idx; 4856 dbgs() << "\n"; 4857 }); 4858 fixupOrderingIndices(CurrentOrder); 4859 // Insert new order with initial value 0, if it does not exist, 4860 // otherwise return the iterator to the existing one. 4861 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4862 ReuseShuffleIndicies, CurrentOrder); 4863 // This is a special case, as it does not gather, but at the same time 4864 // we are not extending buildTree_rec() towards the operands. 4865 ValueList Op0; 4866 Op0.assign(VL.size(), VL0->getOperand(0)); 4867 VectorizableTree.back()->setOperand(0, Op0); 4868 return; 4869 } 4870 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n"); 4871 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4872 ReuseShuffleIndicies); 4873 BS.cancelScheduling(VL, VL0); 4874 return; 4875 } 4876 case Instruction::InsertElement: { 4877 assert(ReuseShuffleIndicies.empty() && "All inserts should be unique"); 4878 4879 // Check that we have a buildvector and not a shuffle of 2 or more 4880 // different vectors. 4881 ValueSet SourceVectors; 4882 for (Value *V : VL) { 4883 SourceVectors.insert(cast<Instruction>(V)->getOperand(0)); 4884 assert(getInsertIndex(V) != None && "Non-constant or undef index?"); 4885 } 4886 4887 if (count_if(VL, [&SourceVectors](Value *V) { 4888 return !SourceVectors.contains(V); 4889 }) >= 2) { 4890 // Found 2nd source vector - cancel. 4891 LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with " 4892 "different source vectors.\n"); 4893 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4894 BS.cancelScheduling(VL, VL0); 4895 return; 4896 } 4897 4898 auto OrdCompare = [](const std::pair<int, int> &P1, 4899 const std::pair<int, int> &P2) { 4900 return P1.first > P2.first; 4901 }; 4902 PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>, 4903 decltype(OrdCompare)> 4904 Indices(OrdCompare); 4905 for (int I = 0, E = VL.size(); I < E; ++I) { 4906 unsigned Idx = *getInsertIndex(VL[I]); 4907 Indices.emplace(Idx, I); 4908 } 4909 OrdersType CurrentOrder(VL.size(), VL.size()); 4910 bool IsIdentity = true; 4911 for (int I = 0, E = VL.size(); I < E; ++I) { 4912 CurrentOrder[Indices.top().second] = I; 4913 IsIdentity &= Indices.top().second == I; 4914 Indices.pop(); 4915 } 4916 if (IsIdentity) 4917 CurrentOrder.clear(); 4918 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4919 None, CurrentOrder); 4920 LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n"); 4921 4922 constexpr int NumOps = 2; 4923 ValueList VectorOperands[NumOps]; 4924 for (int I = 0; I < NumOps; ++I) { 4925 for (Value *V : VL) 4926 VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I)); 4927 4928 TE->setOperand(I, VectorOperands[I]); 4929 } 4930 buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1}); 4931 return; 4932 } 4933 case Instruction::Load: { 4934 // Check that a vectorized load would load the same memory as a scalar 4935 // load. For example, we don't want to vectorize loads that are smaller 4936 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 4937 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 4938 // from such a struct, we read/write packed bits disagreeing with the 4939 // unvectorized version. 4940 SmallVector<Value *> PointerOps; 4941 OrdersType CurrentOrder; 4942 TreeEntry *TE = nullptr; 4943 switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, *LI, CurrentOrder, 4944 PointerOps)) { 4945 case LoadsState::Vectorize: 4946 if (CurrentOrder.empty()) { 4947 // Original loads are consecutive and does not require reordering. 4948 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4949 ReuseShuffleIndicies); 4950 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n"); 4951 } else { 4952 fixupOrderingIndices(CurrentOrder); 4953 // Need to reorder. 4954 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4955 ReuseShuffleIndicies, CurrentOrder); 4956 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n"); 4957 } 4958 TE->setOperandsInOrder(); 4959 break; 4960 case LoadsState::ScatterVectorize: 4961 // Vectorizing non-consecutive loads with `llvm.masked.gather`. 4962 TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S, 4963 UserTreeIdx, ReuseShuffleIndicies); 4964 TE->setOperandsInOrder(); 4965 buildTree_rec(PointerOps, Depth + 1, {TE, 0}); 4966 LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n"); 4967 break; 4968 case LoadsState::Gather: 4969 BS.cancelScheduling(VL, VL0); 4970 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4971 ReuseShuffleIndicies); 4972 #ifndef NDEBUG 4973 Type *ScalarTy = VL0->getType(); 4974 if (DL->getTypeSizeInBits(ScalarTy) != 4975 DL->getTypeAllocSizeInBits(ScalarTy)) 4976 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n"); 4977 else if (any_of(VL, [](Value *V) { 4978 return !cast<LoadInst>(V)->isSimple(); 4979 })) 4980 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n"); 4981 else 4982 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n"); 4983 #endif // NDEBUG 4984 break; 4985 } 4986 return; 4987 } 4988 case Instruction::ZExt: 4989 case Instruction::SExt: 4990 case Instruction::FPToUI: 4991 case Instruction::FPToSI: 4992 case Instruction::FPExt: 4993 case Instruction::PtrToInt: 4994 case Instruction::IntToPtr: 4995 case Instruction::SIToFP: 4996 case Instruction::UIToFP: 4997 case Instruction::Trunc: 4998 case Instruction::FPTrunc: 4999 case Instruction::BitCast: { 5000 Type *SrcTy = VL0->getOperand(0)->getType(); 5001 for (Value *V : VL) { 5002 Type *Ty = cast<Instruction>(V)->getOperand(0)->getType(); 5003 if (Ty != SrcTy || !isValidElementType(Ty)) { 5004 BS.cancelScheduling(VL, VL0); 5005 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5006 ReuseShuffleIndicies); 5007 LLVM_DEBUG(dbgs() 5008 << "SLP: Gathering casts with different src types.\n"); 5009 return; 5010 } 5011 } 5012 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5013 ReuseShuffleIndicies); 5014 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n"); 5015 5016 TE->setOperandsInOrder(); 5017 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 5018 ValueList Operands; 5019 // Prepare the operand vector. 5020 for (Value *V : VL) 5021 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 5022 5023 buildTree_rec(Operands, Depth + 1, {TE, i}); 5024 } 5025 return; 5026 } 5027 case Instruction::ICmp: 5028 case Instruction::FCmp: { 5029 // Check that all of the compares have the same predicate. 5030 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 5031 CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0); 5032 Type *ComparedTy = VL0->getOperand(0)->getType(); 5033 for (Value *V : VL) { 5034 CmpInst *Cmp = cast<CmpInst>(V); 5035 if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) || 5036 Cmp->getOperand(0)->getType() != ComparedTy) { 5037 BS.cancelScheduling(VL, VL0); 5038 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5039 ReuseShuffleIndicies); 5040 LLVM_DEBUG(dbgs() 5041 << "SLP: Gathering cmp with different predicate.\n"); 5042 return; 5043 } 5044 } 5045 5046 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5047 ReuseShuffleIndicies); 5048 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n"); 5049 5050 ValueList Left, Right; 5051 if (cast<CmpInst>(VL0)->isCommutative()) { 5052 // Commutative predicate - collect + sort operands of the instructions 5053 // so that each side is more likely to have the same opcode. 5054 assert(P0 == SwapP0 && "Commutative Predicate mismatch"); 5055 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 5056 } else { 5057 // Collect operands - commute if it uses the swapped predicate. 5058 for (Value *V : VL) { 5059 auto *Cmp = cast<CmpInst>(V); 5060 Value *LHS = Cmp->getOperand(0); 5061 Value *RHS = Cmp->getOperand(1); 5062 if (Cmp->getPredicate() != P0) 5063 std::swap(LHS, RHS); 5064 Left.push_back(LHS); 5065 Right.push_back(RHS); 5066 } 5067 } 5068 TE->setOperand(0, Left); 5069 TE->setOperand(1, Right); 5070 buildTree_rec(Left, Depth + 1, {TE, 0}); 5071 buildTree_rec(Right, Depth + 1, {TE, 1}); 5072 return; 5073 } 5074 case Instruction::Select: 5075 case Instruction::FNeg: 5076 case Instruction::Add: 5077 case Instruction::FAdd: 5078 case Instruction::Sub: 5079 case Instruction::FSub: 5080 case Instruction::Mul: 5081 case Instruction::FMul: 5082 case Instruction::UDiv: 5083 case Instruction::SDiv: 5084 case Instruction::FDiv: 5085 case Instruction::URem: 5086 case Instruction::SRem: 5087 case Instruction::FRem: 5088 case Instruction::Shl: 5089 case Instruction::LShr: 5090 case Instruction::AShr: 5091 case Instruction::And: 5092 case Instruction::Or: 5093 case Instruction::Xor: { 5094 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5095 ReuseShuffleIndicies); 5096 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n"); 5097 5098 // Sort operands of the instructions so that each side is more likely to 5099 // have the same opcode. 5100 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) { 5101 ValueList Left, Right; 5102 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 5103 TE->setOperand(0, Left); 5104 TE->setOperand(1, Right); 5105 buildTree_rec(Left, Depth + 1, {TE, 0}); 5106 buildTree_rec(Right, Depth + 1, {TE, 1}); 5107 return; 5108 } 5109 5110 TE->setOperandsInOrder(); 5111 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 5112 ValueList Operands; 5113 // Prepare the operand vector. 5114 for (Value *V : VL) 5115 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 5116 5117 buildTree_rec(Operands, Depth + 1, {TE, i}); 5118 } 5119 return; 5120 } 5121 case Instruction::GetElementPtr: { 5122 // We don't combine GEPs with complicated (nested) indexing. 5123 for (Value *V : VL) { 5124 auto *I = dyn_cast<GetElementPtrInst>(V); 5125 if (!I) 5126 continue; 5127 if (I->getNumOperands() != 2) { 5128 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"); 5129 BS.cancelScheduling(VL, VL0); 5130 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5131 ReuseShuffleIndicies); 5132 return; 5133 } 5134 } 5135 5136 // We can't combine several GEPs into one vector if they operate on 5137 // different types. 5138 Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType(); 5139 for (Value *V : VL) { 5140 auto *GEP = dyn_cast<GEPOperator>(V); 5141 if (!GEP) 5142 continue; 5143 Type *CurTy = GEP->getSourceElementType(); 5144 if (Ty0 != CurTy) { 5145 LLVM_DEBUG(dbgs() 5146 << "SLP: not-vectorizable GEP (different types).\n"); 5147 BS.cancelScheduling(VL, VL0); 5148 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5149 ReuseShuffleIndicies); 5150 return; 5151 } 5152 } 5153 5154 bool IsScatterUser = 5155 UserTreeIdx.UserTE && 5156 UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize; 5157 // We don't combine GEPs with non-constant indexes. 5158 Type *Ty1 = VL0->getOperand(1)->getType(); 5159 for (Value *V : VL) { 5160 auto *I = dyn_cast<GetElementPtrInst>(V); 5161 if (!I) 5162 continue; 5163 auto *Op = I->getOperand(1); 5164 if ((!IsScatterUser && !isa<ConstantInt>(Op)) || 5165 (Op->getType() != Ty1 && 5166 ((IsScatterUser && !isa<ConstantInt>(Op)) || 5167 Op->getType()->getScalarSizeInBits() > 5168 DL->getIndexSizeInBits( 5169 V->getType()->getPointerAddressSpace())))) { 5170 LLVM_DEBUG(dbgs() 5171 << "SLP: not-vectorizable GEP (non-constant indexes).\n"); 5172 BS.cancelScheduling(VL, VL0); 5173 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5174 ReuseShuffleIndicies); 5175 return; 5176 } 5177 } 5178 5179 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5180 ReuseShuffleIndicies); 5181 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n"); 5182 SmallVector<ValueList, 2> Operands(2); 5183 // Prepare the operand vector for pointer operands. 5184 for (Value *V : VL) { 5185 auto *GEP = dyn_cast<GetElementPtrInst>(V); 5186 if (!GEP) { 5187 Operands.front().push_back(V); 5188 continue; 5189 } 5190 Operands.front().push_back(GEP->getPointerOperand()); 5191 } 5192 TE->setOperand(0, Operands.front()); 5193 // Need to cast all indices to the same type before vectorization to 5194 // avoid crash. 5195 // Required to be able to find correct matches between different gather 5196 // nodes and reuse the vectorized values rather than trying to gather them 5197 // again. 5198 int IndexIdx = 1; 5199 Type *VL0Ty = VL0->getOperand(IndexIdx)->getType(); 5200 Type *Ty = all_of(VL, 5201 [VL0Ty, IndexIdx](Value *V) { 5202 auto *GEP = dyn_cast<GetElementPtrInst>(V); 5203 if (!GEP) 5204 return true; 5205 return VL0Ty == GEP->getOperand(IndexIdx)->getType(); 5206 }) 5207 ? VL0Ty 5208 : DL->getIndexType(cast<GetElementPtrInst>(VL0) 5209 ->getPointerOperandType() 5210 ->getScalarType()); 5211 // Prepare the operand vector. 5212 for (Value *V : VL) { 5213 auto *I = dyn_cast<GetElementPtrInst>(V); 5214 if (!I) { 5215 Operands.back().push_back( 5216 ConstantInt::get(Ty, 0, /*isSigned=*/false)); 5217 continue; 5218 } 5219 auto *Op = I->getOperand(IndexIdx); 5220 auto *CI = dyn_cast<ConstantInt>(Op); 5221 if (!CI) 5222 Operands.back().push_back(Op); 5223 else 5224 Operands.back().push_back(ConstantExpr::getIntegerCast( 5225 CI, Ty, CI->getValue().isSignBitSet())); 5226 } 5227 TE->setOperand(IndexIdx, Operands.back()); 5228 5229 for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I) 5230 buildTree_rec(Operands[I], Depth + 1, {TE, I}); 5231 return; 5232 } 5233 case Instruction::Store: { 5234 // Check if the stores are consecutive or if we need to swizzle them. 5235 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType(); 5236 // Avoid types that are padded when being allocated as scalars, while 5237 // being packed together in a vector (such as i1). 5238 if (DL->getTypeSizeInBits(ScalarTy) != 5239 DL->getTypeAllocSizeInBits(ScalarTy)) { 5240 BS.cancelScheduling(VL, VL0); 5241 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5242 ReuseShuffleIndicies); 5243 LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n"); 5244 return; 5245 } 5246 // Make sure all stores in the bundle are simple - we can't vectorize 5247 // atomic or volatile stores. 5248 SmallVector<Value *, 4> PointerOps(VL.size()); 5249 ValueList Operands(VL.size()); 5250 auto POIter = PointerOps.begin(); 5251 auto OIter = Operands.begin(); 5252 for (Value *V : VL) { 5253 auto *SI = cast<StoreInst>(V); 5254 if (!SI->isSimple()) { 5255 BS.cancelScheduling(VL, VL0); 5256 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5257 ReuseShuffleIndicies); 5258 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n"); 5259 return; 5260 } 5261 *POIter = SI->getPointerOperand(); 5262 *OIter = SI->getValueOperand(); 5263 ++POIter; 5264 ++OIter; 5265 } 5266 5267 OrdersType CurrentOrder; 5268 // Check the order of pointer operands. 5269 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) { 5270 Value *Ptr0; 5271 Value *PtrN; 5272 if (CurrentOrder.empty()) { 5273 Ptr0 = PointerOps.front(); 5274 PtrN = PointerOps.back(); 5275 } else { 5276 Ptr0 = PointerOps[CurrentOrder.front()]; 5277 PtrN = PointerOps[CurrentOrder.back()]; 5278 } 5279 Optional<int> Dist = 5280 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE); 5281 // Check that the sorted pointer operands are consecutive. 5282 if (static_cast<unsigned>(*Dist) == VL.size() - 1) { 5283 if (CurrentOrder.empty()) { 5284 // Original stores are consecutive and does not require reordering. 5285 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, 5286 UserTreeIdx, ReuseShuffleIndicies); 5287 TE->setOperandsInOrder(); 5288 buildTree_rec(Operands, Depth + 1, {TE, 0}); 5289 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n"); 5290 } else { 5291 fixupOrderingIndices(CurrentOrder); 5292 TreeEntry *TE = 5293 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5294 ReuseShuffleIndicies, CurrentOrder); 5295 TE->setOperandsInOrder(); 5296 buildTree_rec(Operands, Depth + 1, {TE, 0}); 5297 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n"); 5298 } 5299 return; 5300 } 5301 } 5302 5303 BS.cancelScheduling(VL, VL0); 5304 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5305 ReuseShuffleIndicies); 5306 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n"); 5307 return; 5308 } 5309 case Instruction::Call: { 5310 // Check if the calls are all to the same vectorizable intrinsic or 5311 // library function. 5312 CallInst *CI = cast<CallInst>(VL0); 5313 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 5314 5315 VFShape Shape = VFShape::get( 5316 *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())), 5317 false /*HasGlobalPred*/); 5318 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 5319 5320 if (!VecFunc && !isTriviallyVectorizable(ID)) { 5321 BS.cancelScheduling(VL, VL0); 5322 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5323 ReuseShuffleIndicies); 5324 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n"); 5325 return; 5326 } 5327 Function *F = CI->getCalledFunction(); 5328 unsigned NumArgs = CI->arg_size(); 5329 SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr); 5330 for (unsigned j = 0; j != NumArgs; ++j) 5331 if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) 5332 ScalarArgs[j] = CI->getArgOperand(j); 5333 for (Value *V : VL) { 5334 CallInst *CI2 = dyn_cast<CallInst>(V); 5335 if (!CI2 || CI2->getCalledFunction() != F || 5336 getVectorIntrinsicIDForCall(CI2, TLI) != ID || 5337 (VecFunc && 5338 VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) || 5339 !CI->hasIdenticalOperandBundleSchema(*CI2)) { 5340 BS.cancelScheduling(VL, VL0); 5341 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5342 ReuseShuffleIndicies); 5343 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V 5344 << "\n"); 5345 return; 5346 } 5347 // Some intrinsics have scalar arguments and should be same in order for 5348 // them to be vectorized. 5349 for (unsigned j = 0; j != NumArgs; ++j) { 5350 if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) { 5351 Value *A1J = CI2->getArgOperand(j); 5352 if (ScalarArgs[j] != A1J) { 5353 BS.cancelScheduling(VL, VL0); 5354 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5355 ReuseShuffleIndicies); 5356 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI 5357 << " argument " << ScalarArgs[j] << "!=" << A1J 5358 << "\n"); 5359 return; 5360 } 5361 } 5362 } 5363 // Verify that the bundle operands are identical between the two calls. 5364 if (CI->hasOperandBundles() && 5365 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(), 5366 CI->op_begin() + CI->getBundleOperandsEndIndex(), 5367 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) { 5368 BS.cancelScheduling(VL, VL0); 5369 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5370 ReuseShuffleIndicies); 5371 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" 5372 << *CI << "!=" << *V << '\n'); 5373 return; 5374 } 5375 } 5376 5377 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5378 ReuseShuffleIndicies); 5379 TE->setOperandsInOrder(); 5380 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 5381 // For scalar operands no need to to create an entry since no need to 5382 // vectorize it. 5383 if (isVectorIntrinsicWithScalarOpAtArg(ID, i)) 5384 continue; 5385 ValueList Operands; 5386 // Prepare the operand vector. 5387 for (Value *V : VL) { 5388 auto *CI2 = cast<CallInst>(V); 5389 Operands.push_back(CI2->getArgOperand(i)); 5390 } 5391 buildTree_rec(Operands, Depth + 1, {TE, i}); 5392 } 5393 return; 5394 } 5395 case Instruction::ShuffleVector: { 5396 // If this is not an alternate sequence of opcode like add-sub 5397 // then do not vectorize this instruction. 5398 if (!S.isAltShuffle()) { 5399 BS.cancelScheduling(VL, VL0); 5400 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5401 ReuseShuffleIndicies); 5402 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n"); 5403 return; 5404 } 5405 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 5406 ReuseShuffleIndicies); 5407 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n"); 5408 5409 // Reorder operands if reordering would enable vectorization. 5410 auto *CI = dyn_cast<CmpInst>(VL0); 5411 if (isa<BinaryOperator>(VL0) || CI) { 5412 ValueList Left, Right; 5413 if (!CI || all_of(VL, [](Value *V) { 5414 return cast<CmpInst>(V)->isCommutative(); 5415 })) { 5416 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 5417 } else { 5418 CmpInst::Predicate P0 = CI->getPredicate(); 5419 CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate(); 5420 assert(P0 != AltP0 && 5421 "Expected different main/alternate predicates."); 5422 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 5423 Value *BaseOp0 = VL0->getOperand(0); 5424 Value *BaseOp1 = VL0->getOperand(1); 5425 // Collect operands - commute if it uses the swapped predicate or 5426 // alternate operation. 5427 for (Value *V : VL) { 5428 auto *Cmp = cast<CmpInst>(V); 5429 Value *LHS = Cmp->getOperand(0); 5430 Value *RHS = Cmp->getOperand(1); 5431 CmpInst::Predicate CurrentPred = Cmp->getPredicate(); 5432 if (P0 == AltP0Swapped) { 5433 if (CI != Cmp && S.AltOp != Cmp && 5434 ((P0 == CurrentPred && 5435 !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) || 5436 (AltP0 == CurrentPred && 5437 areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)))) 5438 std::swap(LHS, RHS); 5439 } else if (P0 != CurrentPred && AltP0 != CurrentPred) { 5440 std::swap(LHS, RHS); 5441 } 5442 Left.push_back(LHS); 5443 Right.push_back(RHS); 5444 } 5445 } 5446 TE->setOperand(0, Left); 5447 TE->setOperand(1, Right); 5448 buildTree_rec(Left, Depth + 1, {TE, 0}); 5449 buildTree_rec(Right, Depth + 1, {TE, 1}); 5450 return; 5451 } 5452 5453 TE->setOperandsInOrder(); 5454 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 5455 ValueList Operands; 5456 // Prepare the operand vector. 5457 for (Value *V : VL) 5458 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 5459 5460 buildTree_rec(Operands, Depth + 1, {TE, i}); 5461 } 5462 return; 5463 } 5464 default: 5465 BS.cancelScheduling(VL, VL0); 5466 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 5467 ReuseShuffleIndicies); 5468 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); 5469 return; 5470 } 5471 } 5472 5473 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const { 5474 unsigned N = 1; 5475 Type *EltTy = T; 5476 5477 while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) || 5478 isa<VectorType>(EltTy)) { 5479 if (auto *ST = dyn_cast<StructType>(EltTy)) { 5480 // Check that struct is homogeneous. 5481 for (const auto *Ty : ST->elements()) 5482 if (Ty != *ST->element_begin()) 5483 return 0; 5484 N *= ST->getNumElements(); 5485 EltTy = *ST->element_begin(); 5486 } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) { 5487 N *= AT->getNumElements(); 5488 EltTy = AT->getElementType(); 5489 } else { 5490 auto *VT = cast<FixedVectorType>(EltTy); 5491 N *= VT->getNumElements(); 5492 EltTy = VT->getElementType(); 5493 } 5494 } 5495 5496 if (!isValidElementType(EltTy)) 5497 return 0; 5498 uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N)); 5499 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T)) 5500 return 0; 5501 return N; 5502 } 5503 5504 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 5505 SmallVectorImpl<unsigned> &CurrentOrder) const { 5506 const auto *It = find_if(VL, [](Value *V) { 5507 return isa<ExtractElementInst, ExtractValueInst>(V); 5508 }); 5509 assert(It != VL.end() && "Expected at least one extract instruction."); 5510 auto *E0 = cast<Instruction>(*It); 5511 assert(all_of(VL, 5512 [](Value *V) { 5513 return isa<UndefValue, ExtractElementInst, ExtractValueInst>( 5514 V); 5515 }) && 5516 "Invalid opcode"); 5517 // Check if all of the extracts come from the same vector and from the 5518 // correct offset. 5519 Value *Vec = E0->getOperand(0); 5520 5521 CurrentOrder.clear(); 5522 5523 // We have to extract from a vector/aggregate with the same number of elements. 5524 unsigned NElts; 5525 if (E0->getOpcode() == Instruction::ExtractValue) { 5526 const DataLayout &DL = E0->getModule()->getDataLayout(); 5527 NElts = canMapToVector(Vec->getType(), DL); 5528 if (!NElts) 5529 return false; 5530 // Check if load can be rewritten as load of vector. 5531 LoadInst *LI = dyn_cast<LoadInst>(Vec); 5532 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size())) 5533 return false; 5534 } else { 5535 NElts = cast<FixedVectorType>(Vec->getType())->getNumElements(); 5536 } 5537 5538 if (NElts != VL.size()) 5539 return false; 5540 5541 // Check that all of the indices extract from the correct offset. 5542 bool ShouldKeepOrder = true; 5543 unsigned E = VL.size(); 5544 // Assign to all items the initial value E + 1 so we can check if the extract 5545 // instruction index was used already. 5546 // Also, later we can check that all the indices are used and we have a 5547 // consecutive access in the extract instructions, by checking that no 5548 // element of CurrentOrder still has value E + 1. 5549 CurrentOrder.assign(E, E); 5550 unsigned I = 0; 5551 for (; I < E; ++I) { 5552 auto *Inst = dyn_cast<Instruction>(VL[I]); 5553 if (!Inst) 5554 continue; 5555 if (Inst->getOperand(0) != Vec) 5556 break; 5557 if (auto *EE = dyn_cast<ExtractElementInst>(Inst)) 5558 if (isa<UndefValue>(EE->getIndexOperand())) 5559 continue; 5560 Optional<unsigned> Idx = getExtractIndex(Inst); 5561 if (!Idx) 5562 break; 5563 const unsigned ExtIdx = *Idx; 5564 if (ExtIdx != I) { 5565 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E) 5566 break; 5567 ShouldKeepOrder = false; 5568 CurrentOrder[ExtIdx] = I; 5569 } else { 5570 if (CurrentOrder[I] != E) 5571 break; 5572 CurrentOrder[I] = I; 5573 } 5574 } 5575 if (I < E) { 5576 CurrentOrder.clear(); 5577 return false; 5578 } 5579 if (ShouldKeepOrder) 5580 CurrentOrder.clear(); 5581 5582 return ShouldKeepOrder; 5583 } 5584 5585 bool BoUpSLP::areAllUsersVectorized(Instruction *I, 5586 ArrayRef<Value *> VectorizedVals) const { 5587 return (I->hasOneUse() && is_contained(VectorizedVals, I)) || 5588 all_of(I->users(), [this](User *U) { 5589 return ScalarToTreeEntry.count(U) > 0 || 5590 isVectorLikeInstWithConstOps(U) || 5591 (isa<ExtractElementInst>(U) && MustGather.contains(U)); 5592 }); 5593 } 5594 5595 static std::pair<InstructionCost, InstructionCost> 5596 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy, 5597 TargetTransformInfo *TTI, TargetLibraryInfo *TLI) { 5598 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 5599 5600 // Calculate the cost of the scalar and vector calls. 5601 SmallVector<Type *, 4> VecTys; 5602 for (Use &Arg : CI->args()) 5603 VecTys.push_back( 5604 FixedVectorType::get(Arg->getType(), VecTy->getNumElements())); 5605 FastMathFlags FMF; 5606 if (auto *FPCI = dyn_cast<FPMathOperator>(CI)) 5607 FMF = FPCI->getFastMathFlags(); 5608 SmallVector<const Value *> Arguments(CI->args()); 5609 IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF, 5610 dyn_cast<IntrinsicInst>(CI)); 5611 auto IntrinsicCost = 5612 TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput); 5613 5614 auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 5615 VecTy->getNumElements())), 5616 false /*HasGlobalPred*/); 5617 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 5618 auto LibCost = IntrinsicCost; 5619 if (!CI->isNoBuiltin() && VecFunc) { 5620 // Calculate the cost of the vector library call. 5621 // If the corresponding vector call is cheaper, return its cost. 5622 LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys, 5623 TTI::TCK_RecipThroughput); 5624 } 5625 return {IntrinsicCost, LibCost}; 5626 } 5627 5628 /// Compute the cost of creating a vector of type \p VecTy containing the 5629 /// extracted values from \p VL. 5630 static InstructionCost 5631 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy, 5632 TargetTransformInfo::ShuffleKind ShuffleKind, 5633 ArrayRef<int> Mask, TargetTransformInfo &TTI) { 5634 unsigned NumOfParts = TTI.getNumberOfParts(VecTy); 5635 5636 if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts || 5637 VecTy->getNumElements() < NumOfParts) 5638 return TTI.getShuffleCost(ShuffleKind, VecTy, Mask); 5639 5640 bool AllConsecutive = true; 5641 unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts; 5642 unsigned Idx = -1; 5643 InstructionCost Cost = 0; 5644 5645 // Process extracts in blocks of EltsPerVector to check if the source vector 5646 // operand can be re-used directly. If not, add the cost of creating a shuffle 5647 // to extract the values into a vector register. 5648 SmallVector<int> RegMask(EltsPerVector, UndefMaskElem); 5649 for (auto *V : VL) { 5650 ++Idx; 5651 5652 // Reached the start of a new vector registers. 5653 if (Idx % EltsPerVector == 0) { 5654 RegMask.assign(EltsPerVector, UndefMaskElem); 5655 AllConsecutive = true; 5656 continue; 5657 } 5658 5659 // Need to exclude undefs from analysis. 5660 if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem) 5661 continue; 5662 5663 // Check all extracts for a vector register on the target directly 5664 // extract values in order. 5665 unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V)); 5666 if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) { 5667 unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1])); 5668 AllConsecutive &= PrevIdx + 1 == CurrentIdx && 5669 CurrentIdx % EltsPerVector == Idx % EltsPerVector; 5670 RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector; 5671 } 5672 5673 if (AllConsecutive) 5674 continue; 5675 5676 // Skip all indices, except for the last index per vector block. 5677 if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size()) 5678 continue; 5679 5680 // If we have a series of extracts which are not consecutive and hence 5681 // cannot re-use the source vector register directly, compute the shuffle 5682 // cost to extract the vector with EltsPerVector elements. 5683 Cost += TTI.getShuffleCost( 5684 TargetTransformInfo::SK_PermuteSingleSrc, 5685 FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask); 5686 } 5687 return Cost; 5688 } 5689 5690 /// Build shuffle mask for shuffle graph entries and lists of main and alternate 5691 /// operations operands. 5692 static void 5693 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices, 5694 ArrayRef<int> ReusesIndices, 5695 const function_ref<bool(Instruction *)> IsAltOp, 5696 SmallVectorImpl<int> &Mask, 5697 SmallVectorImpl<Value *> *OpScalars = nullptr, 5698 SmallVectorImpl<Value *> *AltScalars = nullptr) { 5699 unsigned Sz = VL.size(); 5700 Mask.assign(Sz, UndefMaskElem); 5701 SmallVector<int> OrderMask; 5702 if (!ReorderIndices.empty()) 5703 inversePermutation(ReorderIndices, OrderMask); 5704 for (unsigned I = 0; I < Sz; ++I) { 5705 unsigned Idx = I; 5706 if (!ReorderIndices.empty()) 5707 Idx = OrderMask[I]; 5708 auto *OpInst = cast<Instruction>(VL[Idx]); 5709 if (IsAltOp(OpInst)) { 5710 Mask[I] = Sz + Idx; 5711 if (AltScalars) 5712 AltScalars->push_back(OpInst); 5713 } else { 5714 Mask[I] = Idx; 5715 if (OpScalars) 5716 OpScalars->push_back(OpInst); 5717 } 5718 } 5719 if (!ReusesIndices.empty()) { 5720 SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem); 5721 transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) { 5722 return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem; 5723 }); 5724 Mask.swap(NewMask); 5725 } 5726 } 5727 5728 /// Checks if the specified instruction \p I is an alternate operation for the 5729 /// given \p MainOp and \p AltOp instructions. 5730 static bool isAlternateInstruction(const Instruction *I, 5731 const Instruction *MainOp, 5732 const Instruction *AltOp) { 5733 if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) { 5734 auto *AltCI0 = cast<CmpInst>(AltOp); 5735 auto *CI = cast<CmpInst>(I); 5736 CmpInst::Predicate P0 = CI0->getPredicate(); 5737 CmpInst::Predicate AltP0 = AltCI0->getPredicate(); 5738 assert(P0 != AltP0 && "Expected different main/alternate predicates."); 5739 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 5740 CmpInst::Predicate CurrentPred = CI->getPredicate(); 5741 if (P0 == AltP0Swapped) 5742 return I == AltCI0 || 5743 (I != MainOp && 5744 !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1), 5745 CI->getOperand(0), CI->getOperand(1))); 5746 return AltP0 == CurrentPred || AltP0Swapped == CurrentPred; 5747 } 5748 return I->getOpcode() == AltOp->getOpcode(); 5749 } 5750 5751 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E, 5752 ArrayRef<Value *> VectorizedVals) { 5753 ArrayRef<Value*> VL = E->Scalars; 5754 5755 Type *ScalarTy = VL[0]->getType(); 5756 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 5757 ScalarTy = SI->getValueOperand()->getType(); 5758 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0])) 5759 ScalarTy = CI->getOperand(0)->getType(); 5760 else if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 5761 ScalarTy = IE->getOperand(1)->getType(); 5762 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 5763 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 5764 5765 // If we have computed a smaller type for the expression, update VecTy so 5766 // that the costs will be accurate. 5767 if (MinBWs.count(VL[0])) 5768 VecTy = FixedVectorType::get( 5769 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size()); 5770 unsigned EntryVF = E->getVectorFactor(); 5771 auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF); 5772 5773 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 5774 // FIXME: it tries to fix a problem with MSVC buildbots. 5775 TargetTransformInfo &TTIRef = *TTI; 5776 auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy, 5777 VectorizedVals, E](InstructionCost &Cost) { 5778 DenseMap<Value *, int> ExtractVectorsTys; 5779 SmallPtrSet<Value *, 4> CheckedExtracts; 5780 for (auto *V : VL) { 5781 if (isa<UndefValue>(V)) 5782 continue; 5783 // If all users of instruction are going to be vectorized and this 5784 // instruction itself is not going to be vectorized, consider this 5785 // instruction as dead and remove its cost from the final cost of the 5786 // vectorized tree. 5787 // Also, avoid adjusting the cost for extractelements with multiple uses 5788 // in different graph entries. 5789 const TreeEntry *VE = getTreeEntry(V); 5790 if (!CheckedExtracts.insert(V).second || 5791 !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) || 5792 (VE && VE != E)) 5793 continue; 5794 auto *EE = cast<ExtractElementInst>(V); 5795 Optional<unsigned> EEIdx = getExtractIndex(EE); 5796 if (!EEIdx) 5797 continue; 5798 unsigned Idx = *EEIdx; 5799 if (TTIRef.getNumberOfParts(VecTy) != 5800 TTIRef.getNumberOfParts(EE->getVectorOperandType())) { 5801 auto It = 5802 ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first; 5803 It->getSecond() = std::min<int>(It->second, Idx); 5804 } 5805 // Take credit for instruction that will become dead. 5806 if (EE->hasOneUse()) { 5807 Instruction *Ext = EE->user_back(); 5808 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 5809 all_of(Ext->users(), 5810 [](User *U) { return isa<GetElementPtrInst>(U); })) { 5811 // Use getExtractWithExtendCost() to calculate the cost of 5812 // extractelement/ext pair. 5813 Cost -= 5814 TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(), 5815 EE->getVectorOperandType(), Idx); 5816 // Add back the cost of s|zext which is subtracted separately. 5817 Cost += TTIRef.getCastInstrCost( 5818 Ext->getOpcode(), Ext->getType(), EE->getType(), 5819 TTI::getCastContextHint(Ext), CostKind, Ext); 5820 continue; 5821 } 5822 } 5823 Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement, 5824 EE->getVectorOperandType(), Idx); 5825 } 5826 // Add a cost for subvector extracts/inserts if required. 5827 for (const auto &Data : ExtractVectorsTys) { 5828 auto *EEVTy = cast<FixedVectorType>(Data.first->getType()); 5829 unsigned NumElts = VecTy->getNumElements(); 5830 if (Data.second % NumElts == 0) 5831 continue; 5832 if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) { 5833 unsigned Idx = (Data.second / NumElts) * NumElts; 5834 unsigned EENumElts = EEVTy->getNumElements(); 5835 if (Idx + NumElts <= EENumElts) { 5836 Cost += 5837 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 5838 EEVTy, None, Idx, VecTy); 5839 } else { 5840 // Need to round up the subvector type vectorization factor to avoid a 5841 // crash in cost model functions. Make SubVT so that Idx + VF of SubVT 5842 // <= EENumElts. 5843 auto *SubVT = 5844 FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx); 5845 Cost += 5846 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 5847 EEVTy, None, Idx, SubVT); 5848 } 5849 } else { 5850 Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector, 5851 VecTy, None, 0, EEVTy); 5852 } 5853 } 5854 }; 5855 if (E->State == TreeEntry::NeedToGather) { 5856 if (allConstant(VL)) 5857 return 0; 5858 if (isa<InsertElementInst>(VL[0])) 5859 return InstructionCost::getInvalid(); 5860 SmallVector<int> Mask; 5861 SmallVector<const TreeEntry *> Entries; 5862 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 5863 isGatherShuffledEntry(E, Mask, Entries); 5864 if (Shuffle) { 5865 InstructionCost GatherCost = 0; 5866 if (ShuffleVectorInst::isIdentityMask(Mask)) { 5867 // Perfect match in the graph, will reuse the previously vectorized 5868 // node. Cost is 0. 5869 LLVM_DEBUG( 5870 dbgs() 5871 << "SLP: perfect diamond match for gather bundle that starts with " 5872 << *VL.front() << ".\n"); 5873 if (NeedToShuffleReuses) 5874 GatherCost = 5875 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 5876 FinalVecTy, E->ReuseShuffleIndices); 5877 } else { 5878 LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size() 5879 << " entries for bundle that starts with " 5880 << *VL.front() << ".\n"); 5881 // Detected that instead of gather we can emit a shuffle of single/two 5882 // previously vectorized nodes. Add the cost of the permutation rather 5883 // than gather. 5884 ::addMask(Mask, E->ReuseShuffleIndices); 5885 GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask); 5886 } 5887 return GatherCost; 5888 } 5889 if ((E->getOpcode() == Instruction::ExtractElement || 5890 all_of(E->Scalars, 5891 [](Value *V) { 5892 return isa<ExtractElementInst, UndefValue>(V); 5893 })) && 5894 allSameType(VL)) { 5895 // Check that gather of extractelements can be represented as just a 5896 // shuffle of a single/two vectors the scalars are extracted from. 5897 SmallVector<int> Mask; 5898 Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = 5899 isFixedVectorShuffle(VL, Mask); 5900 if (ShuffleKind) { 5901 // Found the bunch of extractelement instructions that must be gathered 5902 // into a vector and can be represented as a permutation elements in a 5903 // single input vector or of 2 input vectors. 5904 InstructionCost Cost = 5905 computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI); 5906 AdjustExtractsCost(Cost); 5907 if (NeedToShuffleReuses) 5908 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 5909 FinalVecTy, E->ReuseShuffleIndices); 5910 return Cost; 5911 } 5912 } 5913 if (isSplat(VL)) { 5914 // Found the broadcasting of the single scalar, calculate the cost as the 5915 // broadcast. 5916 assert(VecTy == FinalVecTy && 5917 "No reused scalars expected for broadcast."); 5918 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 5919 /*Mask=*/None, /*Index=*/0, 5920 /*SubTp=*/nullptr, /*Args=*/VL[0]); 5921 } 5922 InstructionCost ReuseShuffleCost = 0; 5923 if (NeedToShuffleReuses) 5924 ReuseShuffleCost = TTI->getShuffleCost( 5925 TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices); 5926 // Improve gather cost for gather of loads, if we can group some of the 5927 // loads into vector loads. 5928 if (VL.size() > 2 && E->getOpcode() == Instruction::Load && 5929 !E->isAltShuffle()) { 5930 BoUpSLP::ValueSet VectorizedLoads; 5931 unsigned StartIdx = 0; 5932 unsigned VF = VL.size() / 2; 5933 unsigned VectorizedCnt = 0; 5934 unsigned ScatterVectorizeCnt = 0; 5935 const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType()); 5936 for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) { 5937 for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End; 5938 Cnt += VF) { 5939 ArrayRef<Value *> Slice = VL.slice(Cnt, VF); 5940 if (!VectorizedLoads.count(Slice.front()) && 5941 !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) { 5942 SmallVector<Value *> PointerOps; 5943 OrdersType CurrentOrder; 5944 LoadsState LS = 5945 canVectorizeLoads(Slice, Slice.front(), *TTI, *DL, *SE, *LI, 5946 CurrentOrder, PointerOps); 5947 switch (LS) { 5948 case LoadsState::Vectorize: 5949 case LoadsState::ScatterVectorize: 5950 // Mark the vectorized loads so that we don't vectorize them 5951 // again. 5952 if (LS == LoadsState::Vectorize) 5953 ++VectorizedCnt; 5954 else 5955 ++ScatterVectorizeCnt; 5956 VectorizedLoads.insert(Slice.begin(), Slice.end()); 5957 // If we vectorized initial block, no need to try to vectorize it 5958 // again. 5959 if (Cnt == StartIdx) 5960 StartIdx += VF; 5961 break; 5962 case LoadsState::Gather: 5963 break; 5964 } 5965 } 5966 } 5967 // Check if the whole array was vectorized already - exit. 5968 if (StartIdx >= VL.size()) 5969 break; 5970 // Found vectorizable parts - exit. 5971 if (!VectorizedLoads.empty()) 5972 break; 5973 } 5974 if (!VectorizedLoads.empty()) { 5975 InstructionCost GatherCost = 0; 5976 unsigned NumParts = TTI->getNumberOfParts(VecTy); 5977 bool NeedInsertSubvectorAnalysis = 5978 !NumParts || (VL.size() / VF) > NumParts; 5979 // Get the cost for gathered loads. 5980 for (unsigned I = 0, End = VL.size(); I < End; I += VF) { 5981 if (VectorizedLoads.contains(VL[I])) 5982 continue; 5983 GatherCost += getGatherCost(VL.slice(I, VF)); 5984 } 5985 // The cost for vectorized loads. 5986 InstructionCost ScalarsCost = 0; 5987 for (Value *V : VectorizedLoads) { 5988 auto *LI = cast<LoadInst>(V); 5989 ScalarsCost += TTI->getMemoryOpCost( 5990 Instruction::Load, LI->getType(), LI->getAlign(), 5991 LI->getPointerAddressSpace(), CostKind, LI); 5992 } 5993 auto *LI = cast<LoadInst>(E->getMainOp()); 5994 auto *LoadTy = FixedVectorType::get(LI->getType(), VF); 5995 Align Alignment = LI->getAlign(); 5996 GatherCost += 5997 VectorizedCnt * 5998 TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment, 5999 LI->getPointerAddressSpace(), CostKind, LI); 6000 GatherCost += ScatterVectorizeCnt * 6001 TTI->getGatherScatterOpCost( 6002 Instruction::Load, LoadTy, LI->getPointerOperand(), 6003 /*VariableMask=*/false, Alignment, CostKind, LI); 6004 if (NeedInsertSubvectorAnalysis) { 6005 // Add the cost for the subvectors insert. 6006 for (int I = VF, E = VL.size(); I < E; I += VF) 6007 GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy, 6008 None, I, LoadTy); 6009 } 6010 return ReuseShuffleCost + GatherCost - ScalarsCost; 6011 } 6012 } 6013 return ReuseShuffleCost + getGatherCost(VL); 6014 } 6015 InstructionCost CommonCost = 0; 6016 SmallVector<int> Mask; 6017 if (!E->ReorderIndices.empty()) { 6018 SmallVector<int> NewMask; 6019 if (E->getOpcode() == Instruction::Store) { 6020 // For stores the order is actually a mask. 6021 NewMask.resize(E->ReorderIndices.size()); 6022 copy(E->ReorderIndices, NewMask.begin()); 6023 } else { 6024 inversePermutation(E->ReorderIndices, NewMask); 6025 } 6026 ::addMask(Mask, NewMask); 6027 } 6028 if (NeedToShuffleReuses) 6029 ::addMask(Mask, E->ReuseShuffleIndices); 6030 if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask)) 6031 CommonCost = 6032 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask); 6033 assert((E->State == TreeEntry::Vectorize || 6034 E->State == TreeEntry::ScatterVectorize) && 6035 "Unhandled state"); 6036 assert(E->getOpcode() && 6037 ((allSameType(VL) && allSameBlock(VL)) || 6038 (E->getOpcode() == Instruction::GetElementPtr && 6039 E->getMainOp()->getType()->isPointerTy())) && 6040 "Invalid VL"); 6041 Instruction *VL0 = E->getMainOp(); 6042 unsigned ShuffleOrOp = 6043 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 6044 switch (ShuffleOrOp) { 6045 case Instruction::PHI: 6046 return 0; 6047 6048 case Instruction::ExtractValue: 6049 case Instruction::ExtractElement: { 6050 // The common cost of removal ExtractElement/ExtractValue instructions + 6051 // the cost of shuffles, if required to resuffle the original vector. 6052 if (NeedToShuffleReuses) { 6053 unsigned Idx = 0; 6054 for (unsigned I : E->ReuseShuffleIndices) { 6055 if (ShuffleOrOp == Instruction::ExtractElement) { 6056 auto *EE = cast<ExtractElementInst>(VL[I]); 6057 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 6058 EE->getVectorOperandType(), 6059 *getExtractIndex(EE)); 6060 } else { 6061 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 6062 VecTy, Idx); 6063 ++Idx; 6064 } 6065 } 6066 Idx = EntryVF; 6067 for (Value *V : VL) { 6068 if (ShuffleOrOp == Instruction::ExtractElement) { 6069 auto *EE = cast<ExtractElementInst>(V); 6070 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 6071 EE->getVectorOperandType(), 6072 *getExtractIndex(EE)); 6073 } else { 6074 --Idx; 6075 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 6076 VecTy, Idx); 6077 } 6078 } 6079 } 6080 if (ShuffleOrOp == Instruction::ExtractValue) { 6081 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 6082 auto *EI = cast<Instruction>(VL[I]); 6083 // Take credit for instruction that will become dead. 6084 if (EI->hasOneUse()) { 6085 Instruction *Ext = EI->user_back(); 6086 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 6087 all_of(Ext->users(), 6088 [](User *U) { return isa<GetElementPtrInst>(U); })) { 6089 // Use getExtractWithExtendCost() to calculate the cost of 6090 // extractelement/ext pair. 6091 CommonCost -= TTI->getExtractWithExtendCost( 6092 Ext->getOpcode(), Ext->getType(), VecTy, I); 6093 // Add back the cost of s|zext which is subtracted separately. 6094 CommonCost += TTI->getCastInstrCost( 6095 Ext->getOpcode(), Ext->getType(), EI->getType(), 6096 TTI::getCastContextHint(Ext), CostKind, Ext); 6097 continue; 6098 } 6099 } 6100 CommonCost -= 6101 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I); 6102 } 6103 } else { 6104 AdjustExtractsCost(CommonCost); 6105 } 6106 return CommonCost; 6107 } 6108 case Instruction::InsertElement: { 6109 assert(E->ReuseShuffleIndices.empty() && 6110 "Unique insertelements only are expected."); 6111 auto *SrcVecTy = cast<FixedVectorType>(VL0->getType()); 6112 unsigned const NumElts = SrcVecTy->getNumElements(); 6113 unsigned const NumScalars = VL.size(); 6114 6115 unsigned NumOfParts = TTI->getNumberOfParts(SrcVecTy); 6116 6117 unsigned OffsetBeg = *getInsertIndex(VL.front()); 6118 unsigned OffsetEnd = OffsetBeg; 6119 for (Value *V : VL.drop_front()) { 6120 unsigned Idx = *getInsertIndex(V); 6121 if (OffsetBeg > Idx) 6122 OffsetBeg = Idx; 6123 else if (OffsetEnd < Idx) 6124 OffsetEnd = Idx; 6125 } 6126 unsigned VecScalarsSz = PowerOf2Ceil(NumElts); 6127 if (NumOfParts > 0) 6128 VecScalarsSz = PowerOf2Ceil((NumElts + NumOfParts - 1) / NumOfParts); 6129 unsigned VecSz = 6130 (1 + OffsetEnd / VecScalarsSz - OffsetBeg / VecScalarsSz) * 6131 VecScalarsSz; 6132 unsigned Offset = VecScalarsSz * (OffsetBeg / VecScalarsSz); 6133 unsigned InsertVecSz = std::min<unsigned>( 6134 PowerOf2Ceil(OffsetEnd - OffsetBeg + 1), 6135 ((OffsetEnd - OffsetBeg + VecScalarsSz) / VecScalarsSz) * 6136 VecScalarsSz); 6137 bool IsWholeSubvector = 6138 OffsetBeg == Offset && ((OffsetEnd + 1) % VecScalarsSz == 0); 6139 // Check if we can safely insert a subvector. If it is not possible, just 6140 // generate a whole-sized vector and shuffle the source vector and the new 6141 // subvector. 6142 if (OffsetBeg + InsertVecSz > VecSz) { 6143 // Align OffsetBeg to generate correct mask. 6144 OffsetBeg = alignDown(OffsetBeg, VecSz, Offset); 6145 InsertVecSz = VecSz; 6146 } 6147 6148 APInt DemandedElts = APInt::getZero(NumElts); 6149 // TODO: Add support for Instruction::InsertValue. 6150 SmallVector<int> Mask; 6151 if (!E->ReorderIndices.empty()) { 6152 inversePermutation(E->ReorderIndices, Mask); 6153 Mask.append(InsertVecSz - Mask.size(), UndefMaskElem); 6154 } else { 6155 Mask.assign(VecSz, UndefMaskElem); 6156 std::iota(Mask.begin(), std::next(Mask.begin(), InsertVecSz), 0); 6157 } 6158 bool IsIdentity = true; 6159 SmallVector<int> PrevMask(InsertVecSz, UndefMaskElem); 6160 Mask.swap(PrevMask); 6161 for (unsigned I = 0; I < NumScalars; ++I) { 6162 unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]); 6163 DemandedElts.setBit(InsertIdx); 6164 IsIdentity &= InsertIdx - OffsetBeg == I; 6165 Mask[InsertIdx - OffsetBeg] = I; 6166 } 6167 assert(Offset < NumElts && "Failed to find vector index offset"); 6168 6169 InstructionCost Cost = 0; 6170 Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts, 6171 /*Insert*/ true, /*Extract*/ false); 6172 6173 // First cost - resize to actual vector size if not identity shuffle or 6174 // need to shift the vector. 6175 // Do not calculate the cost if the actual size is the register size and 6176 // we can merge this shuffle with the following SK_Select. 6177 auto *InsertVecTy = 6178 FixedVectorType::get(SrcVecTy->getElementType(), InsertVecSz); 6179 if (!IsIdentity) 6180 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 6181 InsertVecTy, Mask); 6182 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 6183 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); 6184 })); 6185 // Second cost - permutation with subvector, if some elements are from the 6186 // initial vector or inserting a subvector. 6187 // TODO: Implement the analysis of the FirstInsert->getOperand(0) 6188 // subvector of ActualVecTy. 6189 if (!isUndefVector(FirstInsert->getOperand(0)) && NumScalars != NumElts && 6190 !IsWholeSubvector) { 6191 if (InsertVecSz != VecSz) { 6192 auto *ActualVecTy = 6193 FixedVectorType::get(SrcVecTy->getElementType(), VecSz); 6194 Cost += TTI->getShuffleCost(TTI::SK_InsertSubvector, ActualVecTy, 6195 None, OffsetBeg - Offset, InsertVecTy); 6196 } else { 6197 for (unsigned I = 0, End = OffsetBeg - Offset; I < End; ++I) 6198 Mask[I] = I; 6199 for (unsigned I = OffsetBeg - Offset, End = OffsetEnd - Offset; 6200 I <= End; ++I) 6201 if (Mask[I] != UndefMaskElem) 6202 Mask[I] = I + VecSz; 6203 for (unsigned I = OffsetEnd + 1 - Offset; I < VecSz; ++I) 6204 Mask[I] = I; 6205 Cost += TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, InsertVecTy, Mask); 6206 } 6207 } 6208 return Cost; 6209 } 6210 case Instruction::ZExt: 6211 case Instruction::SExt: 6212 case Instruction::FPToUI: 6213 case Instruction::FPToSI: 6214 case Instruction::FPExt: 6215 case Instruction::PtrToInt: 6216 case Instruction::IntToPtr: 6217 case Instruction::SIToFP: 6218 case Instruction::UIToFP: 6219 case Instruction::Trunc: 6220 case Instruction::FPTrunc: 6221 case Instruction::BitCast: { 6222 Type *SrcTy = VL0->getOperand(0)->getType(); 6223 InstructionCost ScalarEltCost = 6224 TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy, 6225 TTI::getCastContextHint(VL0), CostKind, VL0); 6226 if (NeedToShuffleReuses) { 6227 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6228 } 6229 6230 // Calculate the cost of this instruction. 6231 InstructionCost ScalarCost = VL.size() * ScalarEltCost; 6232 6233 auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size()); 6234 InstructionCost VecCost = 0; 6235 // Check if the values are candidates to demote. 6236 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) { 6237 VecCost = CommonCost + TTI->getCastInstrCost( 6238 E->getOpcode(), VecTy, SrcVecTy, 6239 TTI::getCastContextHint(VL0), CostKind, VL0); 6240 } 6241 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6242 return VecCost - ScalarCost; 6243 } 6244 case Instruction::FCmp: 6245 case Instruction::ICmp: 6246 case Instruction::Select: { 6247 // Calculate the cost of this instruction. 6248 InstructionCost ScalarEltCost = 6249 TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 6250 CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0); 6251 if (NeedToShuffleReuses) { 6252 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6253 } 6254 auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size()); 6255 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 6256 6257 // Check if all entries in VL are either compares or selects with compares 6258 // as condition that have the same predicates. 6259 CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE; 6260 bool First = true; 6261 for (auto *V : VL) { 6262 CmpInst::Predicate CurrentPred; 6263 auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value()); 6264 if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) && 6265 !match(V, MatchCmp)) || 6266 (!First && VecPred != CurrentPred)) { 6267 VecPred = CmpInst::BAD_ICMP_PREDICATE; 6268 break; 6269 } 6270 First = false; 6271 VecPred = CurrentPred; 6272 } 6273 6274 InstructionCost VecCost = TTI->getCmpSelInstrCost( 6275 E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0); 6276 // Check if it is possible and profitable to use min/max for selects in 6277 // VL. 6278 // 6279 auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL); 6280 if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) { 6281 IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy, 6282 {VecTy, VecTy}); 6283 InstructionCost IntrinsicCost = 6284 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 6285 // If the selects are the only uses of the compares, they will be dead 6286 // and we can adjust the cost by removing their cost. 6287 if (IntrinsicAndUse.second) 6288 IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, 6289 MaskTy, VecPred, CostKind); 6290 VecCost = std::min(VecCost, IntrinsicCost); 6291 } 6292 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6293 return CommonCost + VecCost - ScalarCost; 6294 } 6295 case Instruction::FNeg: 6296 case Instruction::Add: 6297 case Instruction::FAdd: 6298 case Instruction::Sub: 6299 case Instruction::FSub: 6300 case Instruction::Mul: 6301 case Instruction::FMul: 6302 case Instruction::UDiv: 6303 case Instruction::SDiv: 6304 case Instruction::FDiv: 6305 case Instruction::URem: 6306 case Instruction::SRem: 6307 case Instruction::FRem: 6308 case Instruction::Shl: 6309 case Instruction::LShr: 6310 case Instruction::AShr: 6311 case Instruction::And: 6312 case Instruction::Or: 6313 case Instruction::Xor: { 6314 // Certain instructions can be cheaper to vectorize if they have a 6315 // constant second vector operand. 6316 TargetTransformInfo::OperandValueKind Op1VK = 6317 TargetTransformInfo::OK_AnyValue; 6318 TargetTransformInfo::OperandValueKind Op2VK = 6319 TargetTransformInfo::OK_UniformConstantValue; 6320 TargetTransformInfo::OperandValueProperties Op1VP = 6321 TargetTransformInfo::OP_None; 6322 TargetTransformInfo::OperandValueProperties Op2VP = 6323 TargetTransformInfo::OP_PowerOf2; 6324 6325 // If all operands are exactly the same ConstantInt then set the 6326 // operand kind to OK_UniformConstantValue. 6327 // If instead not all operands are constants, then set the operand kind 6328 // to OK_AnyValue. If all operands are constants but not the same, 6329 // then set the operand kind to OK_NonUniformConstantValue. 6330 ConstantInt *CInt0 = nullptr; 6331 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 6332 const Instruction *I = cast<Instruction>(VL[i]); 6333 unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0; 6334 ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx)); 6335 if (!CInt) { 6336 Op2VK = TargetTransformInfo::OK_AnyValue; 6337 Op2VP = TargetTransformInfo::OP_None; 6338 break; 6339 } 6340 if (Op2VP == TargetTransformInfo::OP_PowerOf2 && 6341 !CInt->getValue().isPowerOf2()) 6342 Op2VP = TargetTransformInfo::OP_None; 6343 if (i == 0) { 6344 CInt0 = CInt; 6345 continue; 6346 } 6347 if (CInt0 != CInt) 6348 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 6349 } 6350 6351 SmallVector<const Value *, 4> Operands(VL0->operand_values()); 6352 InstructionCost ScalarEltCost = 6353 TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK, 6354 Op2VK, Op1VP, Op2VP, Operands, VL0); 6355 if (NeedToShuffleReuses) { 6356 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6357 } 6358 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 6359 InstructionCost VecCost = 6360 TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK, 6361 Op2VK, Op1VP, Op2VP, Operands, VL0); 6362 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6363 return CommonCost + VecCost - ScalarCost; 6364 } 6365 case Instruction::GetElementPtr: { 6366 TargetTransformInfo::OperandValueKind Op1VK = 6367 TargetTransformInfo::OK_AnyValue; 6368 TargetTransformInfo::OperandValueKind Op2VK = 6369 any_of(VL, 6370 [](Value *V) { 6371 return isa<GetElementPtrInst>(V) && 6372 !isConstant( 6373 cast<GetElementPtrInst>(V)->getOperand(1)); 6374 }) 6375 ? TargetTransformInfo::OK_AnyValue 6376 : TargetTransformInfo::OK_UniformConstantValue; 6377 6378 InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost( 6379 Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK); 6380 if (NeedToShuffleReuses) { 6381 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6382 } 6383 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 6384 InstructionCost VecCost = TTI->getArithmeticInstrCost( 6385 Instruction::Add, VecTy, CostKind, Op1VK, Op2VK); 6386 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6387 return CommonCost + VecCost - ScalarCost; 6388 } 6389 case Instruction::Load: { 6390 // Cost of wide load - cost of scalar loads. 6391 Align Alignment = cast<LoadInst>(VL0)->getAlign(); 6392 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 6393 Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0); 6394 if (NeedToShuffleReuses) { 6395 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6396 } 6397 InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost; 6398 InstructionCost VecLdCost; 6399 if (E->State == TreeEntry::Vectorize) { 6400 VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0, 6401 CostKind, VL0); 6402 } else { 6403 assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState"); 6404 Align CommonAlignment = Alignment; 6405 for (Value *V : VL) 6406 CommonAlignment = 6407 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 6408 VecLdCost = TTI->getGatherScatterOpCost( 6409 Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(), 6410 /*VariableMask=*/false, CommonAlignment, CostKind, VL0); 6411 } 6412 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost)); 6413 return CommonCost + VecLdCost - ScalarLdCost; 6414 } 6415 case Instruction::Store: { 6416 // We know that we can merge the stores. Calculate the cost. 6417 bool IsReorder = !E->ReorderIndices.empty(); 6418 auto *SI = 6419 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0); 6420 Align Alignment = SI->getAlign(); 6421 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 6422 Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0); 6423 InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost; 6424 InstructionCost VecStCost = TTI->getMemoryOpCost( 6425 Instruction::Store, VecTy, Alignment, 0, CostKind, VL0); 6426 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost)); 6427 return CommonCost + VecStCost - ScalarStCost; 6428 } 6429 case Instruction::Call: { 6430 CallInst *CI = cast<CallInst>(VL0); 6431 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 6432 6433 // Calculate the cost of the scalar and vector calls. 6434 IntrinsicCostAttributes CostAttrs(ID, *CI, 1); 6435 InstructionCost ScalarEltCost = 6436 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 6437 if (NeedToShuffleReuses) { 6438 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 6439 } 6440 InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost; 6441 6442 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 6443 InstructionCost VecCallCost = 6444 std::min(VecCallCosts.first, VecCallCosts.second); 6445 6446 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost 6447 << " (" << VecCallCost << "-" << ScalarCallCost << ")" 6448 << " for " << *CI << "\n"); 6449 6450 return CommonCost + VecCallCost - ScalarCallCost; 6451 } 6452 case Instruction::ShuffleVector: { 6453 assert(E->isAltShuffle() && 6454 ((Instruction::isBinaryOp(E->getOpcode()) && 6455 Instruction::isBinaryOp(E->getAltOpcode())) || 6456 (Instruction::isCast(E->getOpcode()) && 6457 Instruction::isCast(E->getAltOpcode())) || 6458 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 6459 "Invalid Shuffle Vector Operand"); 6460 InstructionCost ScalarCost = 0; 6461 if (NeedToShuffleReuses) { 6462 for (unsigned Idx : E->ReuseShuffleIndices) { 6463 Instruction *I = cast<Instruction>(VL[Idx]); 6464 CommonCost -= TTI->getInstructionCost(I, CostKind); 6465 } 6466 for (Value *V : VL) { 6467 Instruction *I = cast<Instruction>(V); 6468 CommonCost += TTI->getInstructionCost(I, CostKind); 6469 } 6470 } 6471 for (Value *V : VL) { 6472 Instruction *I = cast<Instruction>(V); 6473 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 6474 ScalarCost += TTI->getInstructionCost(I, CostKind); 6475 } 6476 // VecCost is equal to sum of the cost of creating 2 vectors 6477 // and the cost of creating shuffle. 6478 InstructionCost VecCost = 0; 6479 // Try to find the previous shuffle node with the same operands and same 6480 // main/alternate ops. 6481 auto &&TryFindNodeWithEqualOperands = [this, E]() { 6482 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 6483 if (TE.get() == E) 6484 break; 6485 if (TE->isAltShuffle() && 6486 ((TE->getOpcode() == E->getOpcode() && 6487 TE->getAltOpcode() == E->getAltOpcode()) || 6488 (TE->getOpcode() == E->getAltOpcode() && 6489 TE->getAltOpcode() == E->getOpcode())) && 6490 TE->hasEqualOperands(*E)) 6491 return true; 6492 } 6493 return false; 6494 }; 6495 if (TryFindNodeWithEqualOperands()) { 6496 LLVM_DEBUG({ 6497 dbgs() << "SLP: diamond match for alternate node found.\n"; 6498 E->dump(); 6499 }); 6500 // No need to add new vector costs here since we're going to reuse 6501 // same main/alternate vector ops, just do different shuffling. 6502 } else if (Instruction::isBinaryOp(E->getOpcode())) { 6503 VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind); 6504 VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy, 6505 CostKind); 6506 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 6507 VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, 6508 Builder.getInt1Ty(), 6509 CI0->getPredicate(), CostKind, VL0); 6510 VecCost += TTI->getCmpSelInstrCost( 6511 E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 6512 cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind, 6513 E->getAltOp()); 6514 } else { 6515 Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType(); 6516 Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType(); 6517 auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size()); 6518 auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size()); 6519 VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty, 6520 TTI::CastContextHint::None, CostKind); 6521 VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty, 6522 TTI::CastContextHint::None, CostKind); 6523 } 6524 6525 if (E->ReuseShuffleIndices.empty()) { 6526 CommonCost = 6527 TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy); 6528 } else { 6529 SmallVector<int> Mask; 6530 buildShuffleEntryMask( 6531 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 6532 [E](Instruction *I) { 6533 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 6534 return I->getOpcode() == E->getAltOpcode(); 6535 }, 6536 Mask); 6537 CommonCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc, 6538 FinalVecTy, Mask); 6539 } 6540 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 6541 return CommonCost + VecCost - ScalarCost; 6542 } 6543 default: 6544 llvm_unreachable("Unknown instruction"); 6545 } 6546 } 6547 6548 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const { 6549 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height " 6550 << VectorizableTree.size() << " is fully vectorizable .\n"); 6551 6552 auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) { 6553 SmallVector<int> Mask; 6554 return TE->State == TreeEntry::NeedToGather && 6555 !any_of(TE->Scalars, 6556 [this](Value *V) { return EphValues.contains(V); }) && 6557 (allConstant(TE->Scalars) || isSplat(TE->Scalars) || 6558 TE->Scalars.size() < Limit || 6559 ((TE->getOpcode() == Instruction::ExtractElement || 6560 all_of(TE->Scalars, 6561 [](Value *V) { 6562 return isa<ExtractElementInst, UndefValue>(V); 6563 })) && 6564 isFixedVectorShuffle(TE->Scalars, Mask)) || 6565 (TE->State == TreeEntry::NeedToGather && 6566 TE->getOpcode() == Instruction::Load && !TE->isAltShuffle())); 6567 }; 6568 6569 // We only handle trees of heights 1 and 2. 6570 if (VectorizableTree.size() == 1 && 6571 (VectorizableTree[0]->State == TreeEntry::Vectorize || 6572 (ForReduction && 6573 AreVectorizableGathers(VectorizableTree[0].get(), 6574 VectorizableTree[0]->Scalars.size()) && 6575 VectorizableTree[0]->getVectorFactor() > 2))) 6576 return true; 6577 6578 if (VectorizableTree.size() != 2) 6579 return false; 6580 6581 // Handle splat and all-constants stores. Also try to vectorize tiny trees 6582 // with the second gather nodes if they have less scalar operands rather than 6583 // the initial tree element (may be profitable to shuffle the second gather) 6584 // or they are extractelements, which form shuffle. 6585 SmallVector<int> Mask; 6586 if (VectorizableTree[0]->State == TreeEntry::Vectorize && 6587 AreVectorizableGathers(VectorizableTree[1].get(), 6588 VectorizableTree[0]->Scalars.size())) 6589 return true; 6590 6591 // Gathering cost would be too much for tiny trees. 6592 if (VectorizableTree[0]->State == TreeEntry::NeedToGather || 6593 (VectorizableTree[1]->State == TreeEntry::NeedToGather && 6594 VectorizableTree[0]->State != TreeEntry::ScatterVectorize)) 6595 return false; 6596 6597 return true; 6598 } 6599 6600 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts, 6601 TargetTransformInfo *TTI, 6602 bool MustMatchOrInst) { 6603 // Look past the root to find a source value. Arbitrarily follow the 6604 // path through operand 0 of any 'or'. Also, peek through optional 6605 // shift-left-by-multiple-of-8-bits. 6606 Value *ZextLoad = Root; 6607 const APInt *ShAmtC; 6608 bool FoundOr = false; 6609 while (!isa<ConstantExpr>(ZextLoad) && 6610 (match(ZextLoad, m_Or(m_Value(), m_Value())) || 6611 (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) && 6612 ShAmtC->urem(8) == 0))) { 6613 auto *BinOp = cast<BinaryOperator>(ZextLoad); 6614 ZextLoad = BinOp->getOperand(0); 6615 if (BinOp->getOpcode() == Instruction::Or) 6616 FoundOr = true; 6617 } 6618 // Check if the input is an extended load of the required or/shift expression. 6619 Value *Load; 6620 if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root || 6621 !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load)) 6622 return false; 6623 6624 // Require that the total load bit width is a legal integer type. 6625 // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target. 6626 // But <16 x i8> --> i128 is not, so the backend probably can't reduce it. 6627 Type *SrcTy = Load->getType(); 6628 unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts; 6629 if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth))) 6630 return false; 6631 6632 // Everything matched - assume that we can fold the whole sequence using 6633 // load combining. 6634 LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at " 6635 << *(cast<Instruction>(Root)) << "\n"); 6636 6637 return true; 6638 } 6639 6640 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const { 6641 if (RdxKind != RecurKind::Or) 6642 return false; 6643 6644 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 6645 Value *FirstReduced = VectorizableTree[0]->Scalars[0]; 6646 return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI, 6647 /* MatchOr */ false); 6648 } 6649 6650 bool BoUpSLP::isLoadCombineCandidate() const { 6651 // Peek through a final sequence of stores and check if all operations are 6652 // likely to be load-combined. 6653 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 6654 for (Value *Scalar : VectorizableTree[0]->Scalars) { 6655 Value *X; 6656 if (!match(Scalar, m_Store(m_Value(X), m_Value())) || 6657 !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true)) 6658 return false; 6659 } 6660 return true; 6661 } 6662 6663 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const { 6664 // No need to vectorize inserts of gathered values. 6665 if (VectorizableTree.size() == 2 && 6666 isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) && 6667 VectorizableTree[1]->State == TreeEntry::NeedToGather && 6668 (VectorizableTree[1]->getVectorFactor() <= 2 || 6669 !(isSplat(VectorizableTree[1]->Scalars) || 6670 allConstant(VectorizableTree[1]->Scalars)))) 6671 return true; 6672 6673 // We can vectorize the tree if its size is greater than or equal to the 6674 // minimum size specified by the MinTreeSize command line option. 6675 if (VectorizableTree.size() >= MinTreeSize) 6676 return false; 6677 6678 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we 6679 // can vectorize it if we can prove it fully vectorizable. 6680 if (isFullyVectorizableTinyTree(ForReduction)) 6681 return false; 6682 6683 assert(VectorizableTree.empty() 6684 ? ExternalUses.empty() 6685 : true && "We shouldn't have any external users"); 6686 6687 // Otherwise, we can't vectorize the tree. It is both tiny and not fully 6688 // vectorizable. 6689 return true; 6690 } 6691 6692 InstructionCost BoUpSLP::getSpillCost() const { 6693 // Walk from the bottom of the tree to the top, tracking which values are 6694 // live. When we see a call instruction that is not part of our tree, 6695 // query TTI to see if there is a cost to keeping values live over it 6696 // (for example, if spills and fills are required). 6697 unsigned BundleWidth = VectorizableTree.front()->Scalars.size(); 6698 InstructionCost Cost = 0; 6699 6700 SmallPtrSet<Instruction*, 4> LiveValues; 6701 Instruction *PrevInst = nullptr; 6702 6703 // The entries in VectorizableTree are not necessarily ordered by their 6704 // position in basic blocks. Collect them and order them by dominance so later 6705 // instructions are guaranteed to be visited first. For instructions in 6706 // different basic blocks, we only scan to the beginning of the block, so 6707 // their order does not matter, as long as all instructions in a basic block 6708 // are grouped together. Using dominance ensures a deterministic order. 6709 SmallVector<Instruction *, 16> OrderedScalars; 6710 for (const auto &TEPtr : VectorizableTree) { 6711 Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]); 6712 if (!Inst) 6713 continue; 6714 OrderedScalars.push_back(Inst); 6715 } 6716 llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) { 6717 auto *NodeA = DT->getNode(A->getParent()); 6718 auto *NodeB = DT->getNode(B->getParent()); 6719 assert(NodeA && "Should only process reachable instructions"); 6720 assert(NodeB && "Should only process reachable instructions"); 6721 assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && 6722 "Different nodes should have different DFS numbers"); 6723 if (NodeA != NodeB) 6724 return NodeA->getDFSNumIn() < NodeB->getDFSNumIn(); 6725 return B->comesBefore(A); 6726 }); 6727 6728 for (Instruction *Inst : OrderedScalars) { 6729 if (!PrevInst) { 6730 PrevInst = Inst; 6731 continue; 6732 } 6733 6734 // Update LiveValues. 6735 LiveValues.erase(PrevInst); 6736 for (auto &J : PrevInst->operands()) { 6737 if (isa<Instruction>(&*J) && getTreeEntry(&*J)) 6738 LiveValues.insert(cast<Instruction>(&*J)); 6739 } 6740 6741 LLVM_DEBUG({ 6742 dbgs() << "SLP: #LV: " << LiveValues.size(); 6743 for (auto *X : LiveValues) 6744 dbgs() << " " << X->getName(); 6745 dbgs() << ", Looking at "; 6746 Inst->dump(); 6747 }); 6748 6749 // Now find the sequence of instructions between PrevInst and Inst. 6750 unsigned NumCalls = 0; 6751 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(), 6752 PrevInstIt = 6753 PrevInst->getIterator().getReverse(); 6754 while (InstIt != PrevInstIt) { 6755 if (PrevInstIt == PrevInst->getParent()->rend()) { 6756 PrevInstIt = Inst->getParent()->rbegin(); 6757 continue; 6758 } 6759 6760 // Debug information does not impact spill cost. 6761 if ((isa<CallInst>(&*PrevInstIt) && 6762 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) && 6763 &*PrevInstIt != PrevInst) 6764 NumCalls++; 6765 6766 ++PrevInstIt; 6767 } 6768 6769 if (NumCalls) { 6770 SmallVector<Type*, 4> V; 6771 for (auto *II : LiveValues) { 6772 auto *ScalarTy = II->getType(); 6773 if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy)) 6774 ScalarTy = VectorTy->getElementType(); 6775 V.push_back(FixedVectorType::get(ScalarTy, BundleWidth)); 6776 } 6777 Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V); 6778 } 6779 6780 PrevInst = Inst; 6781 } 6782 6783 return Cost; 6784 } 6785 6786 /// Check if two insertelement instructions are from the same buildvector. 6787 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU, 6788 InsertElementInst *V) { 6789 // Instructions must be from the same basic blocks. 6790 if (VU->getParent() != V->getParent()) 6791 return false; 6792 // Checks if 2 insertelements are from the same buildvector. 6793 if (VU->getType() != V->getType()) 6794 return false; 6795 // Multiple used inserts are separate nodes. 6796 if (!VU->hasOneUse() && !V->hasOneUse()) 6797 return false; 6798 auto *IE1 = VU; 6799 auto *IE2 = V; 6800 unsigned Idx1 = *getInsertIndex(IE1); 6801 unsigned Idx2 = *getInsertIndex(IE2); 6802 // Go through the vector operand of insertelement instructions trying to find 6803 // either VU as the original vector for IE2 or V as the original vector for 6804 // IE1. 6805 do { 6806 if (IE2 == VU) 6807 return VU->hasOneUse(); 6808 if (IE1 == V) 6809 return V->hasOneUse(); 6810 if (IE1) { 6811 if ((IE1 != VU && !IE1->hasOneUse()) || 6812 getInsertIndex(IE1).value_or(Idx2) == Idx2) 6813 IE1 = nullptr; 6814 else 6815 IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0)); 6816 } 6817 if (IE2) { 6818 if ((IE2 != V && !IE2->hasOneUse()) || 6819 getInsertIndex(IE2).value_or(Idx1) == Idx1) 6820 IE2 = nullptr; 6821 else 6822 IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0)); 6823 } 6824 } while (IE1 || IE2); 6825 return false; 6826 } 6827 6828 /// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the 6829 /// buildvector sequence. 6830 static bool isFirstInsertElement(const InsertElementInst *IE1, 6831 const InsertElementInst *IE2) { 6832 if (IE1 == IE2) 6833 return false; 6834 const auto *I1 = IE1; 6835 const auto *I2 = IE2; 6836 const InsertElementInst *PrevI1; 6837 const InsertElementInst *PrevI2; 6838 unsigned Idx1 = *getInsertIndex(IE1); 6839 unsigned Idx2 = *getInsertIndex(IE2); 6840 do { 6841 if (I2 == IE1) 6842 return true; 6843 if (I1 == IE2) 6844 return false; 6845 PrevI1 = I1; 6846 PrevI2 = I2; 6847 if (I1 && (I1 == IE1 || I1->hasOneUse()) && 6848 getInsertIndex(I1).value_or(Idx2) != Idx2) 6849 I1 = dyn_cast<InsertElementInst>(I1->getOperand(0)); 6850 if (I2 && ((I2 == IE2 || I2->hasOneUse())) && 6851 getInsertIndex(I2).value_or(Idx1) != Idx1) 6852 I2 = dyn_cast<InsertElementInst>(I2->getOperand(0)); 6853 } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2)); 6854 llvm_unreachable("Two different buildvectors not expected."); 6855 } 6856 6857 namespace { 6858 /// Returns incoming Value *, if the requested type is Value * too, or a default 6859 /// value, otherwise. 6860 struct ValueSelect { 6861 template <typename U> 6862 static typename std::enable_if<std::is_same<Value *, U>::value, Value *>::type 6863 get(Value *V) { 6864 return V; 6865 } 6866 template <typename U> 6867 static typename std::enable_if<!std::is_same<Value *, U>::value, U>::type 6868 get(Value *) { 6869 return U(); 6870 } 6871 }; 6872 } // namespace 6873 6874 /// Does the analysis of the provided shuffle masks and performs the requested 6875 /// actions on the vectors with the given shuffle masks. It tries to do it in 6876 /// several steps. 6877 /// 1. If the Base vector is not undef vector, resizing the very first mask to 6878 /// have common VF and perform action for 2 input vectors (including non-undef 6879 /// Base). Other shuffle masks are combined with the resulting after the 1 stage 6880 /// and processed as a shuffle of 2 elements. 6881 /// 2. If the Base is undef vector and have only 1 shuffle mask, perform the 6882 /// action only for 1 vector with the given mask, if it is not the identity 6883 /// mask. 6884 /// 3. If > 2 masks are used, perform the remaining shuffle actions for 2 6885 /// vectors, combing the masks properly between the steps. 6886 template <typename T> 6887 static T *performExtractsShuffleAction( 6888 MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base, 6889 function_ref<unsigned(T *)> GetVF, 6890 function_ref<std::pair<T *, bool>(T *, ArrayRef<int>)> ResizeAction, 6891 function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) { 6892 assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts."); 6893 SmallVector<int> Mask(ShuffleMask.begin()->second); 6894 auto VMIt = std::next(ShuffleMask.begin()); 6895 T *Prev = nullptr; 6896 bool IsBaseNotUndef = !isUndefVector(Base); 6897 if (IsBaseNotUndef) { 6898 // Base is not undef, need to combine it with the next subvectors. 6899 std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask); 6900 for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) { 6901 if (Mask[Idx] == UndefMaskElem) 6902 Mask[Idx] = Idx; 6903 else 6904 Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF; 6905 } 6906 auto *V = ValueSelect::get<T *>(Base); 6907 (void)V; 6908 assert((!V || GetVF(V) == Mask.size()) && 6909 "Expected base vector of VF number of elements."); 6910 Prev = Action(Mask, {nullptr, Res.first}); 6911 } else if (ShuffleMask.size() == 1) { 6912 // Base is undef and only 1 vector is shuffled - perform the action only for 6913 // single vector, if the mask is not the identity mask. 6914 std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask); 6915 if (Res.second) 6916 // Identity mask is found. 6917 Prev = Res.first; 6918 else 6919 Prev = Action(Mask, {ShuffleMask.begin()->first}); 6920 } else { 6921 // Base is undef and at least 2 input vectors shuffled - perform 2 vectors 6922 // shuffles step by step, combining shuffle between the steps. 6923 unsigned Vec1VF = GetVF(ShuffleMask.begin()->first); 6924 unsigned Vec2VF = GetVF(VMIt->first); 6925 if (Vec1VF == Vec2VF) { 6926 // No need to resize the input vectors since they are of the same size, we 6927 // can shuffle them directly. 6928 ArrayRef<int> SecMask = VMIt->second; 6929 for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) { 6930 if (SecMask[I] != UndefMaskElem) { 6931 assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars."); 6932 Mask[I] = SecMask[I] + Vec1VF; 6933 } 6934 } 6935 Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first}); 6936 } else { 6937 // Vectors of different sizes - resize and reshuffle. 6938 std::pair<T *, bool> Res1 = 6939 ResizeAction(ShuffleMask.begin()->first, Mask); 6940 std::pair<T *, bool> Res2 = ResizeAction(VMIt->first, VMIt->second); 6941 ArrayRef<int> SecMask = VMIt->second; 6942 for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) { 6943 if (Mask[I] != UndefMaskElem) { 6944 assert(SecMask[I] == UndefMaskElem && "Multiple uses of scalars."); 6945 if (Res1.second) 6946 Mask[I] = I; 6947 } else if (SecMask[I] != UndefMaskElem) { 6948 assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars."); 6949 Mask[I] = (Res2.second ? I : SecMask[I]) + VF; 6950 } 6951 } 6952 Prev = Action(Mask, {Res1.first, Res2.first}); 6953 } 6954 VMIt = std::next(VMIt); 6955 } 6956 // Perform requested actions for the remaining masks/vectors. 6957 for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) { 6958 // Shuffle other input vectors, if any. 6959 std::pair<T *, bool> Res = ResizeAction(VMIt->first, VMIt->second); 6960 ArrayRef<int> SecMask = VMIt->second; 6961 for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) { 6962 if (SecMask[I] != UndefMaskElem) { 6963 assert((Mask[I] == UndefMaskElem || IsBaseNotUndef) && 6964 "Multiple uses of scalars."); 6965 Mask[I] = (Res.second ? I : SecMask[I]) + VF; 6966 } else if (Mask[I] != UndefMaskElem) { 6967 Mask[I] = I; 6968 } 6969 } 6970 Prev = Action(Mask, {Prev, Res.first}); 6971 } 6972 return Prev; 6973 } 6974 6975 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) { 6976 InstructionCost Cost = 0; 6977 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size " 6978 << VectorizableTree.size() << ".\n"); 6979 6980 unsigned BundleWidth = VectorizableTree[0]->Scalars.size(); 6981 6982 for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) { 6983 TreeEntry &TE = *VectorizableTree[I]; 6984 6985 InstructionCost C = getEntryCost(&TE, VectorizedVals); 6986 Cost += C; 6987 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6988 << " for bundle that starts with " << *TE.Scalars[0] 6989 << ".\n" 6990 << "SLP: Current total cost = " << Cost << "\n"); 6991 } 6992 6993 SmallPtrSet<Value *, 16> ExtractCostCalculated; 6994 InstructionCost ExtractCost = 0; 6995 SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks; 6996 SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers; 6997 SmallVector<APInt> DemandedElts; 6998 for (ExternalUser &EU : ExternalUses) { 6999 // We only add extract cost once for the same scalar. 7000 if (!isa_and_nonnull<InsertElementInst>(EU.User) && 7001 !ExtractCostCalculated.insert(EU.Scalar).second) 7002 continue; 7003 7004 // Uses by ephemeral values are free (because the ephemeral value will be 7005 // removed prior to code generation, and so the extraction will be 7006 // removed as well). 7007 if (EphValues.count(EU.User)) 7008 continue; 7009 7010 // No extract cost for vector "scalar" 7011 if (isa<FixedVectorType>(EU.Scalar->getType())) 7012 continue; 7013 7014 // Already counted the cost for external uses when tried to adjust the cost 7015 // for extractelements, no need to add it again. 7016 if (isa<ExtractElementInst>(EU.Scalar)) 7017 continue; 7018 7019 // If found user is an insertelement, do not calculate extract cost but try 7020 // to detect it as a final shuffled/identity match. 7021 if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) { 7022 if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) { 7023 Optional<unsigned> InsertIdx = getInsertIndex(VU); 7024 if (InsertIdx) { 7025 const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar); 7026 auto *It = 7027 find_if(FirstUsers, 7028 [VU](const std::pair<Value *, const TreeEntry *> &Pair) { 7029 return areTwoInsertFromSameBuildVector( 7030 VU, cast<InsertElementInst>(Pair.first)); 7031 }); 7032 int VecId = -1; 7033 if (It == FirstUsers.end()) { 7034 (void)ShuffleMasks.emplace_back(); 7035 SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE]; 7036 if (Mask.empty()) 7037 Mask.assign(FTy->getNumElements(), UndefMaskElem); 7038 // Find the insertvector, vectorized in tree, if any. 7039 Value *Base = VU; 7040 while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) { 7041 if (IEBase != EU.User && 7042 (!IEBase->hasOneUse() || 7043 getInsertIndex(IEBase).value_or(*InsertIdx) == *InsertIdx)) 7044 break; 7045 // Build the mask for the vectorized insertelement instructions. 7046 if (const TreeEntry *E = getTreeEntry(IEBase)) { 7047 VU = IEBase; 7048 do { 7049 IEBase = cast<InsertElementInst>(Base); 7050 int Idx = *getInsertIndex(IEBase); 7051 assert(Mask[Idx] == UndefMaskElem && 7052 "InsertElementInstruction used already."); 7053 Mask[Idx] = Idx; 7054 Base = IEBase->getOperand(0); 7055 } while (E == getTreeEntry(Base)); 7056 break; 7057 } 7058 Base = cast<InsertElementInst>(Base)->getOperand(0); 7059 } 7060 FirstUsers.emplace_back(VU, ScalarTE); 7061 DemandedElts.push_back(APInt::getZero(FTy->getNumElements())); 7062 VecId = FirstUsers.size() - 1; 7063 } else { 7064 if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first))) 7065 It->first = VU; 7066 VecId = std::distance(FirstUsers.begin(), It); 7067 } 7068 int InIdx = *InsertIdx; 7069 SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE]; 7070 if (Mask.empty()) 7071 Mask.assign(FTy->getNumElements(), UndefMaskElem); 7072 Mask[InIdx] = EU.Lane; 7073 DemandedElts[VecId].setBit(InIdx); 7074 continue; 7075 } 7076 } 7077 } 7078 7079 // If we plan to rewrite the tree in a smaller type, we will need to sign 7080 // extend the extracted value back to the original type. Here, we account 7081 // for the extract and the added cost of the sign extend if needed. 7082 auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth); 7083 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 7084 if (MinBWs.count(ScalarRoot)) { 7085 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 7086 auto Extend = 7087 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt; 7088 VecTy = FixedVectorType::get(MinTy, BundleWidth); 7089 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(), 7090 VecTy, EU.Lane); 7091 } else { 7092 ExtractCost += 7093 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane); 7094 } 7095 } 7096 7097 InstructionCost SpillCost = getSpillCost(); 7098 Cost += SpillCost + ExtractCost; 7099 auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask) { 7100 InstructionCost C = 0; 7101 unsigned VF = Mask.size(); 7102 unsigned VecVF = TE->getVectorFactor(); 7103 if (VF != VecVF && 7104 (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) || 7105 (all_of(Mask, 7106 [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) && 7107 !ShuffleVectorInst::isIdentityMask(Mask)))) { 7108 SmallVector<int> OrigMask(VecVF, UndefMaskElem); 7109 std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)), 7110 OrigMask.begin()); 7111 C = TTI->getShuffleCost( 7112 TTI::SK_PermuteSingleSrc, 7113 FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask); 7114 LLVM_DEBUG( 7115 dbgs() << "SLP: Adding cost " << C 7116 << " for final shuffle of insertelement external users.\n"; 7117 TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n"); 7118 Cost += C; 7119 return std::make_pair(TE, true); 7120 } 7121 return std::make_pair(TE, false); 7122 }; 7123 // Calculate the cost of the reshuffled vectors, if any. 7124 for (int I = 0, E = FirstUsers.size(); I < E; ++I) { 7125 Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0); 7126 unsigned VF = ShuffleMasks[I].begin()->second.size(); 7127 auto *FTy = FixedVectorType::get( 7128 cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF); 7129 auto Vector = ShuffleMasks[I].takeVector(); 7130 auto &&EstimateShufflesCost = [this, FTy, 7131 &Cost](ArrayRef<int> Mask, 7132 ArrayRef<const TreeEntry *> TEs) { 7133 assert((TEs.size() == 1 || TEs.size() == 2) && 7134 "Expected exactly 1 or 2 tree entries."); 7135 if (TEs.size() == 1) { 7136 int Limit = 2 * Mask.size(); 7137 if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) || 7138 !ShuffleVectorInst::isIdentityMask(Mask)) { 7139 InstructionCost C = 7140 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask); 7141 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 7142 << " for final shuffle of insertelement " 7143 "external users.\n"; 7144 TEs.front()->dump(); 7145 dbgs() << "SLP: Current total cost = " << Cost << "\n"); 7146 Cost += C; 7147 } 7148 } else { 7149 InstructionCost C = 7150 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask); 7151 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 7152 << " for final shuffle of vector node and external " 7153 "insertelement users.\n"; 7154 if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump(); 7155 dbgs() << "SLP: Current total cost = " << Cost << "\n"); 7156 Cost += C; 7157 } 7158 return TEs.back(); 7159 }; 7160 (void)performExtractsShuffleAction<const TreeEntry>( 7161 makeMutableArrayRef(Vector.data(), Vector.size()), Base, 7162 [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF, 7163 EstimateShufflesCost); 7164 InstructionCost InsertCost = TTI->getScalarizationOverhead( 7165 cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I], 7166 /*Insert*/ true, /*Extract*/ false); 7167 Cost -= InsertCost; 7168 } 7169 7170 #ifndef NDEBUG 7171 SmallString<256> Str; 7172 { 7173 raw_svector_ostream OS(Str); 7174 OS << "SLP: Spill Cost = " << SpillCost << ".\n" 7175 << "SLP: Extract Cost = " << ExtractCost << ".\n" 7176 << "SLP: Total Cost = " << Cost << ".\n"; 7177 } 7178 LLVM_DEBUG(dbgs() << Str); 7179 if (ViewSLPTree) 7180 ViewGraph(this, "SLP" + F->getName(), false, Str); 7181 #endif 7182 7183 return Cost; 7184 } 7185 7186 Optional<TargetTransformInfo::ShuffleKind> 7187 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 7188 SmallVectorImpl<const TreeEntry *> &Entries) { 7189 // TODO: currently checking only for Scalars in the tree entry, need to count 7190 // reused elements too for better cost estimation. 7191 Mask.assign(TE->Scalars.size(), UndefMaskElem); 7192 Entries.clear(); 7193 // Build a lists of values to tree entries. 7194 DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs; 7195 for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) { 7196 if (EntryPtr.get() == TE) 7197 break; 7198 if (EntryPtr->State != TreeEntry::NeedToGather) 7199 continue; 7200 for (Value *V : EntryPtr->Scalars) 7201 ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get()); 7202 } 7203 // Find all tree entries used by the gathered values. If no common entries 7204 // found - not a shuffle. 7205 // Here we build a set of tree nodes for each gathered value and trying to 7206 // find the intersection between these sets. If we have at least one common 7207 // tree node for each gathered value - we have just a permutation of the 7208 // single vector. If we have 2 different sets, we're in situation where we 7209 // have a permutation of 2 input vectors. 7210 SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs; 7211 DenseMap<Value *, int> UsedValuesEntry; 7212 for (Value *V : TE->Scalars) { 7213 if (isa<UndefValue>(V)) 7214 continue; 7215 // Build a list of tree entries where V is used. 7216 SmallPtrSet<const TreeEntry *, 4> VToTEs; 7217 auto It = ValueToTEs.find(V); 7218 if (It != ValueToTEs.end()) 7219 VToTEs = It->second; 7220 if (const TreeEntry *VTE = getTreeEntry(V)) 7221 VToTEs.insert(VTE); 7222 if (VToTEs.empty()) 7223 return None; 7224 if (UsedTEs.empty()) { 7225 // The first iteration, just insert the list of nodes to vector. 7226 UsedTEs.push_back(VToTEs); 7227 } else { 7228 // Need to check if there are any previously used tree nodes which use V. 7229 // If there are no such nodes, consider that we have another one input 7230 // vector. 7231 SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs); 7232 unsigned Idx = 0; 7233 for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) { 7234 // Do we have a non-empty intersection of previously listed tree entries 7235 // and tree entries using current V? 7236 set_intersect(VToTEs, Set); 7237 if (!VToTEs.empty()) { 7238 // Yes, write the new subset and continue analysis for the next 7239 // scalar. 7240 Set.swap(VToTEs); 7241 break; 7242 } 7243 VToTEs = SavedVToTEs; 7244 ++Idx; 7245 } 7246 // No non-empty intersection found - need to add a second set of possible 7247 // source vectors. 7248 if (Idx == UsedTEs.size()) { 7249 // If the number of input vectors is greater than 2 - not a permutation, 7250 // fallback to the regular gather. 7251 if (UsedTEs.size() == 2) 7252 return None; 7253 UsedTEs.push_back(SavedVToTEs); 7254 Idx = UsedTEs.size() - 1; 7255 } 7256 UsedValuesEntry.try_emplace(V, Idx); 7257 } 7258 } 7259 7260 if (UsedTEs.empty()) { 7261 assert(all_of(TE->Scalars, UndefValue::classof) && 7262 "Expected vector of undefs only."); 7263 return None; 7264 } 7265 7266 unsigned VF = 0; 7267 if (UsedTEs.size() == 1) { 7268 // Try to find the perfect match in another gather node at first. 7269 auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) { 7270 return EntryPtr->isSame(TE->Scalars); 7271 }); 7272 if (It != UsedTEs.front().end()) { 7273 Entries.push_back(*It); 7274 std::iota(Mask.begin(), Mask.end(), 0); 7275 return TargetTransformInfo::SK_PermuteSingleSrc; 7276 } 7277 // No perfect match, just shuffle, so choose the first tree node. 7278 Entries.push_back(*UsedTEs.front().begin()); 7279 } else { 7280 // Try to find nodes with the same vector factor. 7281 assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries."); 7282 DenseMap<int, const TreeEntry *> VFToTE; 7283 for (const TreeEntry *TE : UsedTEs.front()) 7284 VFToTE.try_emplace(TE->getVectorFactor(), TE); 7285 for (const TreeEntry *TE : UsedTEs.back()) { 7286 auto It = VFToTE.find(TE->getVectorFactor()); 7287 if (It != VFToTE.end()) { 7288 VF = It->first; 7289 Entries.push_back(It->second); 7290 Entries.push_back(TE); 7291 break; 7292 } 7293 } 7294 // No 2 source vectors with the same vector factor - give up and do regular 7295 // gather. 7296 if (Entries.empty()) 7297 return None; 7298 } 7299 7300 // Build a shuffle mask for better cost estimation and vector emission. 7301 for (int I = 0, E = TE->Scalars.size(); I < E; ++I) { 7302 Value *V = TE->Scalars[I]; 7303 if (isa<UndefValue>(V)) 7304 continue; 7305 unsigned Idx = UsedValuesEntry.lookup(V); 7306 const TreeEntry *VTE = Entries[Idx]; 7307 int FoundLane = VTE->findLaneForValue(V); 7308 Mask[I] = Idx * VF + FoundLane; 7309 // Extra check required by isSingleSourceMaskImpl function (called by 7310 // ShuffleVectorInst::isSingleSourceMask). 7311 if (Mask[I] >= 2 * E) 7312 return None; 7313 } 7314 switch (Entries.size()) { 7315 case 1: 7316 return TargetTransformInfo::SK_PermuteSingleSrc; 7317 case 2: 7318 return TargetTransformInfo::SK_PermuteTwoSrc; 7319 default: 7320 break; 7321 } 7322 return None; 7323 } 7324 7325 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty, 7326 const APInt &ShuffledIndices, 7327 bool NeedToShuffle) const { 7328 InstructionCost Cost = 7329 TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true, 7330 /*Extract*/ false); 7331 if (NeedToShuffle) 7332 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty); 7333 return Cost; 7334 } 7335 7336 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const { 7337 // Find the type of the operands in VL. 7338 Type *ScalarTy = VL[0]->getType(); 7339 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 7340 ScalarTy = SI->getValueOperand()->getType(); 7341 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 7342 bool DuplicateNonConst = false; 7343 // Find the cost of inserting/extracting values from the vector. 7344 // Check if the same elements are inserted several times and count them as 7345 // shuffle candidates. 7346 APInt ShuffledElements = APInt::getZero(VL.size()); 7347 DenseSet<Value *> UniqueElements; 7348 // Iterate in reverse order to consider insert elements with the high cost. 7349 for (unsigned I = VL.size(); I > 0; --I) { 7350 unsigned Idx = I - 1; 7351 // No need to shuffle duplicates for constants. 7352 if (isConstant(VL[Idx])) { 7353 ShuffledElements.setBit(Idx); 7354 continue; 7355 } 7356 if (!UniqueElements.insert(VL[Idx]).second) { 7357 DuplicateNonConst = true; 7358 ShuffledElements.setBit(Idx); 7359 } 7360 } 7361 return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst); 7362 } 7363 7364 // Perform operand reordering on the instructions in VL and return the reordered 7365 // operands in Left and Right. 7366 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 7367 SmallVectorImpl<Value *> &Left, 7368 SmallVectorImpl<Value *> &Right, 7369 const DataLayout &DL, 7370 ScalarEvolution &SE, 7371 const BoUpSLP &R) { 7372 if (VL.empty()) 7373 return; 7374 VLOperands Ops(VL, DL, SE, R); 7375 // Reorder the operands in place. 7376 Ops.reorder(); 7377 Left = Ops.getVL(0); 7378 Right = Ops.getVL(1); 7379 } 7380 7381 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) { 7382 // Get the basic block this bundle is in. All instructions in the bundle 7383 // should be in this block (except for extractelement-like instructions with 7384 // constant indeces). 7385 auto *Front = E->getMainOp(); 7386 auto *BB = Front->getParent(); 7387 assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool { 7388 if (E->getOpcode() == Instruction::GetElementPtr && 7389 !isa<GetElementPtrInst>(V)) 7390 return true; 7391 auto *I = cast<Instruction>(V); 7392 return !E->isOpcodeOrAlt(I) || I->getParent() == BB || 7393 isVectorLikeInstWithConstOps(I); 7394 })); 7395 7396 auto &&FindLastInst = [E, Front, this, &BB]() { 7397 Instruction *LastInst = Front; 7398 for (Value *V : E->Scalars) { 7399 auto *I = dyn_cast<Instruction>(V); 7400 if (!I) 7401 continue; 7402 if (LastInst->getParent() == I->getParent()) { 7403 if (LastInst->comesBefore(I)) 7404 LastInst = I; 7405 continue; 7406 } 7407 assert(isVectorLikeInstWithConstOps(LastInst) && 7408 isVectorLikeInstWithConstOps(I) && 7409 "Expected vector-like insts only."); 7410 if (!DT->isReachableFromEntry(LastInst->getParent())) { 7411 LastInst = I; 7412 continue; 7413 } 7414 if (!DT->isReachableFromEntry(I->getParent())) 7415 continue; 7416 auto *NodeA = DT->getNode(LastInst->getParent()); 7417 auto *NodeB = DT->getNode(I->getParent()); 7418 assert(NodeA && "Should only process reachable instructions"); 7419 assert(NodeB && "Should only process reachable instructions"); 7420 assert((NodeA == NodeB) == 7421 (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && 7422 "Different nodes should have different DFS numbers"); 7423 if (NodeA->getDFSNumIn() < NodeB->getDFSNumIn()) 7424 LastInst = I; 7425 } 7426 BB = LastInst->getParent(); 7427 return LastInst; 7428 }; 7429 7430 auto &&FindFirstInst = [E, Front]() { 7431 Instruction *FirstInst = Front; 7432 for (Value *V : E->Scalars) { 7433 auto *I = dyn_cast<Instruction>(V); 7434 if (!I) 7435 continue; 7436 if (I->comesBefore(FirstInst)) 7437 FirstInst = I; 7438 } 7439 return FirstInst; 7440 }; 7441 7442 // Set the insert point to the beginning of the basic block if the entry 7443 // should not be scheduled. 7444 if (E->State != TreeEntry::NeedToGather && 7445 doesNotNeedToSchedule(E->Scalars)) { 7446 Instruction *InsertInst; 7447 if (all_of(E->Scalars, isUsedOutsideBlock)) 7448 InsertInst = FindLastInst(); 7449 else 7450 InsertInst = FindFirstInst(); 7451 // If the instruction is PHI, set the insert point after all the PHIs. 7452 if (isa<PHINode>(InsertInst)) 7453 InsertInst = BB->getFirstNonPHI(); 7454 BasicBlock::iterator InsertPt = InsertInst->getIterator(); 7455 Builder.SetInsertPoint(BB, InsertPt); 7456 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 7457 return; 7458 } 7459 7460 // The last instruction in the bundle in program order. 7461 Instruction *LastInst = nullptr; 7462 7463 // Find the last instruction. The common case should be that BB has been 7464 // scheduled, and the last instruction is VL.back(). So we start with 7465 // VL.back() and iterate over schedule data until we reach the end of the 7466 // bundle. The end of the bundle is marked by null ScheduleData. 7467 if (BlocksSchedules.count(BB)) { 7468 Value *V = E->isOneOf(E->Scalars.back()); 7469 if (doesNotNeedToBeScheduled(V)) 7470 V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled); 7471 auto *Bundle = BlocksSchedules[BB]->getScheduleData(V); 7472 if (Bundle && Bundle->isPartOfBundle()) 7473 for (; Bundle; Bundle = Bundle->NextInBundle) 7474 if (Bundle->OpValue == Bundle->Inst) 7475 LastInst = Bundle->Inst; 7476 } 7477 7478 // LastInst can still be null at this point if there's either not an entry 7479 // for BB in BlocksSchedules or there's no ScheduleData available for 7480 // VL.back(). This can be the case if buildTree_rec aborts for various 7481 // reasons (e.g., the maximum recursion depth is reached, the maximum region 7482 // size is reached, etc.). ScheduleData is initialized in the scheduling 7483 // "dry-run". 7484 // 7485 // If this happens, we can still find the last instruction by brute force. We 7486 // iterate forwards from Front (inclusive) until we either see all 7487 // instructions in the bundle or reach the end of the block. If Front is the 7488 // last instruction in program order, LastInst will be set to Front, and we 7489 // will visit all the remaining instructions in the block. 7490 // 7491 // One of the reasons we exit early from buildTree_rec is to place an upper 7492 // bound on compile-time. Thus, taking an additional compile-time hit here is 7493 // not ideal. However, this should be exceedingly rare since it requires that 7494 // we both exit early from buildTree_rec and that the bundle be out-of-order 7495 // (causing us to iterate all the way to the end of the block). 7496 if (!LastInst) { 7497 LastInst = FindLastInst(); 7498 // If the instruction is PHI, set the insert point after all the PHIs. 7499 if (isa<PHINode>(LastInst)) 7500 LastInst = BB->getFirstNonPHI()->getPrevNode(); 7501 } 7502 assert(LastInst && "Failed to find last instruction in bundle"); 7503 7504 // Set the insertion point after the last instruction in the bundle. Set the 7505 // debug location to Front. 7506 Builder.SetInsertPoint(BB, std::next(LastInst->getIterator())); 7507 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 7508 } 7509 7510 Value *BoUpSLP::gather(ArrayRef<Value *> VL) { 7511 // List of instructions/lanes from current block and/or the blocks which are 7512 // part of the current loop. These instructions will be inserted at the end to 7513 // make it possible to optimize loops and hoist invariant instructions out of 7514 // the loops body with better chances for success. 7515 SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts; 7516 SmallSet<int, 4> PostponedIndices; 7517 Loop *L = LI->getLoopFor(Builder.GetInsertBlock()); 7518 auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) { 7519 SmallPtrSet<BasicBlock *, 4> Visited; 7520 while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second) 7521 InsertBB = InsertBB->getSinglePredecessor(); 7522 return InsertBB && InsertBB == InstBB; 7523 }; 7524 for (int I = 0, E = VL.size(); I < E; ++I) { 7525 if (auto *Inst = dyn_cast<Instruction>(VL[I])) 7526 if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) || 7527 getTreeEntry(Inst) || (L && (L->contains(Inst)))) && 7528 PostponedIndices.insert(I).second) 7529 PostponedInsts.emplace_back(Inst, I); 7530 } 7531 7532 auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) { 7533 Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos)); 7534 auto *InsElt = dyn_cast<InsertElementInst>(Vec); 7535 if (!InsElt) 7536 return Vec; 7537 GatherShuffleSeq.insert(InsElt); 7538 CSEBlocks.insert(InsElt->getParent()); 7539 // Add to our 'need-to-extract' list. 7540 if (TreeEntry *Entry = getTreeEntry(V)) { 7541 // Find which lane we need to extract. 7542 unsigned FoundLane = Entry->findLaneForValue(V); 7543 ExternalUses.emplace_back(V, InsElt, FoundLane); 7544 } 7545 return Vec; 7546 }; 7547 Value *Val0 = 7548 isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0]; 7549 FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size()); 7550 Value *Vec = PoisonValue::get(VecTy); 7551 SmallVector<int> NonConsts; 7552 // Insert constant values at first. 7553 for (int I = 0, E = VL.size(); I < E; ++I) { 7554 if (PostponedIndices.contains(I)) 7555 continue; 7556 if (!isConstant(VL[I])) { 7557 NonConsts.push_back(I); 7558 continue; 7559 } 7560 Vec = CreateInsertElement(Vec, VL[I], I); 7561 } 7562 // Insert non-constant values. 7563 for (int I : NonConsts) 7564 Vec = CreateInsertElement(Vec, VL[I], I); 7565 // Append instructions, which are/may be part of the loop, in the end to make 7566 // it possible to hoist non-loop-based instructions. 7567 for (const std::pair<Value *, unsigned> &Pair : PostponedInsts) 7568 Vec = CreateInsertElement(Vec, Pair.first, Pair.second); 7569 7570 return Vec; 7571 } 7572 7573 namespace { 7574 /// Merges shuffle masks and emits final shuffle instruction, if required. 7575 class ShuffleInstructionBuilder { 7576 IRBuilderBase &Builder; 7577 const unsigned VF = 0; 7578 bool IsFinalized = false; 7579 SmallVector<int, 4> Mask; 7580 /// Holds all of the instructions that we gathered. 7581 SetVector<Instruction *> &GatherShuffleSeq; 7582 /// A list of blocks that we are going to CSE. 7583 SetVector<BasicBlock *> &CSEBlocks; 7584 7585 public: 7586 ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF, 7587 SetVector<Instruction *> &GatherShuffleSeq, 7588 SetVector<BasicBlock *> &CSEBlocks) 7589 : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq), 7590 CSEBlocks(CSEBlocks) {} 7591 7592 /// Adds a mask, inverting it before applying. 7593 void addInversedMask(ArrayRef<unsigned> SubMask) { 7594 if (SubMask.empty()) 7595 return; 7596 SmallVector<int, 4> NewMask; 7597 inversePermutation(SubMask, NewMask); 7598 addMask(NewMask); 7599 } 7600 7601 /// Functions adds masks, merging them into single one. 7602 void addMask(ArrayRef<unsigned> SubMask) { 7603 SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end()); 7604 addMask(NewMask); 7605 } 7606 7607 void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); } 7608 7609 Value *finalize(Value *V) { 7610 IsFinalized = true; 7611 unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements(); 7612 if (VF == ValueVF && Mask.empty()) 7613 return V; 7614 SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem); 7615 std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0); 7616 addMask(NormalizedMask); 7617 7618 if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask)) 7619 return V; 7620 Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle"); 7621 if (auto *I = dyn_cast<Instruction>(Vec)) { 7622 GatherShuffleSeq.insert(I); 7623 CSEBlocks.insert(I->getParent()); 7624 } 7625 return Vec; 7626 } 7627 7628 ~ShuffleInstructionBuilder() { 7629 assert((IsFinalized || Mask.empty()) && 7630 "Shuffle construction must be finalized."); 7631 } 7632 }; 7633 } // namespace 7634 7635 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { 7636 const unsigned VF = VL.size(); 7637 InstructionsState S = getSameOpcode(VL); 7638 // Special processing for GEPs bundle, which may include non-gep values. 7639 if (!S.getOpcode() && VL.front()->getType()->isPointerTy()) { 7640 const auto *It = 7641 find_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }); 7642 if (It != VL.end()) 7643 S = getSameOpcode(*It); 7644 } 7645 if (S.getOpcode()) { 7646 if (TreeEntry *E = getTreeEntry(S.OpValue)) 7647 if (E->isSame(VL)) { 7648 Value *V = vectorizeTree(E); 7649 if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) { 7650 if (!E->ReuseShuffleIndices.empty()) { 7651 // Reshuffle to get only unique values. 7652 // If some of the scalars are duplicated in the vectorization tree 7653 // entry, we do not vectorize them but instead generate a mask for 7654 // the reuses. But if there are several users of the same entry, 7655 // they may have different vectorization factors. This is especially 7656 // important for PHI nodes. In this case, we need to adapt the 7657 // resulting instruction for the user vectorization factor and have 7658 // to reshuffle it again to take only unique elements of the vector. 7659 // Without this code the function incorrectly returns reduced vector 7660 // instruction with the same elements, not with the unique ones. 7661 7662 // block: 7663 // %phi = phi <2 x > { .., %entry} {%shuffle, %block} 7664 // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0> 7665 // ... (use %2) 7666 // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0} 7667 // br %block 7668 SmallVector<int> UniqueIdxs(VF, UndefMaskElem); 7669 SmallSet<int, 4> UsedIdxs; 7670 int Pos = 0; 7671 int Sz = VL.size(); 7672 for (int Idx : E->ReuseShuffleIndices) { 7673 if (Idx != Sz && Idx != UndefMaskElem && 7674 UsedIdxs.insert(Idx).second) 7675 UniqueIdxs[Idx] = Pos; 7676 ++Pos; 7677 } 7678 assert(VF >= UsedIdxs.size() && "Expected vectorization factor " 7679 "less than original vector size."); 7680 UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem); 7681 V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle"); 7682 } else { 7683 assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() && 7684 "Expected vectorization factor less " 7685 "than original vector size."); 7686 SmallVector<int> UniformMask(VF, 0); 7687 std::iota(UniformMask.begin(), UniformMask.end(), 0); 7688 V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle"); 7689 } 7690 if (auto *I = dyn_cast<Instruction>(V)) { 7691 GatherShuffleSeq.insert(I); 7692 CSEBlocks.insert(I->getParent()); 7693 } 7694 } 7695 return V; 7696 } 7697 } 7698 7699 // Can't vectorize this, so simply build a new vector with each lane 7700 // corresponding to the requested value. 7701 return createBuildVector(VL); 7702 } 7703 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) { 7704 unsigned VF = VL.size(); 7705 // Exploit possible reuse of values across lanes. 7706 SmallVector<int> ReuseShuffleIndicies; 7707 SmallVector<Value *> UniqueValues; 7708 if (VL.size() > 2) { 7709 DenseMap<Value *, unsigned> UniquePositions; 7710 unsigned NumValues = 7711 std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) { 7712 return !isa<UndefValue>(V); 7713 }).base()); 7714 VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues)); 7715 int UniqueVals = 0; 7716 for (Value *V : VL.drop_back(VL.size() - VF)) { 7717 if (isa<UndefValue>(V)) { 7718 ReuseShuffleIndicies.emplace_back(UndefMaskElem); 7719 continue; 7720 } 7721 if (isConstant(V)) { 7722 ReuseShuffleIndicies.emplace_back(UniqueValues.size()); 7723 UniqueValues.emplace_back(V); 7724 continue; 7725 } 7726 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 7727 ReuseShuffleIndicies.emplace_back(Res.first->second); 7728 if (Res.second) { 7729 UniqueValues.emplace_back(V); 7730 ++UniqueVals; 7731 } 7732 } 7733 if (UniqueVals == 1 && UniqueValues.size() == 1) { 7734 // Emit pure splat vector. 7735 ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(), 7736 UndefMaskElem); 7737 } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) { 7738 if (UniqueValues.empty()) { 7739 assert(all_of(VL, UndefValue::classof) && "Expected list of undefs."); 7740 NumValues = VF; 7741 } 7742 ReuseShuffleIndicies.clear(); 7743 UniqueValues.clear(); 7744 UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues)); 7745 } 7746 UniqueValues.append(VF - UniqueValues.size(), 7747 PoisonValue::get(VL[0]->getType())); 7748 VL = UniqueValues; 7749 } 7750 7751 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 7752 CSEBlocks); 7753 Value *Vec = gather(VL); 7754 if (!ReuseShuffleIndicies.empty()) { 7755 ShuffleBuilder.addMask(ReuseShuffleIndicies); 7756 Vec = ShuffleBuilder.finalize(Vec); 7757 } 7758 return Vec; 7759 } 7760 7761 Value *BoUpSLP::vectorizeTree(TreeEntry *E) { 7762 IRBuilder<>::InsertPointGuard Guard(Builder); 7763 7764 if (E->VectorizedValue) { 7765 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"); 7766 return E->VectorizedValue; 7767 } 7768 7769 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 7770 unsigned VF = E->getVectorFactor(); 7771 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 7772 CSEBlocks); 7773 if (E->State == TreeEntry::NeedToGather) { 7774 if (E->getMainOp()) 7775 setInsertPointAfterBundle(E); 7776 Value *Vec; 7777 SmallVector<int> Mask; 7778 SmallVector<const TreeEntry *> Entries; 7779 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 7780 isGatherShuffledEntry(E, Mask, Entries); 7781 if (Shuffle) { 7782 assert((Entries.size() == 1 || Entries.size() == 2) && 7783 "Expected shuffle of 1 or 2 entries."); 7784 Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue, 7785 Entries.back()->VectorizedValue, Mask); 7786 if (auto *I = dyn_cast<Instruction>(Vec)) { 7787 GatherShuffleSeq.insert(I); 7788 CSEBlocks.insert(I->getParent()); 7789 } 7790 } else { 7791 Vec = gather(E->Scalars); 7792 } 7793 if (NeedToShuffleReuses) { 7794 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7795 Vec = ShuffleBuilder.finalize(Vec); 7796 } 7797 E->VectorizedValue = Vec; 7798 return Vec; 7799 } 7800 7801 assert((E->State == TreeEntry::Vectorize || 7802 E->State == TreeEntry::ScatterVectorize) && 7803 "Unhandled state"); 7804 unsigned ShuffleOrOp = 7805 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 7806 Instruction *VL0 = E->getMainOp(); 7807 Type *ScalarTy = VL0->getType(); 7808 if (auto *Store = dyn_cast<StoreInst>(VL0)) 7809 ScalarTy = Store->getValueOperand()->getType(); 7810 else if (auto *IE = dyn_cast<InsertElementInst>(VL0)) 7811 ScalarTy = IE->getOperand(1)->getType(); 7812 auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size()); 7813 switch (ShuffleOrOp) { 7814 case Instruction::PHI: { 7815 assert( 7816 (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) && 7817 "PHI reordering is free."); 7818 auto *PH = cast<PHINode>(VL0); 7819 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI()); 7820 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 7821 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); 7822 Value *V = NewPhi; 7823 7824 // Adjust insertion point once all PHI's have been generated. 7825 Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt()); 7826 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 7827 7828 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7829 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7830 V = ShuffleBuilder.finalize(V); 7831 7832 E->VectorizedValue = V; 7833 7834 // PHINodes may have multiple entries from the same block. We want to 7835 // visit every block once. 7836 SmallPtrSet<BasicBlock*, 4> VisitedBBs; 7837 7838 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 7839 ValueList Operands; 7840 BasicBlock *IBB = PH->getIncomingBlock(i); 7841 7842 if (!VisitedBBs.insert(IBB).second) { 7843 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB); 7844 continue; 7845 } 7846 7847 Builder.SetInsertPoint(IBB->getTerminator()); 7848 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 7849 Value *Vec = vectorizeTree(E->getOperand(i)); 7850 NewPhi->addIncoming(Vec, IBB); 7851 } 7852 7853 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && 7854 "Invalid number of incoming values"); 7855 return V; 7856 } 7857 7858 case Instruction::ExtractElement: { 7859 Value *V = E->getSingleOperand(0); 7860 Builder.SetInsertPoint(VL0); 7861 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7862 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7863 V = ShuffleBuilder.finalize(V); 7864 E->VectorizedValue = V; 7865 return V; 7866 } 7867 case Instruction::ExtractValue: { 7868 auto *LI = cast<LoadInst>(E->getSingleOperand(0)); 7869 Builder.SetInsertPoint(LI); 7870 auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace()); 7871 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy); 7872 LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign()); 7873 Value *NewV = propagateMetadata(V, E->Scalars); 7874 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7875 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7876 NewV = ShuffleBuilder.finalize(NewV); 7877 E->VectorizedValue = NewV; 7878 return NewV; 7879 } 7880 case Instruction::InsertElement: { 7881 assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique"); 7882 Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back())); 7883 Value *V = vectorizeTree(E->getOperand(1)); 7884 7885 // Create InsertVector shuffle if necessary 7886 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 7887 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); 7888 })); 7889 const unsigned NumElts = 7890 cast<FixedVectorType>(FirstInsert->getType())->getNumElements(); 7891 const unsigned NumScalars = E->Scalars.size(); 7892 7893 unsigned Offset = *getInsertIndex(VL0); 7894 assert(Offset < NumElts && "Failed to find vector index offset"); 7895 7896 // Create shuffle to resize vector 7897 SmallVector<int> Mask; 7898 if (!E->ReorderIndices.empty()) { 7899 inversePermutation(E->ReorderIndices, Mask); 7900 Mask.append(NumElts - NumScalars, UndefMaskElem); 7901 } else { 7902 Mask.assign(NumElts, UndefMaskElem); 7903 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 7904 } 7905 // Create InsertVector shuffle if necessary 7906 bool IsIdentity = true; 7907 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 7908 Mask.swap(PrevMask); 7909 for (unsigned I = 0; I < NumScalars; ++I) { 7910 Value *Scalar = E->Scalars[PrevMask[I]]; 7911 unsigned InsertIdx = *getInsertIndex(Scalar); 7912 IsIdentity &= InsertIdx - Offset == I; 7913 Mask[InsertIdx - Offset] = I; 7914 } 7915 if (!IsIdentity || NumElts != NumScalars) { 7916 V = Builder.CreateShuffleVector(V, Mask); 7917 if (auto *I = dyn_cast<Instruction>(V)) { 7918 GatherShuffleSeq.insert(I); 7919 CSEBlocks.insert(I->getParent()); 7920 } 7921 } 7922 7923 if ((!IsIdentity || Offset != 0 || 7924 !isUndefVector(FirstInsert->getOperand(0))) && 7925 NumElts != NumScalars) { 7926 SmallVector<int> InsertMask(NumElts); 7927 std::iota(InsertMask.begin(), InsertMask.end(), 0); 7928 for (unsigned I = 0; I < NumElts; I++) { 7929 if (Mask[I] != UndefMaskElem) 7930 InsertMask[Offset + I] = NumElts + I; 7931 } 7932 7933 V = Builder.CreateShuffleVector( 7934 FirstInsert->getOperand(0), V, InsertMask, 7935 cast<Instruction>(E->Scalars.back())->getName()); 7936 if (auto *I = dyn_cast<Instruction>(V)) { 7937 GatherShuffleSeq.insert(I); 7938 CSEBlocks.insert(I->getParent()); 7939 } 7940 } 7941 7942 ++NumVectorInstructions; 7943 E->VectorizedValue = V; 7944 return V; 7945 } 7946 case Instruction::ZExt: 7947 case Instruction::SExt: 7948 case Instruction::FPToUI: 7949 case Instruction::FPToSI: 7950 case Instruction::FPExt: 7951 case Instruction::PtrToInt: 7952 case Instruction::IntToPtr: 7953 case Instruction::SIToFP: 7954 case Instruction::UIToFP: 7955 case Instruction::Trunc: 7956 case Instruction::FPTrunc: 7957 case Instruction::BitCast: { 7958 setInsertPointAfterBundle(E); 7959 7960 Value *InVec = vectorizeTree(E->getOperand(0)); 7961 7962 if (E->VectorizedValue) { 7963 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7964 return E->VectorizedValue; 7965 } 7966 7967 auto *CI = cast<CastInst>(VL0); 7968 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); 7969 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7970 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7971 V = ShuffleBuilder.finalize(V); 7972 7973 E->VectorizedValue = V; 7974 ++NumVectorInstructions; 7975 return V; 7976 } 7977 case Instruction::FCmp: 7978 case Instruction::ICmp: { 7979 setInsertPointAfterBundle(E); 7980 7981 Value *L = vectorizeTree(E->getOperand(0)); 7982 Value *R = vectorizeTree(E->getOperand(1)); 7983 7984 if (E->VectorizedValue) { 7985 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7986 return E->VectorizedValue; 7987 } 7988 7989 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 7990 Value *V = Builder.CreateCmp(P0, L, R); 7991 propagateIRFlags(V, E->Scalars, VL0); 7992 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7993 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7994 V = ShuffleBuilder.finalize(V); 7995 7996 E->VectorizedValue = V; 7997 ++NumVectorInstructions; 7998 return V; 7999 } 8000 case Instruction::Select: { 8001 setInsertPointAfterBundle(E); 8002 8003 Value *Cond = vectorizeTree(E->getOperand(0)); 8004 Value *True = vectorizeTree(E->getOperand(1)); 8005 Value *False = vectorizeTree(E->getOperand(2)); 8006 8007 if (E->VectorizedValue) { 8008 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 8009 return E->VectorizedValue; 8010 } 8011 8012 Value *V = Builder.CreateSelect(Cond, True, False); 8013 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8014 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8015 V = ShuffleBuilder.finalize(V); 8016 8017 E->VectorizedValue = V; 8018 ++NumVectorInstructions; 8019 return V; 8020 } 8021 case Instruction::FNeg: { 8022 setInsertPointAfterBundle(E); 8023 8024 Value *Op = vectorizeTree(E->getOperand(0)); 8025 8026 if (E->VectorizedValue) { 8027 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 8028 return E->VectorizedValue; 8029 } 8030 8031 Value *V = Builder.CreateUnOp( 8032 static_cast<Instruction::UnaryOps>(E->getOpcode()), Op); 8033 propagateIRFlags(V, E->Scalars, VL0); 8034 if (auto *I = dyn_cast<Instruction>(V)) 8035 V = propagateMetadata(I, E->Scalars); 8036 8037 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8038 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8039 V = ShuffleBuilder.finalize(V); 8040 8041 E->VectorizedValue = V; 8042 ++NumVectorInstructions; 8043 8044 return V; 8045 } 8046 case Instruction::Add: 8047 case Instruction::FAdd: 8048 case Instruction::Sub: 8049 case Instruction::FSub: 8050 case Instruction::Mul: 8051 case Instruction::FMul: 8052 case Instruction::UDiv: 8053 case Instruction::SDiv: 8054 case Instruction::FDiv: 8055 case Instruction::URem: 8056 case Instruction::SRem: 8057 case Instruction::FRem: 8058 case Instruction::Shl: 8059 case Instruction::LShr: 8060 case Instruction::AShr: 8061 case Instruction::And: 8062 case Instruction::Or: 8063 case Instruction::Xor: { 8064 setInsertPointAfterBundle(E); 8065 8066 Value *LHS = vectorizeTree(E->getOperand(0)); 8067 Value *RHS = vectorizeTree(E->getOperand(1)); 8068 8069 if (E->VectorizedValue) { 8070 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 8071 return E->VectorizedValue; 8072 } 8073 8074 Value *V = Builder.CreateBinOp( 8075 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, 8076 RHS); 8077 propagateIRFlags(V, E->Scalars, VL0); 8078 if (auto *I = dyn_cast<Instruction>(V)) 8079 V = propagateMetadata(I, E->Scalars); 8080 8081 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8082 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8083 V = ShuffleBuilder.finalize(V); 8084 8085 E->VectorizedValue = V; 8086 ++NumVectorInstructions; 8087 8088 return V; 8089 } 8090 case Instruction::Load: { 8091 // Loads are inserted at the head of the tree because we don't want to 8092 // sink them all the way down past store instructions. 8093 setInsertPointAfterBundle(E); 8094 8095 LoadInst *LI = cast<LoadInst>(VL0); 8096 Instruction *NewLI; 8097 unsigned AS = LI->getPointerAddressSpace(); 8098 Value *PO = LI->getPointerOperand(); 8099 if (E->State == TreeEntry::Vectorize) { 8100 Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS)); 8101 NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign()); 8102 8103 // The pointer operand uses an in-tree scalar so we add the new BitCast 8104 // or LoadInst to ExternalUses list to make sure that an extract will 8105 // be generated in the future. 8106 if (TreeEntry *Entry = getTreeEntry(PO)) { 8107 // Find which lane we need to extract. 8108 unsigned FoundLane = Entry->findLaneForValue(PO); 8109 ExternalUses.emplace_back( 8110 PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane); 8111 } 8112 } else { 8113 assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state"); 8114 Value *VecPtr = vectorizeTree(E->getOperand(0)); 8115 // Use the minimum alignment of the gathered loads. 8116 Align CommonAlignment = LI->getAlign(); 8117 for (Value *V : E->Scalars) 8118 CommonAlignment = 8119 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 8120 NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment); 8121 } 8122 Value *V = propagateMetadata(NewLI, E->Scalars); 8123 8124 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8125 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8126 V = ShuffleBuilder.finalize(V); 8127 E->VectorizedValue = V; 8128 ++NumVectorInstructions; 8129 return V; 8130 } 8131 case Instruction::Store: { 8132 auto *SI = cast<StoreInst>(VL0); 8133 unsigned AS = SI->getPointerAddressSpace(); 8134 8135 setInsertPointAfterBundle(E); 8136 8137 Value *VecValue = vectorizeTree(E->getOperand(0)); 8138 ShuffleBuilder.addMask(E->ReorderIndices); 8139 VecValue = ShuffleBuilder.finalize(VecValue); 8140 8141 Value *ScalarPtr = SI->getPointerOperand(); 8142 Value *VecPtr = Builder.CreateBitCast( 8143 ScalarPtr, VecValue->getType()->getPointerTo(AS)); 8144 StoreInst *ST = 8145 Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign()); 8146 8147 // The pointer operand uses an in-tree scalar, so add the new BitCast or 8148 // StoreInst to ExternalUses to make sure that an extract will be 8149 // generated in the future. 8150 if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) { 8151 // Find which lane we need to extract. 8152 unsigned FoundLane = Entry->findLaneForValue(ScalarPtr); 8153 ExternalUses.push_back(ExternalUser( 8154 ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST, 8155 FoundLane)); 8156 } 8157 8158 Value *V = propagateMetadata(ST, E->Scalars); 8159 8160 E->VectorizedValue = V; 8161 ++NumVectorInstructions; 8162 return V; 8163 } 8164 case Instruction::GetElementPtr: { 8165 auto *GEP0 = cast<GetElementPtrInst>(VL0); 8166 setInsertPointAfterBundle(E); 8167 8168 Value *Op0 = vectorizeTree(E->getOperand(0)); 8169 8170 SmallVector<Value *> OpVecs; 8171 for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) { 8172 Value *OpVec = vectorizeTree(E->getOperand(J)); 8173 OpVecs.push_back(OpVec); 8174 } 8175 8176 Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs); 8177 if (Instruction *I = dyn_cast<GetElementPtrInst>(V)) { 8178 SmallVector<Value *> GEPs; 8179 for (Value *V : E->Scalars) { 8180 if (isa<GetElementPtrInst>(V)) 8181 GEPs.push_back(V); 8182 } 8183 V = propagateMetadata(I, GEPs); 8184 } 8185 8186 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8187 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8188 V = ShuffleBuilder.finalize(V); 8189 8190 E->VectorizedValue = V; 8191 ++NumVectorInstructions; 8192 8193 return V; 8194 } 8195 case Instruction::Call: { 8196 CallInst *CI = cast<CallInst>(VL0); 8197 setInsertPointAfterBundle(E); 8198 8199 Intrinsic::ID IID = Intrinsic::not_intrinsic; 8200 if (Function *FI = CI->getCalledFunction()) 8201 IID = FI->getIntrinsicID(); 8202 8203 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 8204 8205 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 8206 bool UseIntrinsic = ID != Intrinsic::not_intrinsic && 8207 VecCallCosts.first <= VecCallCosts.second; 8208 8209 Value *ScalarArg = nullptr; 8210 std::vector<Value *> OpVecs; 8211 SmallVector<Type *, 2> TysForDecl = 8212 {FixedVectorType::get(CI->getType(), E->Scalars.size())}; 8213 for (int j = 0, e = CI->arg_size(); j < e; ++j) { 8214 ValueList OpVL; 8215 // Some intrinsics have scalar arguments. This argument should not be 8216 // vectorized. 8217 if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) { 8218 CallInst *CEI = cast<CallInst>(VL0); 8219 ScalarArg = CEI->getArgOperand(j); 8220 OpVecs.push_back(CEI->getArgOperand(j)); 8221 if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j)) 8222 TysForDecl.push_back(ScalarArg->getType()); 8223 continue; 8224 } 8225 8226 Value *OpVec = vectorizeTree(E->getOperand(j)); 8227 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n"); 8228 OpVecs.push_back(OpVec); 8229 if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j)) 8230 TysForDecl.push_back(OpVec->getType()); 8231 } 8232 8233 Function *CF; 8234 if (!UseIntrinsic) { 8235 VFShape Shape = 8236 VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 8237 VecTy->getNumElements())), 8238 false /*HasGlobalPred*/); 8239 CF = VFDatabase(*CI).getVectorizedFunction(Shape); 8240 } else { 8241 CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl); 8242 } 8243 8244 SmallVector<OperandBundleDef, 1> OpBundles; 8245 CI->getOperandBundlesAsDefs(OpBundles); 8246 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles); 8247 8248 // The scalar argument uses an in-tree scalar so we add the new vectorized 8249 // call to ExternalUses list to make sure that an extract will be 8250 // generated in the future. 8251 if (ScalarArg) { 8252 if (TreeEntry *Entry = getTreeEntry(ScalarArg)) { 8253 // Find which lane we need to extract. 8254 unsigned FoundLane = Entry->findLaneForValue(ScalarArg); 8255 ExternalUses.push_back( 8256 ExternalUser(ScalarArg, cast<User>(V), FoundLane)); 8257 } 8258 } 8259 8260 propagateIRFlags(V, E->Scalars, VL0); 8261 ShuffleBuilder.addInversedMask(E->ReorderIndices); 8262 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 8263 V = ShuffleBuilder.finalize(V); 8264 8265 E->VectorizedValue = V; 8266 ++NumVectorInstructions; 8267 return V; 8268 } 8269 case Instruction::ShuffleVector: { 8270 assert(E->isAltShuffle() && 8271 ((Instruction::isBinaryOp(E->getOpcode()) && 8272 Instruction::isBinaryOp(E->getAltOpcode())) || 8273 (Instruction::isCast(E->getOpcode()) && 8274 Instruction::isCast(E->getAltOpcode())) || 8275 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 8276 "Invalid Shuffle Vector Operand"); 8277 8278 Value *LHS = nullptr, *RHS = nullptr; 8279 if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) { 8280 setInsertPointAfterBundle(E); 8281 LHS = vectorizeTree(E->getOperand(0)); 8282 RHS = vectorizeTree(E->getOperand(1)); 8283 } else { 8284 setInsertPointAfterBundle(E); 8285 LHS = vectorizeTree(E->getOperand(0)); 8286 } 8287 8288 if (E->VectorizedValue) { 8289 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 8290 return E->VectorizedValue; 8291 } 8292 8293 Value *V0, *V1; 8294 if (Instruction::isBinaryOp(E->getOpcode())) { 8295 V0 = Builder.CreateBinOp( 8296 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS); 8297 V1 = Builder.CreateBinOp( 8298 static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS); 8299 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 8300 V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS); 8301 auto *AltCI = cast<CmpInst>(E->getAltOp()); 8302 CmpInst::Predicate AltPred = AltCI->getPredicate(); 8303 V1 = Builder.CreateCmp(AltPred, LHS, RHS); 8304 } else { 8305 V0 = Builder.CreateCast( 8306 static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy); 8307 V1 = Builder.CreateCast( 8308 static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy); 8309 } 8310 // Add V0 and V1 to later analysis to try to find and remove matching 8311 // instruction, if any. 8312 for (Value *V : {V0, V1}) { 8313 if (auto *I = dyn_cast<Instruction>(V)) { 8314 GatherShuffleSeq.insert(I); 8315 CSEBlocks.insert(I->getParent()); 8316 } 8317 } 8318 8319 // Create shuffle to take alternate operations from the vector. 8320 // Also, gather up main and alt scalar ops to propagate IR flags to 8321 // each vector operation. 8322 ValueList OpScalars, AltScalars; 8323 SmallVector<int> Mask; 8324 buildShuffleEntryMask( 8325 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 8326 [E](Instruction *I) { 8327 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 8328 return isAlternateInstruction(I, E->getMainOp(), E->getAltOp()); 8329 }, 8330 Mask, &OpScalars, &AltScalars); 8331 8332 propagateIRFlags(V0, OpScalars); 8333 propagateIRFlags(V1, AltScalars); 8334 8335 Value *V = Builder.CreateShuffleVector(V0, V1, Mask); 8336 if (auto *I = dyn_cast<Instruction>(V)) { 8337 V = propagateMetadata(I, E->Scalars); 8338 GatherShuffleSeq.insert(I); 8339 CSEBlocks.insert(I->getParent()); 8340 } 8341 V = ShuffleBuilder.finalize(V); 8342 8343 E->VectorizedValue = V; 8344 ++NumVectorInstructions; 8345 8346 return V; 8347 } 8348 default: 8349 llvm_unreachable("unknown inst"); 8350 } 8351 return nullptr; 8352 } 8353 8354 Value *BoUpSLP::vectorizeTree() { 8355 ExtraValueToDebugLocsMap ExternallyUsedValues; 8356 return vectorizeTree(ExternallyUsedValues); 8357 } 8358 8359 namespace { 8360 /// Data type for handling buildvector sequences with the reused scalars from 8361 /// other tree entries. 8362 struct ShuffledInsertData { 8363 /// List of insertelements to be replaced by shuffles. 8364 SmallVector<InsertElementInst *> InsertElements; 8365 /// The parent vectors and shuffle mask for the given list of inserts. 8366 MapVector<Value *, SmallVector<int>> ValueMasks; 8367 }; 8368 } // namespace 8369 8370 Value * 8371 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) { 8372 // All blocks must be scheduled before any instructions are inserted. 8373 for (auto &BSIter : BlocksSchedules) { 8374 scheduleBlock(BSIter.second.get()); 8375 } 8376 8377 Builder.SetInsertPoint(&F->getEntryBlock().front()); 8378 auto *VectorRoot = vectorizeTree(VectorizableTree[0].get()); 8379 8380 // If the vectorized tree can be rewritten in a smaller type, we truncate the 8381 // vectorized root. InstCombine will then rewrite the entire expression. We 8382 // sign extend the extracted values below. 8383 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 8384 if (MinBWs.count(ScalarRoot)) { 8385 if (auto *I = dyn_cast<Instruction>(VectorRoot)) { 8386 // If current instr is a phi and not the last phi, insert it after the 8387 // last phi node. 8388 if (isa<PHINode>(I)) 8389 Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt()); 8390 else 8391 Builder.SetInsertPoint(&*++BasicBlock::iterator(I)); 8392 } 8393 auto BundleWidth = VectorizableTree[0]->Scalars.size(); 8394 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 8395 auto *VecTy = FixedVectorType::get(MinTy, BundleWidth); 8396 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy); 8397 VectorizableTree[0]->VectorizedValue = Trunc; 8398 } 8399 8400 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() 8401 << " values .\n"); 8402 8403 SmallVector<ShuffledInsertData> ShuffledInserts; 8404 // Maps vector instruction to original insertelement instruction 8405 DenseMap<Value *, InsertElementInst *> VectorToInsertElement; 8406 // Extract all of the elements with the external uses. 8407 for (const auto &ExternalUse : ExternalUses) { 8408 Value *Scalar = ExternalUse.Scalar; 8409 llvm::User *User = ExternalUse.User; 8410 8411 // Skip users that we already RAUW. This happens when one instruction 8412 // has multiple uses of the same value. 8413 if (User && !is_contained(Scalar->users(), User)) 8414 continue; 8415 TreeEntry *E = getTreeEntry(Scalar); 8416 assert(E && "Invalid scalar"); 8417 assert(E->State != TreeEntry::NeedToGather && 8418 "Extracting from a gather list"); 8419 // Non-instruction pointers are not deleted, just skip them. 8420 if (E->getOpcode() == Instruction::GetElementPtr && 8421 !isa<GetElementPtrInst>(Scalar)) 8422 continue; 8423 8424 Value *Vec = E->VectorizedValue; 8425 assert(Vec && "Can't find vectorizable value"); 8426 8427 Value *Lane = Builder.getInt32(ExternalUse.Lane); 8428 auto ExtractAndExtendIfNeeded = [&](Value *Vec) { 8429 if (Scalar->getType() != Vec->getType()) { 8430 Value *Ex; 8431 // "Reuse" the existing extract to improve final codegen. 8432 if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) { 8433 Ex = Builder.CreateExtractElement(ES->getOperand(0), 8434 ES->getOperand(1)); 8435 } else { 8436 Ex = Builder.CreateExtractElement(Vec, Lane); 8437 } 8438 // If necessary, sign-extend or zero-extend ScalarRoot 8439 // to the larger type. 8440 if (!MinBWs.count(ScalarRoot)) 8441 return Ex; 8442 if (MinBWs[ScalarRoot].second) 8443 return Builder.CreateSExt(Ex, Scalar->getType()); 8444 return Builder.CreateZExt(Ex, Scalar->getType()); 8445 } 8446 assert(isa<FixedVectorType>(Scalar->getType()) && 8447 isa<InsertElementInst>(Scalar) && 8448 "In-tree scalar of vector type is not insertelement?"); 8449 auto *IE = cast<InsertElementInst>(Scalar); 8450 VectorToInsertElement.try_emplace(Vec, IE); 8451 return Vec; 8452 }; 8453 // If User == nullptr, the Scalar is used as extra arg. Generate 8454 // ExtractElement instruction and update the record for this scalar in 8455 // ExternallyUsedValues. 8456 if (!User) { 8457 assert(ExternallyUsedValues.count(Scalar) && 8458 "Scalar with nullptr as an external user must be registered in " 8459 "ExternallyUsedValues map"); 8460 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 8461 Builder.SetInsertPoint(VecI->getParent(), 8462 std::next(VecI->getIterator())); 8463 } else { 8464 Builder.SetInsertPoint(&F->getEntryBlock().front()); 8465 } 8466 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 8467 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent()); 8468 auto &NewInstLocs = ExternallyUsedValues[NewInst]; 8469 auto It = ExternallyUsedValues.find(Scalar); 8470 assert(It != ExternallyUsedValues.end() && 8471 "Externally used scalar is not found in ExternallyUsedValues"); 8472 NewInstLocs.append(It->second); 8473 ExternallyUsedValues.erase(Scalar); 8474 // Required to update internally referenced instructions. 8475 Scalar->replaceAllUsesWith(NewInst); 8476 continue; 8477 } 8478 8479 if (auto *VU = dyn_cast<InsertElementInst>(User)) { 8480 // Skip if the scalar is another vector op or Vec is not an instruction. 8481 if (!Scalar->getType()->isVectorTy() && isa<Instruction>(Vec)) { 8482 if (auto *FTy = dyn_cast<FixedVectorType>(User->getType())) { 8483 Optional<unsigned> InsertIdx = getInsertIndex(VU); 8484 if (InsertIdx) { 8485 // Need to use original vector, if the root is truncated. 8486 if (MinBWs.count(Scalar) && 8487 VectorizableTree[0]->VectorizedValue == Vec) 8488 Vec = VectorRoot; 8489 auto *It = 8490 find_if(ShuffledInserts, [VU](const ShuffledInsertData &Data) { 8491 // Checks if 2 insertelements are from the same buildvector. 8492 InsertElementInst *VecInsert = Data.InsertElements.front(); 8493 return areTwoInsertFromSameBuildVector(VU, VecInsert); 8494 }); 8495 unsigned Idx = *InsertIdx; 8496 if (It == ShuffledInserts.end()) { 8497 (void)ShuffledInserts.emplace_back(); 8498 It = std::next(ShuffledInserts.begin(), 8499 ShuffledInserts.size() - 1); 8500 SmallVectorImpl<int> &Mask = It->ValueMasks[Vec]; 8501 if (Mask.empty()) 8502 Mask.assign(FTy->getNumElements(), UndefMaskElem); 8503 // Find the insertvector, vectorized in tree, if any. 8504 Value *Base = VU; 8505 while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) { 8506 if (IEBase != User && 8507 (!IEBase->hasOneUse() || 8508 getInsertIndex(IEBase).value_or(Idx) == Idx)) 8509 break; 8510 // Build the mask for the vectorized insertelement instructions. 8511 if (const TreeEntry *E = getTreeEntry(IEBase)) { 8512 do { 8513 IEBase = cast<InsertElementInst>(Base); 8514 int IEIdx = *getInsertIndex(IEBase); 8515 assert(Mask[Idx] == UndefMaskElem && 8516 "InsertElementInstruction used already."); 8517 Mask[IEIdx] = IEIdx; 8518 Base = IEBase->getOperand(0); 8519 } while (E == getTreeEntry(Base)); 8520 break; 8521 } 8522 Base = cast<InsertElementInst>(Base)->getOperand(0); 8523 // After the vectorization the def-use chain has changed, need 8524 // to look through original insertelement instructions, if they 8525 // get replaced by vector instructions. 8526 auto It = VectorToInsertElement.find(Base); 8527 if (It != VectorToInsertElement.end()) 8528 Base = It->second; 8529 } 8530 } 8531 SmallVectorImpl<int> &Mask = It->ValueMasks[Vec]; 8532 if (Mask.empty()) 8533 Mask.assign(FTy->getNumElements(), UndefMaskElem); 8534 Mask[Idx] = ExternalUse.Lane; 8535 It->InsertElements.push_back(cast<InsertElementInst>(User)); 8536 continue; 8537 } 8538 } 8539 } 8540 } 8541 8542 // Generate extracts for out-of-tree users. 8543 // Find the insertion point for the extractelement lane. 8544 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 8545 if (PHINode *PH = dyn_cast<PHINode>(User)) { 8546 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { 8547 if (PH->getIncomingValue(i) == Scalar) { 8548 Instruction *IncomingTerminator = 8549 PH->getIncomingBlock(i)->getTerminator(); 8550 if (isa<CatchSwitchInst>(IncomingTerminator)) { 8551 Builder.SetInsertPoint(VecI->getParent(), 8552 std::next(VecI->getIterator())); 8553 } else { 8554 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator()); 8555 } 8556 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 8557 CSEBlocks.insert(PH->getIncomingBlock(i)); 8558 PH->setOperand(i, NewInst); 8559 } 8560 } 8561 } else { 8562 Builder.SetInsertPoint(cast<Instruction>(User)); 8563 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 8564 CSEBlocks.insert(cast<Instruction>(User)->getParent()); 8565 User->replaceUsesOfWith(Scalar, NewInst); 8566 } 8567 } else { 8568 Builder.SetInsertPoint(&F->getEntryBlock().front()); 8569 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 8570 CSEBlocks.insert(&F->getEntryBlock()); 8571 User->replaceUsesOfWith(Scalar, NewInst); 8572 } 8573 8574 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n"); 8575 } 8576 8577 // Checks if the mask is an identity mask. 8578 auto &&IsIdentityMask = [](ArrayRef<int> Mask, FixedVectorType *VecTy) { 8579 int Limit = Mask.size(); 8580 return VecTy->getNumElements() == Mask.size() && 8581 all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) && 8582 ShuffleVectorInst::isIdentityMask(Mask); 8583 }; 8584 // Tries to combine 2 different masks into single one. 8585 auto &&CombineMasks = [](SmallVectorImpl<int> &Mask, ArrayRef<int> ExtMask) { 8586 SmallVector<int> NewMask(ExtMask.size(), UndefMaskElem); 8587 for (int I = 0, Sz = ExtMask.size(); I < Sz; ++I) { 8588 if (ExtMask[I] == UndefMaskElem) 8589 continue; 8590 NewMask[I] = Mask[ExtMask[I]]; 8591 } 8592 Mask.swap(NewMask); 8593 }; 8594 // Peek through shuffles, trying to simplify the final shuffle code. 8595 auto &&PeekThroughShuffles = 8596 [&IsIdentityMask, &CombineMasks](Value *&V, SmallVectorImpl<int> &Mask, 8597 bool CheckForLengthChange = false) { 8598 while (auto *SV = dyn_cast<ShuffleVectorInst>(V)) { 8599 // Exit if not a fixed vector type or changing size shuffle. 8600 if (!isa<FixedVectorType>(SV->getType()) || 8601 (CheckForLengthChange && SV->changesLength())) 8602 break; 8603 // Exit if the identity or broadcast mask is found. 8604 if (IsIdentityMask(Mask, cast<FixedVectorType>(SV->getType())) || 8605 SV->isZeroEltSplat()) 8606 break; 8607 bool IsOp1Undef = isUndefVector(SV->getOperand(0)); 8608 bool IsOp2Undef = isUndefVector(SV->getOperand(1)); 8609 if (!IsOp1Undef && !IsOp2Undef) 8610 break; 8611 SmallVector<int> ShuffleMask(SV->getShuffleMask().begin(), 8612 SV->getShuffleMask().end()); 8613 CombineMasks(ShuffleMask, Mask); 8614 Mask.swap(ShuffleMask); 8615 if (IsOp2Undef) 8616 V = SV->getOperand(0); 8617 else 8618 V = SV->getOperand(1); 8619 } 8620 }; 8621 // Smart shuffle instruction emission, walks through shuffles trees and 8622 // tries to find the best matching vector for the actual shuffle 8623 // instruction. 8624 auto &&CreateShuffle = [this, &IsIdentityMask, &PeekThroughShuffles, 8625 &CombineMasks](Value *V1, Value *V2, 8626 ArrayRef<int> Mask) -> Value * { 8627 assert(V1 && "Expected at least one vector value."); 8628 if (V2 && !isUndefVector(V2)) { 8629 // Peek through shuffles. 8630 Value *Op1 = V1; 8631 Value *Op2 = V2; 8632 int VF = 8633 cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue(); 8634 SmallVector<int> CombinedMask1(Mask.size(), UndefMaskElem); 8635 SmallVector<int> CombinedMask2(Mask.size(), UndefMaskElem); 8636 for (int I = 0, E = Mask.size(); I < E; ++I) { 8637 if (Mask[I] < VF) 8638 CombinedMask1[I] = Mask[I]; 8639 else 8640 CombinedMask2[I] = Mask[I] - VF; 8641 } 8642 Value *PrevOp1; 8643 Value *PrevOp2; 8644 do { 8645 PrevOp1 = Op1; 8646 PrevOp2 = Op2; 8647 PeekThroughShuffles(Op1, CombinedMask1, /*CheckForLengthChange=*/true); 8648 PeekThroughShuffles(Op2, CombinedMask2, /*CheckForLengthChange=*/true); 8649 // Check if we have 2 resizing shuffles - need to peek through operands 8650 // again. 8651 if (auto *SV1 = dyn_cast<ShuffleVectorInst>(Op1)) 8652 if (auto *SV2 = dyn_cast<ShuffleVectorInst>(Op2)) 8653 if (SV1->getOperand(0)->getType() == 8654 SV2->getOperand(0)->getType() && 8655 SV1->getOperand(0)->getType() != SV1->getType() && 8656 isUndefVector(SV1->getOperand(1)) && 8657 isUndefVector(SV2->getOperand(1))) { 8658 Op1 = SV1->getOperand(0); 8659 Op2 = SV2->getOperand(0); 8660 SmallVector<int> ShuffleMask1(SV1->getShuffleMask().begin(), 8661 SV1->getShuffleMask().end()); 8662 CombineMasks(ShuffleMask1, CombinedMask1); 8663 CombinedMask1.swap(ShuffleMask1); 8664 SmallVector<int> ShuffleMask2(SV2->getShuffleMask().begin(), 8665 SV2->getShuffleMask().end()); 8666 CombineMasks(ShuffleMask2, CombinedMask2); 8667 CombinedMask2.swap(ShuffleMask2); 8668 } 8669 } while (PrevOp1 != Op1 || PrevOp2 != Op2); 8670 VF = cast<VectorType>(Op1->getType()) 8671 ->getElementCount() 8672 .getKnownMinValue(); 8673 for (int I = 0, E = Mask.size(); I < E; ++I) { 8674 if (CombinedMask2[I] != UndefMaskElem) { 8675 assert(CombinedMask1[I] == UndefMaskElem && 8676 "Expected undefined mask element"); 8677 CombinedMask1[I] = CombinedMask2[I] + (Op1 == Op2 ? 0 : VF); 8678 } 8679 } 8680 Value *Vec = Builder.CreateShuffleVector( 8681 Op1, Op1 == Op2 ? PoisonValue::get(Op1->getType()) : Op2, 8682 CombinedMask1); 8683 if (auto *I = dyn_cast<Instruction>(Vec)) { 8684 GatherShuffleSeq.insert(I); 8685 CSEBlocks.insert(I->getParent()); 8686 } 8687 return Vec; 8688 } 8689 if (isa<PoisonValue>(V1)) 8690 return PoisonValue::get(FixedVectorType::get( 8691 cast<VectorType>(V1->getType())->getElementType(), Mask.size())); 8692 Value *Op = V1; 8693 SmallVector<int> CombinedMask(Mask.begin(), Mask.end()); 8694 PeekThroughShuffles(Op, CombinedMask); 8695 if (!isa<FixedVectorType>(Op->getType()) || 8696 !IsIdentityMask(CombinedMask, cast<FixedVectorType>(Op->getType()))) { 8697 Value *Vec = Builder.CreateShuffleVector(Op, CombinedMask); 8698 if (auto *I = dyn_cast<Instruction>(Vec)) { 8699 GatherShuffleSeq.insert(I); 8700 CSEBlocks.insert(I->getParent()); 8701 } 8702 return Vec; 8703 } 8704 return Op; 8705 }; 8706 8707 auto &&ResizeToVF = [&CreateShuffle](Value *Vec, ArrayRef<int> Mask) { 8708 unsigned VF = Mask.size(); 8709 unsigned VecVF = cast<FixedVectorType>(Vec->getType())->getNumElements(); 8710 if (VF != VecVF) { 8711 if (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); })) { 8712 Vec = CreateShuffle(Vec, nullptr, Mask); 8713 return std::make_pair(Vec, true); 8714 } 8715 SmallVector<int> ResizeMask(VF, UndefMaskElem); 8716 for (unsigned I = 0; I < VF; ++I) { 8717 if (Mask[I] != UndefMaskElem) 8718 ResizeMask[Mask[I]] = Mask[I]; 8719 } 8720 Vec = CreateShuffle(Vec, nullptr, ResizeMask); 8721 } 8722 8723 return std::make_pair(Vec, false); 8724 }; 8725 // Perform shuffling of the vectorize tree entries for better handling of 8726 // external extracts. 8727 for (int I = 0, E = ShuffledInserts.size(); I < E; ++I) { 8728 // Find the first and the last instruction in the list of insertelements. 8729 sort(ShuffledInserts[I].InsertElements, isFirstInsertElement); 8730 InsertElementInst *FirstInsert = ShuffledInserts[I].InsertElements.front(); 8731 InsertElementInst *LastInsert = ShuffledInserts[I].InsertElements.back(); 8732 Builder.SetInsertPoint(LastInsert); 8733 auto Vector = ShuffledInserts[I].ValueMasks.takeVector(); 8734 Value *NewInst = performExtractsShuffleAction<Value>( 8735 makeMutableArrayRef(Vector.data(), Vector.size()), 8736 FirstInsert->getOperand(0), 8737 [](Value *Vec) { 8738 return cast<VectorType>(Vec->getType()) 8739 ->getElementCount() 8740 .getKnownMinValue(); 8741 }, 8742 ResizeToVF, 8743 [FirstInsert, &CreateShuffle](ArrayRef<int> Mask, 8744 ArrayRef<Value *> Vals) { 8745 assert((Vals.size() == 1 || Vals.size() == 2) && 8746 "Expected exactly 1 or 2 input values."); 8747 if (Vals.size() == 1) { 8748 // Do not create shuffle if the mask is a simple identity 8749 // non-resizing mask. 8750 if (Mask.size() != cast<FixedVectorType>(Vals.front()->getType()) 8751 ->getNumElements() || 8752 !ShuffleVectorInst::isIdentityMask(Mask)) 8753 return CreateShuffle(Vals.front(), nullptr, Mask); 8754 return Vals.front(); 8755 } 8756 return CreateShuffle(Vals.front() ? Vals.front() 8757 : FirstInsert->getOperand(0), 8758 Vals.back(), Mask); 8759 }); 8760 auto It = ShuffledInserts[I].InsertElements.rbegin(); 8761 // Rebuild buildvector chain. 8762 InsertElementInst *II = nullptr; 8763 if (It != ShuffledInserts[I].InsertElements.rend()) 8764 II = *It; 8765 SmallVector<Instruction *> Inserts; 8766 while (It != ShuffledInserts[I].InsertElements.rend()) { 8767 assert(II && "Must be an insertelement instruction."); 8768 if (*It == II) 8769 ++It; 8770 else 8771 Inserts.push_back(cast<Instruction>(II)); 8772 II = dyn_cast<InsertElementInst>(II->getOperand(0)); 8773 } 8774 for (Instruction *II : reverse(Inserts)) { 8775 II->replaceUsesOfWith(II->getOperand(0), NewInst); 8776 if (auto *NewI = dyn_cast<Instruction>(NewInst)) 8777 if (II->getParent() == NewI->getParent() && II->comesBefore(NewI)) 8778 II->moveAfter(NewI); 8779 NewInst = II; 8780 } 8781 LastInsert->replaceAllUsesWith(NewInst); 8782 for (InsertElementInst *IE : reverse(ShuffledInserts[I].InsertElements)) { 8783 IE->replaceUsesOfWith(IE->getOperand(1), 8784 PoisonValue::get(IE->getOperand(1)->getType())); 8785 eraseInstruction(IE); 8786 } 8787 CSEBlocks.insert(LastInsert->getParent()); 8788 } 8789 8790 // For each vectorized value: 8791 for (auto &TEPtr : VectorizableTree) { 8792 TreeEntry *Entry = TEPtr.get(); 8793 8794 // No need to handle users of gathered values. 8795 if (Entry->State == TreeEntry::NeedToGather) 8796 continue; 8797 8798 assert(Entry->VectorizedValue && "Can't find vectorizable value"); 8799 8800 // For each lane: 8801 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 8802 Value *Scalar = Entry->Scalars[Lane]; 8803 8804 if (Entry->getOpcode() == Instruction::GetElementPtr && 8805 !isa<GetElementPtrInst>(Scalar)) 8806 continue; 8807 #ifndef NDEBUG 8808 Type *Ty = Scalar->getType(); 8809 if (!Ty->isVoidTy()) { 8810 for (User *U : Scalar->users()) { 8811 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n"); 8812 8813 // It is legal to delete users in the ignorelist. 8814 assert((getTreeEntry(U) || 8815 (UserIgnoreList && UserIgnoreList->contains(U)) || 8816 (isa_and_nonnull<Instruction>(U) && 8817 isDeleted(cast<Instruction>(U)))) && 8818 "Deleting out-of-tree value"); 8819 } 8820 } 8821 #endif 8822 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n"); 8823 eraseInstruction(cast<Instruction>(Scalar)); 8824 } 8825 } 8826 8827 Builder.ClearInsertionPoint(); 8828 InstrElementSize.clear(); 8829 8830 return VectorizableTree[0]->VectorizedValue; 8831 } 8832 8833 void BoUpSLP::optimizeGatherSequence() { 8834 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size() 8835 << " gather sequences instructions.\n"); 8836 // LICM InsertElementInst sequences. 8837 for (Instruction *I : GatherShuffleSeq) { 8838 if (isDeleted(I)) 8839 continue; 8840 8841 // Check if this block is inside a loop. 8842 Loop *L = LI->getLoopFor(I->getParent()); 8843 if (!L) 8844 continue; 8845 8846 // Check if it has a preheader. 8847 BasicBlock *PreHeader = L->getLoopPreheader(); 8848 if (!PreHeader) 8849 continue; 8850 8851 // If the vector or the element that we insert into it are 8852 // instructions that are defined in this basic block then we can't 8853 // hoist this instruction. 8854 if (any_of(I->operands(), [L](Value *V) { 8855 auto *OpI = dyn_cast<Instruction>(V); 8856 return OpI && L->contains(OpI); 8857 })) 8858 continue; 8859 8860 // We can hoist this instruction. Move it to the pre-header. 8861 I->moveBefore(PreHeader->getTerminator()); 8862 } 8863 8864 // Make a list of all reachable blocks in our CSE queue. 8865 SmallVector<const DomTreeNode *, 8> CSEWorkList; 8866 CSEWorkList.reserve(CSEBlocks.size()); 8867 for (BasicBlock *BB : CSEBlocks) 8868 if (DomTreeNode *N = DT->getNode(BB)) { 8869 assert(DT->isReachableFromEntry(N)); 8870 CSEWorkList.push_back(N); 8871 } 8872 8873 // Sort blocks by domination. This ensures we visit a block after all blocks 8874 // dominating it are visited. 8875 llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) { 8876 assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && 8877 "Different nodes should have different DFS numbers"); 8878 return A->getDFSNumIn() < B->getDFSNumIn(); 8879 }); 8880 8881 // Less defined shuffles can be replaced by the more defined copies. 8882 // Between two shuffles one is less defined if it has the same vector operands 8883 // and its mask indeces are the same as in the first one or undefs. E.g. 8884 // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0, 8885 // poison, <0, 0, 0, 0>. 8886 auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2, 8887 SmallVectorImpl<int> &NewMask) { 8888 if (I1->getType() != I2->getType()) 8889 return false; 8890 auto *SI1 = dyn_cast<ShuffleVectorInst>(I1); 8891 auto *SI2 = dyn_cast<ShuffleVectorInst>(I2); 8892 if (!SI1 || !SI2) 8893 return I1->isIdenticalTo(I2); 8894 if (SI1->isIdenticalTo(SI2)) 8895 return true; 8896 for (int I = 0, E = SI1->getNumOperands(); I < E; ++I) 8897 if (SI1->getOperand(I) != SI2->getOperand(I)) 8898 return false; 8899 // Check if the second instruction is more defined than the first one. 8900 NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end()); 8901 ArrayRef<int> SM1 = SI1->getShuffleMask(); 8902 // Count trailing undefs in the mask to check the final number of used 8903 // registers. 8904 unsigned LastUndefsCnt = 0; 8905 for (int I = 0, E = NewMask.size(); I < E; ++I) { 8906 if (SM1[I] == UndefMaskElem) 8907 ++LastUndefsCnt; 8908 else 8909 LastUndefsCnt = 0; 8910 if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem && 8911 NewMask[I] != SM1[I]) 8912 return false; 8913 if (NewMask[I] == UndefMaskElem) 8914 NewMask[I] = SM1[I]; 8915 } 8916 // Check if the last undefs actually change the final number of used vector 8917 // registers. 8918 return SM1.size() - LastUndefsCnt > 1 && 8919 TTI->getNumberOfParts(SI1->getType()) == 8920 TTI->getNumberOfParts( 8921 FixedVectorType::get(SI1->getType()->getElementType(), 8922 SM1.size() - LastUndefsCnt)); 8923 }; 8924 // Perform O(N^2) search over the gather/shuffle sequences and merge identical 8925 // instructions. TODO: We can further optimize this scan if we split the 8926 // instructions into different buckets based on the insert lane. 8927 SmallVector<Instruction *, 16> Visited; 8928 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) { 8929 assert(*I && 8930 (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && 8931 "Worklist not sorted properly!"); 8932 BasicBlock *BB = (*I)->getBlock(); 8933 // For all instructions in blocks containing gather sequences: 8934 for (Instruction &In : llvm::make_early_inc_range(*BB)) { 8935 if (isDeleted(&In)) 8936 continue; 8937 if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) && 8938 !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In)) 8939 continue; 8940 8941 // Check if we can replace this instruction with any of the 8942 // visited instructions. 8943 bool Replaced = false; 8944 for (Instruction *&V : Visited) { 8945 SmallVector<int> NewMask; 8946 if (IsIdenticalOrLessDefined(&In, V, NewMask) && 8947 DT->dominates(V->getParent(), In.getParent())) { 8948 In.replaceAllUsesWith(V); 8949 eraseInstruction(&In); 8950 if (auto *SI = dyn_cast<ShuffleVectorInst>(V)) 8951 if (!NewMask.empty()) 8952 SI->setShuffleMask(NewMask); 8953 Replaced = true; 8954 break; 8955 } 8956 if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) && 8957 GatherShuffleSeq.contains(V) && 8958 IsIdenticalOrLessDefined(V, &In, NewMask) && 8959 DT->dominates(In.getParent(), V->getParent())) { 8960 In.moveAfter(V); 8961 V->replaceAllUsesWith(&In); 8962 eraseInstruction(V); 8963 if (auto *SI = dyn_cast<ShuffleVectorInst>(&In)) 8964 if (!NewMask.empty()) 8965 SI->setShuffleMask(NewMask); 8966 V = &In; 8967 Replaced = true; 8968 break; 8969 } 8970 } 8971 if (!Replaced) { 8972 assert(!is_contained(Visited, &In)); 8973 Visited.push_back(&In); 8974 } 8975 } 8976 } 8977 CSEBlocks.clear(); 8978 GatherShuffleSeq.clear(); 8979 } 8980 8981 BoUpSLP::ScheduleData * 8982 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) { 8983 ScheduleData *Bundle = nullptr; 8984 ScheduleData *PrevInBundle = nullptr; 8985 for (Value *V : VL) { 8986 if (doesNotNeedToBeScheduled(V)) 8987 continue; 8988 ScheduleData *BundleMember = getScheduleData(V); 8989 assert(BundleMember && 8990 "no ScheduleData for bundle member " 8991 "(maybe not in same basic block)"); 8992 assert(BundleMember->isSchedulingEntity() && 8993 "bundle member already part of other bundle"); 8994 if (PrevInBundle) { 8995 PrevInBundle->NextInBundle = BundleMember; 8996 } else { 8997 Bundle = BundleMember; 8998 } 8999 9000 // Group the instructions to a bundle. 9001 BundleMember->FirstInBundle = Bundle; 9002 PrevInBundle = BundleMember; 9003 } 9004 assert(Bundle && "Failed to find schedule bundle"); 9005 return Bundle; 9006 } 9007 9008 // Groups the instructions to a bundle (which is then a single scheduling entity) 9009 // and schedules instructions until the bundle gets ready. 9010 Optional<BoUpSLP::ScheduleData *> 9011 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 9012 const InstructionsState &S) { 9013 // No need to schedule PHIs, insertelement, extractelement and extractvalue 9014 // instructions. 9015 if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) || 9016 doesNotNeedToSchedule(VL)) 9017 return nullptr; 9018 9019 // Initialize the instruction bundle. 9020 Instruction *OldScheduleEnd = ScheduleEnd; 9021 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n"); 9022 9023 auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule, 9024 ScheduleData *Bundle) { 9025 // The scheduling region got new instructions at the lower end (or it is a 9026 // new region for the first bundle). This makes it necessary to 9027 // recalculate all dependencies. 9028 // It is seldom that this needs to be done a second time after adding the 9029 // initial bundle to the region. 9030 if (ScheduleEnd != OldScheduleEnd) { 9031 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) 9032 doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); }); 9033 ReSchedule = true; 9034 } 9035 if (Bundle) { 9036 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle 9037 << " in block " << BB->getName() << "\n"); 9038 calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP); 9039 } 9040 9041 if (ReSchedule) { 9042 resetSchedule(); 9043 initialFillReadyList(ReadyInsts); 9044 } 9045 9046 // Now try to schedule the new bundle or (if no bundle) just calculate 9047 // dependencies. As soon as the bundle is "ready" it means that there are no 9048 // cyclic dependencies and we can schedule it. Note that's important that we 9049 // don't "schedule" the bundle yet (see cancelScheduling). 9050 while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) && 9051 !ReadyInsts.empty()) { 9052 ScheduleData *Picked = ReadyInsts.pop_back_val(); 9053 assert(Picked->isSchedulingEntity() && Picked->isReady() && 9054 "must be ready to schedule"); 9055 schedule(Picked, ReadyInsts); 9056 } 9057 }; 9058 9059 // Make sure that the scheduling region contains all 9060 // instructions of the bundle. 9061 for (Value *V : VL) { 9062 if (doesNotNeedToBeScheduled(V)) 9063 continue; 9064 if (!extendSchedulingRegion(V, S)) { 9065 // If the scheduling region got new instructions at the lower end (or it 9066 // is a new region for the first bundle). This makes it necessary to 9067 // recalculate all dependencies. 9068 // Otherwise the compiler may crash trying to incorrectly calculate 9069 // dependencies and emit instruction in the wrong order at the actual 9070 // scheduling. 9071 TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr); 9072 return None; 9073 } 9074 } 9075 9076 bool ReSchedule = false; 9077 for (Value *V : VL) { 9078 if (doesNotNeedToBeScheduled(V)) 9079 continue; 9080 ScheduleData *BundleMember = getScheduleData(V); 9081 assert(BundleMember && 9082 "no ScheduleData for bundle member (maybe not in same basic block)"); 9083 9084 // Make sure we don't leave the pieces of the bundle in the ready list when 9085 // whole bundle might not be ready. 9086 ReadyInsts.remove(BundleMember); 9087 9088 if (!BundleMember->IsScheduled) 9089 continue; 9090 // A bundle member was scheduled as single instruction before and now 9091 // needs to be scheduled as part of the bundle. We just get rid of the 9092 // existing schedule. 9093 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember 9094 << " was already scheduled\n"); 9095 ReSchedule = true; 9096 } 9097 9098 auto *Bundle = buildBundle(VL); 9099 TryScheduleBundleImpl(ReSchedule, Bundle); 9100 if (!Bundle->isReady()) { 9101 cancelScheduling(VL, S.OpValue); 9102 return None; 9103 } 9104 return Bundle; 9105 } 9106 9107 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL, 9108 Value *OpValue) { 9109 if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) || 9110 doesNotNeedToSchedule(VL)) 9111 return; 9112 9113 if (doesNotNeedToBeScheduled(OpValue)) 9114 OpValue = *find_if_not(VL, doesNotNeedToBeScheduled); 9115 ScheduleData *Bundle = getScheduleData(OpValue); 9116 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n"); 9117 assert(!Bundle->IsScheduled && 9118 "Can't cancel bundle which is already scheduled"); 9119 assert(Bundle->isSchedulingEntity() && 9120 (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) && 9121 "tried to unbundle something which is not a bundle"); 9122 9123 // Remove the bundle from the ready list. 9124 if (Bundle->isReady()) 9125 ReadyInsts.remove(Bundle); 9126 9127 // Un-bundle: make single instructions out of the bundle. 9128 ScheduleData *BundleMember = Bundle; 9129 while (BundleMember) { 9130 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links"); 9131 BundleMember->FirstInBundle = BundleMember; 9132 ScheduleData *Next = BundleMember->NextInBundle; 9133 BundleMember->NextInBundle = nullptr; 9134 BundleMember->TE = nullptr; 9135 if (BundleMember->unscheduledDepsInBundle() == 0) { 9136 ReadyInsts.insert(BundleMember); 9137 } 9138 BundleMember = Next; 9139 } 9140 } 9141 9142 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() { 9143 // Allocate a new ScheduleData for the instruction. 9144 if (ChunkPos >= ChunkSize) { 9145 ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize)); 9146 ChunkPos = 0; 9147 } 9148 return &(ScheduleDataChunks.back()[ChunkPos++]); 9149 } 9150 9151 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V, 9152 const InstructionsState &S) { 9153 if (getScheduleData(V, isOneOf(S, V))) 9154 return true; 9155 Instruction *I = dyn_cast<Instruction>(V); 9156 assert(I && "bundle member must be an instruction"); 9157 assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && 9158 !doesNotNeedToBeScheduled(I) && 9159 "phi nodes/insertelements/extractelements/extractvalues don't need to " 9160 "be scheduled"); 9161 auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool { 9162 ScheduleData *ISD = getScheduleData(I); 9163 if (!ISD) 9164 return false; 9165 assert(isInSchedulingRegion(ISD) && 9166 "ScheduleData not in scheduling region"); 9167 ScheduleData *SD = allocateScheduleDataChunks(); 9168 SD->Inst = I; 9169 SD->init(SchedulingRegionID, S.OpValue); 9170 ExtraScheduleDataMap[I][S.OpValue] = SD; 9171 return true; 9172 }; 9173 if (CheckScheduleForI(I)) 9174 return true; 9175 if (!ScheduleStart) { 9176 // It's the first instruction in the new region. 9177 initScheduleData(I, I->getNextNode(), nullptr, nullptr); 9178 ScheduleStart = I; 9179 ScheduleEnd = I->getNextNode(); 9180 if (isOneOf(S, I) != I) 9181 CheckScheduleForI(I); 9182 assert(ScheduleEnd && "tried to vectorize a terminator?"); 9183 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n"); 9184 return true; 9185 } 9186 // Search up and down at the same time, because we don't know if the new 9187 // instruction is above or below the existing scheduling region. 9188 BasicBlock::reverse_iterator UpIter = 9189 ++ScheduleStart->getIterator().getReverse(); 9190 BasicBlock::reverse_iterator UpperEnd = BB->rend(); 9191 BasicBlock::iterator DownIter = ScheduleEnd->getIterator(); 9192 BasicBlock::iterator LowerEnd = BB->end(); 9193 while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I && 9194 &*DownIter != I) { 9195 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) { 9196 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n"); 9197 return false; 9198 } 9199 9200 ++UpIter; 9201 ++DownIter; 9202 } 9203 if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) { 9204 assert(I->getParent() == ScheduleStart->getParent() && 9205 "Instruction is in wrong basic block."); 9206 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion); 9207 ScheduleStart = I; 9208 if (isOneOf(S, I) != I) 9209 CheckScheduleForI(I); 9210 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I 9211 << "\n"); 9212 return true; 9213 } 9214 assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && 9215 "Expected to reach top of the basic block or instruction down the " 9216 "lower end."); 9217 assert(I->getParent() == ScheduleEnd->getParent() && 9218 "Instruction is in wrong basic block."); 9219 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion, 9220 nullptr); 9221 ScheduleEnd = I->getNextNode(); 9222 if (isOneOf(S, I) != I) 9223 CheckScheduleForI(I); 9224 assert(ScheduleEnd && "tried to vectorize a terminator?"); 9225 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n"); 9226 return true; 9227 } 9228 9229 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI, 9230 Instruction *ToI, 9231 ScheduleData *PrevLoadStore, 9232 ScheduleData *NextLoadStore) { 9233 ScheduleData *CurrentLoadStore = PrevLoadStore; 9234 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) { 9235 // No need to allocate data for non-schedulable instructions. 9236 if (doesNotNeedToBeScheduled(I)) 9237 continue; 9238 ScheduleData *SD = ScheduleDataMap.lookup(I); 9239 if (!SD) { 9240 SD = allocateScheduleDataChunks(); 9241 ScheduleDataMap[I] = SD; 9242 SD->Inst = I; 9243 } 9244 assert(!isInSchedulingRegion(SD) && 9245 "new ScheduleData already in scheduling region"); 9246 SD->init(SchedulingRegionID, I); 9247 9248 if (I->mayReadOrWriteMemory() && 9249 (!isa<IntrinsicInst>(I) || 9250 (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect && 9251 cast<IntrinsicInst>(I)->getIntrinsicID() != 9252 Intrinsic::pseudoprobe))) { 9253 // Update the linked list of memory accessing instructions. 9254 if (CurrentLoadStore) { 9255 CurrentLoadStore->NextLoadStore = SD; 9256 } else { 9257 FirstLoadStoreInRegion = SD; 9258 } 9259 CurrentLoadStore = SD; 9260 } 9261 9262 if (match(I, m_Intrinsic<Intrinsic::stacksave>()) || 9263 match(I, m_Intrinsic<Intrinsic::stackrestore>())) 9264 RegionHasStackSave = true; 9265 } 9266 if (NextLoadStore) { 9267 if (CurrentLoadStore) 9268 CurrentLoadStore->NextLoadStore = NextLoadStore; 9269 } else { 9270 LastLoadStoreInRegion = CurrentLoadStore; 9271 } 9272 } 9273 9274 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD, 9275 bool InsertInReadyList, 9276 BoUpSLP *SLP) { 9277 assert(SD->isSchedulingEntity()); 9278 9279 SmallVector<ScheduleData *, 10> WorkList; 9280 WorkList.push_back(SD); 9281 9282 while (!WorkList.empty()) { 9283 ScheduleData *SD = WorkList.pop_back_val(); 9284 for (ScheduleData *BundleMember = SD; BundleMember; 9285 BundleMember = BundleMember->NextInBundle) { 9286 assert(isInSchedulingRegion(BundleMember)); 9287 if (BundleMember->hasValidDependencies()) 9288 continue; 9289 9290 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember 9291 << "\n"); 9292 BundleMember->Dependencies = 0; 9293 BundleMember->resetUnscheduledDeps(); 9294 9295 // Handle def-use chain dependencies. 9296 if (BundleMember->OpValue != BundleMember->Inst) { 9297 if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) { 9298 BundleMember->Dependencies++; 9299 ScheduleData *DestBundle = UseSD->FirstInBundle; 9300 if (!DestBundle->IsScheduled) 9301 BundleMember->incrementUnscheduledDeps(1); 9302 if (!DestBundle->hasValidDependencies()) 9303 WorkList.push_back(DestBundle); 9304 } 9305 } else { 9306 for (User *U : BundleMember->Inst->users()) { 9307 if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) { 9308 BundleMember->Dependencies++; 9309 ScheduleData *DestBundle = UseSD->FirstInBundle; 9310 if (!DestBundle->IsScheduled) 9311 BundleMember->incrementUnscheduledDeps(1); 9312 if (!DestBundle->hasValidDependencies()) 9313 WorkList.push_back(DestBundle); 9314 } 9315 } 9316 } 9317 9318 auto makeControlDependent = [&](Instruction *I) { 9319 auto *DepDest = getScheduleData(I); 9320 assert(DepDest && "must be in schedule window"); 9321 DepDest->ControlDependencies.push_back(BundleMember); 9322 BundleMember->Dependencies++; 9323 ScheduleData *DestBundle = DepDest->FirstInBundle; 9324 if (!DestBundle->IsScheduled) 9325 BundleMember->incrementUnscheduledDeps(1); 9326 if (!DestBundle->hasValidDependencies()) 9327 WorkList.push_back(DestBundle); 9328 }; 9329 9330 // Any instruction which isn't safe to speculate at the begining of the 9331 // block is control dependend on any early exit or non-willreturn call 9332 // which proceeds it. 9333 if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) { 9334 for (Instruction *I = BundleMember->Inst->getNextNode(); 9335 I != ScheduleEnd; I = I->getNextNode()) { 9336 if (isSafeToSpeculativelyExecute(I, &*BB->begin())) 9337 continue; 9338 9339 // Add the dependency 9340 makeControlDependent(I); 9341 9342 if (!isGuaranteedToTransferExecutionToSuccessor(I)) 9343 // Everything past here must be control dependent on I. 9344 break; 9345 } 9346 } 9347 9348 if (RegionHasStackSave) { 9349 // If we have an inalloc alloca instruction, it needs to be scheduled 9350 // after any preceeding stacksave. We also need to prevent any alloca 9351 // from reordering above a preceeding stackrestore. 9352 if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) || 9353 match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) { 9354 for (Instruction *I = BundleMember->Inst->getNextNode(); 9355 I != ScheduleEnd; I = I->getNextNode()) { 9356 if (match(I, m_Intrinsic<Intrinsic::stacksave>()) || 9357 match(I, m_Intrinsic<Intrinsic::stackrestore>())) 9358 // Any allocas past here must be control dependent on I, and I 9359 // must be memory dependend on BundleMember->Inst. 9360 break; 9361 9362 if (!isa<AllocaInst>(I)) 9363 continue; 9364 9365 // Add the dependency 9366 makeControlDependent(I); 9367 } 9368 } 9369 9370 // In addition to the cases handle just above, we need to prevent 9371 // allocas from moving below a stacksave. The stackrestore case 9372 // is currently thought to be conservatism. 9373 if (isa<AllocaInst>(BundleMember->Inst)) { 9374 for (Instruction *I = BundleMember->Inst->getNextNode(); 9375 I != ScheduleEnd; I = I->getNextNode()) { 9376 if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) && 9377 !match(I, m_Intrinsic<Intrinsic::stackrestore>())) 9378 continue; 9379 9380 // Add the dependency 9381 makeControlDependent(I); 9382 break; 9383 } 9384 } 9385 } 9386 9387 // Handle the memory dependencies (if any). 9388 ScheduleData *DepDest = BundleMember->NextLoadStore; 9389 if (!DepDest) 9390 continue; 9391 Instruction *SrcInst = BundleMember->Inst; 9392 assert(SrcInst->mayReadOrWriteMemory() && 9393 "NextLoadStore list for non memory effecting bundle?"); 9394 MemoryLocation SrcLoc = getLocation(SrcInst); 9395 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory(); 9396 unsigned numAliased = 0; 9397 unsigned DistToSrc = 1; 9398 9399 for ( ; DepDest; DepDest = DepDest->NextLoadStore) { 9400 assert(isInSchedulingRegion(DepDest)); 9401 9402 // We have two limits to reduce the complexity: 9403 // 1) AliasedCheckLimit: It's a small limit to reduce calls to 9404 // SLP->isAliased (which is the expensive part in this loop). 9405 // 2) MaxMemDepDistance: It's for very large blocks and it aborts 9406 // the whole loop (even if the loop is fast, it's quadratic). 9407 // It's important for the loop break condition (see below) to 9408 // check this limit even between two read-only instructions. 9409 if (DistToSrc >= MaxMemDepDistance || 9410 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) && 9411 (numAliased >= AliasedCheckLimit || 9412 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) { 9413 9414 // We increment the counter only if the locations are aliased 9415 // (instead of counting all alias checks). This gives a better 9416 // balance between reduced runtime and accurate dependencies. 9417 numAliased++; 9418 9419 DepDest->MemoryDependencies.push_back(BundleMember); 9420 BundleMember->Dependencies++; 9421 ScheduleData *DestBundle = DepDest->FirstInBundle; 9422 if (!DestBundle->IsScheduled) { 9423 BundleMember->incrementUnscheduledDeps(1); 9424 } 9425 if (!DestBundle->hasValidDependencies()) { 9426 WorkList.push_back(DestBundle); 9427 } 9428 } 9429 9430 // Example, explaining the loop break condition: Let's assume our 9431 // starting instruction is i0 and MaxMemDepDistance = 3. 9432 // 9433 // +--------v--v--v 9434 // i0,i1,i2,i3,i4,i5,i6,i7,i8 9435 // +--------^--^--^ 9436 // 9437 // MaxMemDepDistance let us stop alias-checking at i3 and we add 9438 // dependencies from i0 to i3,i4,.. (even if they are not aliased). 9439 // Previously we already added dependencies from i3 to i6,i7,i8 9440 // (because of MaxMemDepDistance). As we added a dependency from 9441 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8 9442 // and we can abort this loop at i6. 9443 if (DistToSrc >= 2 * MaxMemDepDistance) 9444 break; 9445 DistToSrc++; 9446 } 9447 } 9448 if (InsertInReadyList && SD->isReady()) { 9449 ReadyInsts.insert(SD); 9450 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst 9451 << "\n"); 9452 } 9453 } 9454 } 9455 9456 void BoUpSLP::BlockScheduling::resetSchedule() { 9457 assert(ScheduleStart && 9458 "tried to reset schedule on block which has not been scheduled"); 9459 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 9460 doForAllOpcodes(I, [&](ScheduleData *SD) { 9461 assert(isInSchedulingRegion(SD) && 9462 "ScheduleData not in scheduling region"); 9463 SD->IsScheduled = false; 9464 SD->resetUnscheduledDeps(); 9465 }); 9466 } 9467 ReadyInsts.clear(); 9468 } 9469 9470 void BoUpSLP::scheduleBlock(BlockScheduling *BS) { 9471 if (!BS->ScheduleStart) 9472 return; 9473 9474 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n"); 9475 9476 // A key point - if we got here, pre-scheduling was able to find a valid 9477 // scheduling of the sub-graph of the scheduling window which consists 9478 // of all vector bundles and their transitive users. As such, we do not 9479 // need to reschedule anything *outside of* that subgraph. 9480 9481 BS->resetSchedule(); 9482 9483 // For the real scheduling we use a more sophisticated ready-list: it is 9484 // sorted by the original instruction location. This lets the final schedule 9485 // be as close as possible to the original instruction order. 9486 // WARNING: If changing this order causes a correctness issue, that means 9487 // there is some missing dependence edge in the schedule data graph. 9488 struct ScheduleDataCompare { 9489 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const { 9490 return SD2->SchedulingPriority < SD1->SchedulingPriority; 9491 } 9492 }; 9493 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts; 9494 9495 // Ensure that all dependency data is updated (for nodes in the sub-graph) 9496 // and fill the ready-list with initial instructions. 9497 int Idx = 0; 9498 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; 9499 I = I->getNextNode()) { 9500 BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) { 9501 TreeEntry *SDTE = getTreeEntry(SD->Inst); 9502 (void)SDTE; 9503 assert((isVectorLikeInstWithConstOps(SD->Inst) || 9504 SD->isPartOfBundle() == 9505 (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) && 9506 "scheduler and vectorizer bundle mismatch"); 9507 SD->FirstInBundle->SchedulingPriority = Idx++; 9508 9509 if (SD->isSchedulingEntity() && SD->isPartOfBundle()) 9510 BS->calculateDependencies(SD, false, this); 9511 }); 9512 } 9513 BS->initialFillReadyList(ReadyInsts); 9514 9515 Instruction *LastScheduledInst = BS->ScheduleEnd; 9516 9517 // Do the "real" scheduling. 9518 while (!ReadyInsts.empty()) { 9519 ScheduleData *picked = *ReadyInsts.begin(); 9520 ReadyInsts.erase(ReadyInsts.begin()); 9521 9522 // Move the scheduled instruction(s) to their dedicated places, if not 9523 // there yet. 9524 for (ScheduleData *BundleMember = picked; BundleMember; 9525 BundleMember = BundleMember->NextInBundle) { 9526 Instruction *pickedInst = BundleMember->Inst; 9527 if (pickedInst->getNextNode() != LastScheduledInst) 9528 pickedInst->moveBefore(LastScheduledInst); 9529 LastScheduledInst = pickedInst; 9530 } 9531 9532 BS->schedule(picked, ReadyInsts); 9533 } 9534 9535 // Check that we didn't break any of our invariants. 9536 #ifdef EXPENSIVE_CHECKS 9537 BS->verify(); 9538 #endif 9539 9540 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS) 9541 // Check that all schedulable entities got scheduled 9542 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) { 9543 BS->doForAllOpcodes(I, [&](ScheduleData *SD) { 9544 if (SD->isSchedulingEntity() && SD->hasValidDependencies()) { 9545 assert(SD->IsScheduled && "must be scheduled at this point"); 9546 } 9547 }); 9548 } 9549 #endif 9550 9551 // Avoid duplicate scheduling of the block. 9552 BS->ScheduleStart = nullptr; 9553 } 9554 9555 unsigned BoUpSLP::getVectorElementSize(Value *V) { 9556 // If V is a store, just return the width of the stored value (or value 9557 // truncated just before storing) without traversing the expression tree. 9558 // This is the common case. 9559 if (auto *Store = dyn_cast<StoreInst>(V)) 9560 return DL->getTypeSizeInBits(Store->getValueOperand()->getType()); 9561 9562 if (auto *IEI = dyn_cast<InsertElementInst>(V)) 9563 return getVectorElementSize(IEI->getOperand(1)); 9564 9565 auto E = InstrElementSize.find(V); 9566 if (E != InstrElementSize.end()) 9567 return E->second; 9568 9569 // If V is not a store, we can traverse the expression tree to find loads 9570 // that feed it. The type of the loaded value may indicate a more suitable 9571 // width than V's type. We want to base the vector element size on the width 9572 // of memory operations where possible. 9573 SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist; 9574 SmallPtrSet<Instruction *, 16> Visited; 9575 if (auto *I = dyn_cast<Instruction>(V)) { 9576 Worklist.emplace_back(I, I->getParent()); 9577 Visited.insert(I); 9578 } 9579 9580 // Traverse the expression tree in bottom-up order looking for loads. If we 9581 // encounter an instruction we don't yet handle, we give up. 9582 auto Width = 0u; 9583 while (!Worklist.empty()) { 9584 Instruction *I; 9585 BasicBlock *Parent; 9586 std::tie(I, Parent) = Worklist.pop_back_val(); 9587 9588 // We should only be looking at scalar instructions here. If the current 9589 // instruction has a vector type, skip. 9590 auto *Ty = I->getType(); 9591 if (isa<VectorType>(Ty)) 9592 continue; 9593 9594 // If the current instruction is a load, update MaxWidth to reflect the 9595 // width of the loaded value. 9596 if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) || 9597 isa<ExtractValueInst>(I)) 9598 Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty)); 9599 9600 // Otherwise, we need to visit the operands of the instruction. We only 9601 // handle the interesting cases from buildTree here. If an operand is an 9602 // instruction we haven't yet visited and from the same basic block as the 9603 // user or the use is a PHI node, we add it to the worklist. 9604 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 9605 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) || 9606 isa<UnaryOperator>(I)) { 9607 for (Use &U : I->operands()) 9608 if (auto *J = dyn_cast<Instruction>(U.get())) 9609 if (Visited.insert(J).second && 9610 (isa<PHINode>(I) || J->getParent() == Parent)) 9611 Worklist.emplace_back(J, J->getParent()); 9612 } else { 9613 break; 9614 } 9615 } 9616 9617 // If we didn't encounter a memory access in the expression tree, or if we 9618 // gave up for some reason, just return the width of V. Otherwise, return the 9619 // maximum width we found. 9620 if (!Width) { 9621 if (auto *CI = dyn_cast<CmpInst>(V)) 9622 V = CI->getOperand(0); 9623 Width = DL->getTypeSizeInBits(V->getType()); 9624 } 9625 9626 for (Instruction *I : Visited) 9627 InstrElementSize[I] = Width; 9628 9629 return Width; 9630 } 9631 9632 // Determine if a value V in a vectorizable expression Expr can be demoted to a 9633 // smaller type with a truncation. We collect the values that will be demoted 9634 // in ToDemote and additional roots that require investigating in Roots. 9635 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr, 9636 SmallVectorImpl<Value *> &ToDemote, 9637 SmallVectorImpl<Value *> &Roots) { 9638 // We can always demote constants. 9639 if (isa<Constant>(V)) { 9640 ToDemote.push_back(V); 9641 return true; 9642 } 9643 9644 // If the value is not an instruction in the expression with only one use, it 9645 // cannot be demoted. 9646 auto *I = dyn_cast<Instruction>(V); 9647 if (!I || !I->hasOneUse() || !Expr.count(I)) 9648 return false; 9649 9650 switch (I->getOpcode()) { 9651 9652 // We can always demote truncations and extensions. Since truncations can 9653 // seed additional demotion, we save the truncated value. 9654 case Instruction::Trunc: 9655 Roots.push_back(I->getOperand(0)); 9656 break; 9657 case Instruction::ZExt: 9658 case Instruction::SExt: 9659 if (isa<ExtractElementInst>(I->getOperand(0)) || 9660 isa<InsertElementInst>(I->getOperand(0))) 9661 return false; 9662 break; 9663 9664 // We can demote certain binary operations if we can demote both of their 9665 // operands. 9666 case Instruction::Add: 9667 case Instruction::Sub: 9668 case Instruction::Mul: 9669 case Instruction::And: 9670 case Instruction::Or: 9671 case Instruction::Xor: 9672 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) || 9673 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots)) 9674 return false; 9675 break; 9676 9677 // We can demote selects if we can demote their true and false values. 9678 case Instruction::Select: { 9679 SelectInst *SI = cast<SelectInst>(I); 9680 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) || 9681 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots)) 9682 return false; 9683 break; 9684 } 9685 9686 // We can demote phis if we can demote all their incoming operands. Note that 9687 // we don't need to worry about cycles since we ensure single use above. 9688 case Instruction::PHI: { 9689 PHINode *PN = cast<PHINode>(I); 9690 for (Value *IncValue : PN->incoming_values()) 9691 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots)) 9692 return false; 9693 break; 9694 } 9695 9696 // Otherwise, conservatively give up. 9697 default: 9698 return false; 9699 } 9700 9701 // Record the value that we can demote. 9702 ToDemote.push_back(V); 9703 return true; 9704 } 9705 9706 void BoUpSLP::computeMinimumValueSizes() { 9707 // If there are no external uses, the expression tree must be rooted by a 9708 // store. We can't demote in-memory values, so there is nothing to do here. 9709 if (ExternalUses.empty()) 9710 return; 9711 9712 // We only attempt to truncate integer expressions. 9713 auto &TreeRoot = VectorizableTree[0]->Scalars; 9714 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType()); 9715 if (!TreeRootIT) 9716 return; 9717 9718 // If the expression is not rooted by a store, these roots should have 9719 // external uses. We will rely on InstCombine to rewrite the expression in 9720 // the narrower type. However, InstCombine only rewrites single-use values. 9721 // This means that if a tree entry other than a root is used externally, it 9722 // must have multiple uses and InstCombine will not rewrite it. The code 9723 // below ensures that only the roots are used externally. 9724 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end()); 9725 for (auto &EU : ExternalUses) 9726 if (!Expr.erase(EU.Scalar)) 9727 return; 9728 if (!Expr.empty()) 9729 return; 9730 9731 // Collect the scalar values of the vectorizable expression. We will use this 9732 // context to determine which values can be demoted. If we see a truncation, 9733 // we mark it as seeding another demotion. 9734 for (auto &EntryPtr : VectorizableTree) 9735 Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end()); 9736 9737 // Ensure the roots of the vectorizable tree don't form a cycle. They must 9738 // have a single external user that is not in the vectorizable tree. 9739 for (auto *Root : TreeRoot) 9740 if (!Root->hasOneUse() || Expr.count(*Root->user_begin())) 9741 return; 9742 9743 // Conservatively determine if we can actually truncate the roots of the 9744 // expression. Collect the values that can be demoted in ToDemote and 9745 // additional roots that require investigating in Roots. 9746 SmallVector<Value *, 32> ToDemote; 9747 SmallVector<Value *, 4> Roots; 9748 for (auto *Root : TreeRoot) 9749 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots)) 9750 return; 9751 9752 // The maximum bit width required to represent all the values that can be 9753 // demoted without loss of precision. It would be safe to truncate the roots 9754 // of the expression to this width. 9755 auto MaxBitWidth = 8u; 9756 9757 // We first check if all the bits of the roots are demanded. If they're not, 9758 // we can truncate the roots to this narrower type. 9759 for (auto *Root : TreeRoot) { 9760 auto Mask = DB->getDemandedBits(cast<Instruction>(Root)); 9761 MaxBitWidth = std::max<unsigned>( 9762 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth); 9763 } 9764 9765 // True if the roots can be zero-extended back to their original type, rather 9766 // than sign-extended. We know that if the leading bits are not demanded, we 9767 // can safely zero-extend. So we initialize IsKnownPositive to True. 9768 bool IsKnownPositive = true; 9769 9770 // If all the bits of the roots are demanded, we can try a little harder to 9771 // compute a narrower type. This can happen, for example, if the roots are 9772 // getelementptr indices. InstCombine promotes these indices to the pointer 9773 // width. Thus, all their bits are technically demanded even though the 9774 // address computation might be vectorized in a smaller type. 9775 // 9776 // We start by looking at each entry that can be demoted. We compute the 9777 // maximum bit width required to store the scalar by using ValueTracking to 9778 // compute the number of high-order bits we can truncate. 9779 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) && 9780 llvm::all_of(TreeRoot, [](Value *R) { 9781 assert(R->hasOneUse() && "Root should have only one use!"); 9782 return isa<GetElementPtrInst>(R->user_back()); 9783 })) { 9784 MaxBitWidth = 8u; 9785 9786 // Determine if the sign bit of all the roots is known to be zero. If not, 9787 // IsKnownPositive is set to False. 9788 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) { 9789 KnownBits Known = computeKnownBits(R, *DL); 9790 return Known.isNonNegative(); 9791 }); 9792 9793 // Determine the maximum number of bits required to store the scalar 9794 // values. 9795 for (auto *Scalar : ToDemote) { 9796 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT); 9797 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType()); 9798 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth); 9799 } 9800 9801 // If we can't prove that the sign bit is zero, we must add one to the 9802 // maximum bit width to account for the unknown sign bit. This preserves 9803 // the existing sign bit so we can safely sign-extend the root back to the 9804 // original type. Otherwise, if we know the sign bit is zero, we will 9805 // zero-extend the root instead. 9806 // 9807 // FIXME: This is somewhat suboptimal, as there will be cases where adding 9808 // one to the maximum bit width will yield a larger-than-necessary 9809 // type. In general, we need to add an extra bit only if we can't 9810 // prove that the upper bit of the original type is equal to the 9811 // upper bit of the proposed smaller type. If these two bits are the 9812 // same (either zero or one) we know that sign-extending from the 9813 // smaller type will result in the same value. Here, since we can't 9814 // yet prove this, we are just making the proposed smaller type 9815 // larger to ensure correctness. 9816 if (!IsKnownPositive) 9817 ++MaxBitWidth; 9818 } 9819 9820 // Round MaxBitWidth up to the next power-of-two. 9821 if (!isPowerOf2_64(MaxBitWidth)) 9822 MaxBitWidth = NextPowerOf2(MaxBitWidth); 9823 9824 // If the maximum bit width we compute is less than the with of the roots' 9825 // type, we can proceed with the narrowing. Otherwise, do nothing. 9826 if (MaxBitWidth >= TreeRootIT->getBitWidth()) 9827 return; 9828 9829 // If we can truncate the root, we must collect additional values that might 9830 // be demoted as a result. That is, those seeded by truncations we will 9831 // modify. 9832 while (!Roots.empty()) 9833 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots); 9834 9835 // Finally, map the values we can demote to the maximum bit with we computed. 9836 for (auto *Scalar : ToDemote) 9837 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive); 9838 } 9839 9840 namespace { 9841 9842 /// The SLPVectorizer Pass. 9843 struct SLPVectorizer : public FunctionPass { 9844 SLPVectorizerPass Impl; 9845 9846 /// Pass identification, replacement for typeid 9847 static char ID; 9848 9849 explicit SLPVectorizer() : FunctionPass(ID) { 9850 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); 9851 } 9852 9853 bool doInitialization(Module &M) override { return false; } 9854 9855 bool runOnFunction(Function &F) override { 9856 if (skipFunction(F)) 9857 return false; 9858 9859 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 9860 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 9861 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 9862 auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr; 9863 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 9864 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 9865 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 9866 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 9867 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); 9868 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 9869 9870 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 9871 } 9872 9873 void getAnalysisUsage(AnalysisUsage &AU) const override { 9874 FunctionPass::getAnalysisUsage(AU); 9875 AU.addRequired<AssumptionCacheTracker>(); 9876 AU.addRequired<ScalarEvolutionWrapperPass>(); 9877 AU.addRequired<AAResultsWrapperPass>(); 9878 AU.addRequired<TargetTransformInfoWrapperPass>(); 9879 AU.addRequired<LoopInfoWrapperPass>(); 9880 AU.addRequired<DominatorTreeWrapperPass>(); 9881 AU.addRequired<DemandedBitsWrapperPass>(); 9882 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 9883 AU.addRequired<InjectTLIMappingsLegacy>(); 9884 AU.addPreserved<LoopInfoWrapperPass>(); 9885 AU.addPreserved<DominatorTreeWrapperPass>(); 9886 AU.addPreserved<AAResultsWrapperPass>(); 9887 AU.addPreserved<GlobalsAAWrapperPass>(); 9888 AU.setPreservesCFG(); 9889 } 9890 }; 9891 9892 } // end anonymous namespace 9893 9894 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) { 9895 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 9896 auto *TTI = &AM.getResult<TargetIRAnalysis>(F); 9897 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F); 9898 auto *AA = &AM.getResult<AAManager>(F); 9899 auto *LI = &AM.getResult<LoopAnalysis>(F); 9900 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 9901 auto *AC = &AM.getResult<AssumptionAnalysis>(F); 9902 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F); 9903 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 9904 9905 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 9906 if (!Changed) 9907 return PreservedAnalyses::all(); 9908 9909 PreservedAnalyses PA; 9910 PA.preserveSet<CFGAnalyses>(); 9911 return PA; 9912 } 9913 9914 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_, 9915 TargetTransformInfo *TTI_, 9916 TargetLibraryInfo *TLI_, AAResults *AA_, 9917 LoopInfo *LI_, DominatorTree *DT_, 9918 AssumptionCache *AC_, DemandedBits *DB_, 9919 OptimizationRemarkEmitter *ORE_) { 9920 if (!RunSLPVectorization) 9921 return false; 9922 SE = SE_; 9923 TTI = TTI_; 9924 TLI = TLI_; 9925 AA = AA_; 9926 LI = LI_; 9927 DT = DT_; 9928 AC = AC_; 9929 DB = DB_; 9930 DL = &F.getParent()->getDataLayout(); 9931 9932 Stores.clear(); 9933 GEPs.clear(); 9934 bool Changed = false; 9935 9936 // If the target claims to have no vector registers don't attempt 9937 // vectorization. 9938 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) { 9939 LLVM_DEBUG( 9940 dbgs() << "SLP: Didn't find any vector registers for target, abort.\n"); 9941 return false; 9942 } 9943 9944 // Don't vectorize when the attribute NoImplicitFloat is used. 9945 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) 9946 return false; 9947 9948 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"); 9949 9950 // Use the bottom up slp vectorizer to construct chains that start with 9951 // store instructions. 9952 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_); 9953 9954 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to 9955 // delete instructions. 9956 9957 // Update DFS numbers now so that we can use them for ordering. 9958 DT->updateDFSNumbers(); 9959 9960 // Scan the blocks in the function in post order. 9961 for (auto BB : post_order(&F.getEntryBlock())) { 9962 // Start new block - clear the list of reduction roots. 9963 R.clearReductionData(); 9964 collectSeedInstructions(BB); 9965 9966 // Vectorize trees that end at stores. 9967 if (!Stores.empty()) { 9968 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size() 9969 << " underlying objects.\n"); 9970 Changed |= vectorizeStoreChains(R); 9971 } 9972 9973 // Vectorize trees that end at reductions. 9974 Changed |= vectorizeChainsInBlock(BB, R); 9975 9976 // Vectorize the index computations of getelementptr instructions. This 9977 // is primarily intended to catch gather-like idioms ending at 9978 // non-consecutive loads. 9979 if (!GEPs.empty()) { 9980 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size() 9981 << " underlying objects.\n"); 9982 Changed |= vectorizeGEPIndices(BB, R); 9983 } 9984 } 9985 9986 if (Changed) { 9987 R.optimizeGatherSequence(); 9988 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n"); 9989 } 9990 return Changed; 9991 } 9992 9993 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R, 9994 unsigned Idx, unsigned MinVF) { 9995 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size() 9996 << "\n"); 9997 const unsigned Sz = R.getVectorElementSize(Chain[0]); 9998 unsigned VF = Chain.size(); 9999 10000 if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF) 10001 return false; 10002 10003 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx 10004 << "\n"); 10005 10006 R.buildTree(Chain); 10007 if (R.isTreeTinyAndNotFullyVectorizable()) 10008 return false; 10009 if (R.isLoadCombineCandidate()) 10010 return false; 10011 R.reorderTopToBottom(); 10012 R.reorderBottomToTop(); 10013 R.buildExternalUses(); 10014 10015 R.computeMinimumValueSizes(); 10016 10017 InstructionCost Cost = R.getTreeCost(); 10018 10019 LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n"); 10020 if (Cost < -SLPCostThreshold) { 10021 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n"); 10022 10023 using namespace ore; 10024 10025 R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized", 10026 cast<StoreInst>(Chain[0])) 10027 << "Stores SLP vectorized with cost " << NV("Cost", Cost) 10028 << " and with tree size " 10029 << NV("TreeSize", R.getTreeSize())); 10030 10031 R.vectorizeTree(); 10032 return true; 10033 } 10034 10035 return false; 10036 } 10037 10038 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores, 10039 BoUpSLP &R) { 10040 // We may run into multiple chains that merge into a single chain. We mark the 10041 // stores that we vectorized so that we don't visit the same store twice. 10042 BoUpSLP::ValueSet VectorizedStores; 10043 bool Changed = false; 10044 10045 int E = Stores.size(); 10046 SmallBitVector Tails(E, false); 10047 int MaxIter = MaxStoreLookup.getValue(); 10048 SmallVector<std::pair<int, int>, 16> ConsecutiveChain( 10049 E, std::make_pair(E, INT_MAX)); 10050 SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false)); 10051 int IterCnt; 10052 auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter, 10053 &CheckedPairs, 10054 &ConsecutiveChain](int K, int Idx) { 10055 if (IterCnt >= MaxIter) 10056 return true; 10057 if (CheckedPairs[Idx].test(K)) 10058 return ConsecutiveChain[K].second == 1 && 10059 ConsecutiveChain[K].first == Idx; 10060 ++IterCnt; 10061 CheckedPairs[Idx].set(K); 10062 CheckedPairs[K].set(Idx); 10063 Optional<int> Diff = getPointersDiff( 10064 Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(), 10065 Stores[Idx]->getValueOperand()->getType(), 10066 Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true); 10067 if (!Diff || *Diff == 0) 10068 return false; 10069 int Val = *Diff; 10070 if (Val < 0) { 10071 if (ConsecutiveChain[Idx].second > -Val) { 10072 Tails.set(K); 10073 ConsecutiveChain[Idx] = std::make_pair(K, -Val); 10074 } 10075 return false; 10076 } 10077 if (ConsecutiveChain[K].second <= Val) 10078 return false; 10079 10080 Tails.set(Idx); 10081 ConsecutiveChain[K] = std::make_pair(Idx, Val); 10082 return Val == 1; 10083 }; 10084 // Do a quadratic search on all of the given stores in reverse order and find 10085 // all of the pairs of stores that follow each other. 10086 for (int Idx = E - 1; Idx >= 0; --Idx) { 10087 // If a store has multiple consecutive store candidates, search according 10088 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ... 10089 // This is because usually pairing with immediate succeeding or preceding 10090 // candidate create the best chance to find slp vectorization opportunity. 10091 const int MaxLookDepth = std::max(E - Idx, Idx + 1); 10092 IterCnt = 0; 10093 for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset) 10094 if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) || 10095 (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx))) 10096 break; 10097 } 10098 10099 // Tracks if we tried to vectorize stores starting from the given tail 10100 // already. 10101 SmallBitVector TriedTails(E, false); 10102 // For stores that start but don't end a link in the chain: 10103 for (int Cnt = E; Cnt > 0; --Cnt) { 10104 int I = Cnt - 1; 10105 if (ConsecutiveChain[I].first == E || Tails.test(I)) 10106 continue; 10107 // We found a store instr that starts a chain. Now follow the chain and try 10108 // to vectorize it. 10109 BoUpSLP::ValueList Operands; 10110 // Collect the chain into a list. 10111 while (I != E && !VectorizedStores.count(Stores[I])) { 10112 Operands.push_back(Stores[I]); 10113 Tails.set(I); 10114 if (ConsecutiveChain[I].second != 1) { 10115 // Mark the new end in the chain and go back, if required. It might be 10116 // required if the original stores come in reversed order, for example. 10117 if (ConsecutiveChain[I].first != E && 10118 Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) && 10119 !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) { 10120 TriedTails.set(I); 10121 Tails.reset(ConsecutiveChain[I].first); 10122 if (Cnt < ConsecutiveChain[I].first + 2) 10123 Cnt = ConsecutiveChain[I].first + 2; 10124 } 10125 break; 10126 } 10127 // Move to the next value in the chain. 10128 I = ConsecutiveChain[I].first; 10129 } 10130 assert(!Operands.empty() && "Expected non-empty list of stores."); 10131 10132 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 10133 unsigned EltSize = R.getVectorElementSize(Operands[0]); 10134 unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize); 10135 10136 unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store), 10137 MaxElts); 10138 auto *Store = cast<StoreInst>(Operands[0]); 10139 Type *StoreTy = Store->getValueOperand()->getType(); 10140 Type *ValueTy = StoreTy; 10141 if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand())) 10142 ValueTy = Trunc->getSrcTy(); 10143 unsigned MinVF = TTI->getStoreMinimumVF( 10144 R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy); 10145 10146 // FIXME: Is division-by-2 the correct step? Should we assert that the 10147 // register size is a power-of-2? 10148 unsigned StartIdx = 0; 10149 for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) { 10150 for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) { 10151 ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size); 10152 if (!VectorizedStores.count(Slice.front()) && 10153 !VectorizedStores.count(Slice.back()) && 10154 vectorizeStoreChain(Slice, R, Cnt, MinVF)) { 10155 // Mark the vectorized stores so that we don't vectorize them again. 10156 VectorizedStores.insert(Slice.begin(), Slice.end()); 10157 Changed = true; 10158 // If we vectorized initial block, no need to try to vectorize it 10159 // again. 10160 if (Cnt == StartIdx) 10161 StartIdx += Size; 10162 Cnt += Size; 10163 continue; 10164 } 10165 ++Cnt; 10166 } 10167 // Check if the whole array was vectorized already - exit. 10168 if (StartIdx >= Operands.size()) 10169 break; 10170 } 10171 } 10172 10173 return Changed; 10174 } 10175 10176 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) { 10177 // Initialize the collections. We will make a single pass over the block. 10178 Stores.clear(); 10179 GEPs.clear(); 10180 10181 // Visit the store and getelementptr instructions in BB and organize them in 10182 // Stores and GEPs according to the underlying objects of their pointer 10183 // operands. 10184 for (Instruction &I : *BB) { 10185 // Ignore store instructions that are volatile or have a pointer operand 10186 // that doesn't point to a scalar type. 10187 if (auto *SI = dyn_cast<StoreInst>(&I)) { 10188 if (!SI->isSimple()) 10189 continue; 10190 if (!isValidElementType(SI->getValueOperand()->getType())) 10191 continue; 10192 Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI); 10193 } 10194 10195 // Ignore getelementptr instructions that have more than one index, a 10196 // constant index, or a pointer operand that doesn't point to a scalar 10197 // type. 10198 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 10199 auto Idx = GEP->idx_begin()->get(); 10200 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx)) 10201 continue; 10202 if (!isValidElementType(Idx->getType())) 10203 continue; 10204 if (GEP->getType()->isVectorTy()) 10205 continue; 10206 GEPs[GEP->getPointerOperand()].push_back(GEP); 10207 } 10208 } 10209 } 10210 10211 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { 10212 if (!A || !B) 10213 return false; 10214 if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B)) 10215 return false; 10216 Value *VL[] = {A, B}; 10217 return tryToVectorizeList(VL, R); 10218 } 10219 10220 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, 10221 bool LimitForRegisterSize) { 10222 if (VL.size() < 2) 10223 return false; 10224 10225 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " 10226 << VL.size() << ".\n"); 10227 10228 // Check that all of the parts are instructions of the same type, 10229 // we permit an alternate opcode via InstructionsState. 10230 InstructionsState S = getSameOpcode(VL); 10231 if (!S.getOpcode()) 10232 return false; 10233 10234 Instruction *I0 = cast<Instruction>(S.OpValue); 10235 // Make sure invalid types (including vector type) are rejected before 10236 // determining vectorization factor for scalar instructions. 10237 for (Value *V : VL) { 10238 Type *Ty = V->getType(); 10239 if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) { 10240 // NOTE: the following will give user internal llvm type name, which may 10241 // not be useful. 10242 R.getORE()->emit([&]() { 10243 std::string type_str; 10244 llvm::raw_string_ostream rso(type_str); 10245 Ty->print(rso); 10246 return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0) 10247 << "Cannot SLP vectorize list: type " 10248 << rso.str() + " is unsupported by vectorizer"; 10249 }); 10250 return false; 10251 } 10252 } 10253 10254 unsigned Sz = R.getVectorElementSize(I0); 10255 unsigned MinVF = R.getMinVF(Sz); 10256 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF); 10257 MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF); 10258 if (MaxVF < 2) { 10259 R.getORE()->emit([&]() { 10260 return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0) 10261 << "Cannot SLP vectorize list: vectorization factor " 10262 << "less than 2 is not supported"; 10263 }); 10264 return false; 10265 } 10266 10267 bool Changed = false; 10268 bool CandidateFound = false; 10269 InstructionCost MinCost = SLPCostThreshold.getValue(); 10270 Type *ScalarTy = VL[0]->getType(); 10271 if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 10272 ScalarTy = IE->getOperand(1)->getType(); 10273 10274 unsigned NextInst = 0, MaxInst = VL.size(); 10275 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) { 10276 // No actual vectorization should happen, if number of parts is the same as 10277 // provided vectorization factor (i.e. the scalar type is used for vector 10278 // code during codegen). 10279 auto *VecTy = FixedVectorType::get(ScalarTy, VF); 10280 if (TTI->getNumberOfParts(VecTy) == VF) 10281 continue; 10282 for (unsigned I = NextInst; I < MaxInst; ++I) { 10283 unsigned OpsWidth = 0; 10284 10285 if (I + VF > MaxInst) 10286 OpsWidth = MaxInst - I; 10287 else 10288 OpsWidth = VF; 10289 10290 if (!isPowerOf2_32(OpsWidth)) 10291 continue; 10292 10293 if ((LimitForRegisterSize && OpsWidth < MaxVF) || 10294 (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2)) 10295 break; 10296 10297 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth); 10298 // Check that a previous iteration of this loop did not delete the Value. 10299 if (llvm::any_of(Ops, [&R](Value *V) { 10300 auto *I = dyn_cast<Instruction>(V); 10301 return I && R.isDeleted(I); 10302 })) 10303 continue; 10304 10305 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " 10306 << "\n"); 10307 10308 R.buildTree(Ops); 10309 if (R.isTreeTinyAndNotFullyVectorizable()) 10310 continue; 10311 R.reorderTopToBottom(); 10312 R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front())); 10313 R.buildExternalUses(); 10314 10315 R.computeMinimumValueSizes(); 10316 InstructionCost Cost = R.getTreeCost(); 10317 CandidateFound = true; 10318 MinCost = std::min(MinCost, Cost); 10319 10320 if (Cost < -SLPCostThreshold) { 10321 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n"); 10322 R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList", 10323 cast<Instruction>(Ops[0])) 10324 << "SLP vectorized with cost " << ore::NV("Cost", Cost) 10325 << " and with tree size " 10326 << ore::NV("TreeSize", R.getTreeSize())); 10327 10328 R.vectorizeTree(); 10329 // Move to the next bundle. 10330 I += VF - 1; 10331 NextInst = I + 1; 10332 Changed = true; 10333 } 10334 } 10335 } 10336 10337 if (!Changed && CandidateFound) { 10338 R.getORE()->emit([&]() { 10339 return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0) 10340 << "List vectorization was possible but not beneficial with cost " 10341 << ore::NV("Cost", MinCost) << " >= " 10342 << ore::NV("Treshold", -SLPCostThreshold); 10343 }); 10344 } else if (!Changed) { 10345 R.getORE()->emit([&]() { 10346 return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0) 10347 << "Cannot SLP vectorize list: vectorization was impossible" 10348 << " with available vectorization factors"; 10349 }); 10350 } 10351 return Changed; 10352 } 10353 10354 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) { 10355 if (!I) 10356 return false; 10357 10358 if ((!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) || 10359 isa<VectorType>(I->getType())) 10360 return false; 10361 10362 Value *P = I->getParent(); 10363 10364 // Vectorize in current basic block only. 10365 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0)); 10366 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1)); 10367 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P) 10368 return false; 10369 10370 // First collect all possible candidates 10371 SmallVector<std::pair<Value *, Value *>, 4> Candidates; 10372 Candidates.emplace_back(Op0, Op1); 10373 10374 auto *A = dyn_cast<BinaryOperator>(Op0); 10375 auto *B = dyn_cast<BinaryOperator>(Op1); 10376 // Try to skip B. 10377 if (A && B && B->hasOneUse()) { 10378 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); 10379 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); 10380 if (B0 && B0->getParent() == P) 10381 Candidates.emplace_back(A, B0); 10382 if (B1 && B1->getParent() == P) 10383 Candidates.emplace_back(A, B1); 10384 } 10385 // Try to skip A. 10386 if (B && A && A->hasOneUse()) { 10387 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); 10388 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); 10389 if (A0 && A0->getParent() == P) 10390 Candidates.emplace_back(A0, B); 10391 if (A1 && A1->getParent() == P) 10392 Candidates.emplace_back(A1, B); 10393 } 10394 10395 if (Candidates.size() == 1) 10396 return tryToVectorizePair(Op0, Op1, R); 10397 10398 // We have multiple options. Try to pick the single best. 10399 Optional<int> BestCandidate = R.findBestRootPair(Candidates); 10400 if (!BestCandidate) 10401 return false; 10402 return tryToVectorizePair(Candidates[*BestCandidate].first, 10403 Candidates[*BestCandidate].second, R); 10404 } 10405 10406 namespace { 10407 10408 /// Model horizontal reductions. 10409 /// 10410 /// A horizontal reduction is a tree of reduction instructions that has values 10411 /// that can be put into a vector as its leaves. For example: 10412 /// 10413 /// mul mul mul mul 10414 /// \ / \ / 10415 /// + + 10416 /// \ / 10417 /// + 10418 /// This tree has "mul" as its leaf values and "+" as its reduction 10419 /// instructions. A reduction can feed into a store or a binary operation 10420 /// feeding a phi. 10421 /// ... 10422 /// \ / 10423 /// + 10424 /// | 10425 /// phi += 10426 /// 10427 /// Or: 10428 /// ... 10429 /// \ / 10430 /// + 10431 /// | 10432 /// *p = 10433 /// 10434 class HorizontalReduction { 10435 using ReductionOpsType = SmallVector<Value *, 16>; 10436 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>; 10437 ReductionOpsListType ReductionOps; 10438 /// List of possibly reduced values. 10439 SmallVector<SmallVector<Value *>> ReducedVals; 10440 /// Maps reduced value to the corresponding reduction operation. 10441 DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps; 10442 // Use map vector to make stable output. 10443 MapVector<Instruction *, Value *> ExtraArgs; 10444 WeakTrackingVH ReductionRoot; 10445 /// The type of reduction operation. 10446 RecurKind RdxKind; 10447 10448 static bool isCmpSelMinMax(Instruction *I) { 10449 return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) && 10450 RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I)); 10451 } 10452 10453 // And/or are potentially poison-safe logical patterns like: 10454 // select x, y, false 10455 // select x, true, y 10456 static bool isBoolLogicOp(Instruction *I) { 10457 return match(I, m_LogicalAnd(m_Value(), m_Value())) || 10458 match(I, m_LogicalOr(m_Value(), m_Value())); 10459 } 10460 10461 /// Checks if instruction is associative and can be vectorized. 10462 static bool isVectorizable(RecurKind Kind, Instruction *I) { 10463 if (Kind == RecurKind::None) 10464 return false; 10465 10466 // Integer ops that map to select instructions or intrinsics are fine. 10467 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) || 10468 isBoolLogicOp(I)) 10469 return true; 10470 10471 if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) { 10472 // FP min/max are associative except for NaN and -0.0. We do not 10473 // have to rule out -0.0 here because the intrinsic semantics do not 10474 // specify a fixed result for it. 10475 return I->getFastMathFlags().noNaNs(); 10476 } 10477 10478 return I->isAssociative(); 10479 } 10480 10481 static Value *getRdxOperand(Instruction *I, unsigned Index) { 10482 // Poison-safe 'or' takes the form: select X, true, Y 10483 // To make that work with the normal operand processing, we skip the 10484 // true value operand. 10485 // TODO: Change the code and data structures to handle this without a hack. 10486 if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1) 10487 return I->getOperand(2); 10488 return I->getOperand(Index); 10489 } 10490 10491 /// Creates reduction operation with the current opcode. 10492 static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS, 10493 Value *RHS, const Twine &Name, bool UseSelect) { 10494 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind); 10495 switch (Kind) { 10496 case RecurKind::Or: 10497 if (UseSelect && 10498 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 10499 return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name); 10500 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 10501 Name); 10502 case RecurKind::And: 10503 if (UseSelect && 10504 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 10505 return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name); 10506 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 10507 Name); 10508 case RecurKind::Add: 10509 case RecurKind::Mul: 10510 case RecurKind::Xor: 10511 case RecurKind::FAdd: 10512 case RecurKind::FMul: 10513 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 10514 Name); 10515 case RecurKind::FMax: 10516 return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS); 10517 case RecurKind::FMin: 10518 return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS); 10519 case RecurKind::SMax: 10520 if (UseSelect) { 10521 Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name); 10522 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 10523 } 10524 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS); 10525 case RecurKind::SMin: 10526 if (UseSelect) { 10527 Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name); 10528 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 10529 } 10530 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS); 10531 case RecurKind::UMax: 10532 if (UseSelect) { 10533 Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name); 10534 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 10535 } 10536 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS); 10537 case RecurKind::UMin: 10538 if (UseSelect) { 10539 Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name); 10540 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 10541 } 10542 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS); 10543 default: 10544 llvm_unreachable("Unknown reduction operation."); 10545 } 10546 } 10547 10548 /// Creates reduction operation with the current opcode with the IR flags 10549 /// from \p ReductionOps, dropping nuw/nsw flags. 10550 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 10551 Value *RHS, const Twine &Name, 10552 const ReductionOpsListType &ReductionOps) { 10553 bool UseSelect = ReductionOps.size() == 2 || 10554 // Logical or/and. 10555 (ReductionOps.size() == 1 && 10556 isa<SelectInst>(ReductionOps.front().front())); 10557 assert((!UseSelect || ReductionOps.size() != 2 || 10558 isa<SelectInst>(ReductionOps[1][0])) && 10559 "Expected cmp + select pairs for reduction"); 10560 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect); 10561 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 10562 if (auto *Sel = dyn_cast<SelectInst>(Op)) { 10563 propagateIRFlags(Sel->getCondition(), ReductionOps[0], nullptr, 10564 /*IncludeWrapFlags=*/false); 10565 propagateIRFlags(Op, ReductionOps[1], nullptr, 10566 /*IncludeWrapFlags=*/false); 10567 return Op; 10568 } 10569 } 10570 propagateIRFlags(Op, ReductionOps[0], nullptr, /*IncludeWrapFlags=*/false); 10571 return Op; 10572 } 10573 10574 static RecurKind getRdxKind(Value *V) { 10575 auto *I = dyn_cast<Instruction>(V); 10576 if (!I) 10577 return RecurKind::None; 10578 if (match(I, m_Add(m_Value(), m_Value()))) 10579 return RecurKind::Add; 10580 if (match(I, m_Mul(m_Value(), m_Value()))) 10581 return RecurKind::Mul; 10582 if (match(I, m_And(m_Value(), m_Value())) || 10583 match(I, m_LogicalAnd(m_Value(), m_Value()))) 10584 return RecurKind::And; 10585 if (match(I, m_Or(m_Value(), m_Value())) || 10586 match(I, m_LogicalOr(m_Value(), m_Value()))) 10587 return RecurKind::Or; 10588 if (match(I, m_Xor(m_Value(), m_Value()))) 10589 return RecurKind::Xor; 10590 if (match(I, m_FAdd(m_Value(), m_Value()))) 10591 return RecurKind::FAdd; 10592 if (match(I, m_FMul(m_Value(), m_Value()))) 10593 return RecurKind::FMul; 10594 10595 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value()))) 10596 return RecurKind::FMax; 10597 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value()))) 10598 return RecurKind::FMin; 10599 10600 // This matches either cmp+select or intrinsics. SLP is expected to handle 10601 // either form. 10602 // TODO: If we are canonicalizing to intrinsics, we can remove several 10603 // special-case paths that deal with selects. 10604 if (match(I, m_SMax(m_Value(), m_Value()))) 10605 return RecurKind::SMax; 10606 if (match(I, m_SMin(m_Value(), m_Value()))) 10607 return RecurKind::SMin; 10608 if (match(I, m_UMax(m_Value(), m_Value()))) 10609 return RecurKind::UMax; 10610 if (match(I, m_UMin(m_Value(), m_Value()))) 10611 return RecurKind::UMin; 10612 10613 if (auto *Select = dyn_cast<SelectInst>(I)) { 10614 // Try harder: look for min/max pattern based on instructions producing 10615 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2). 10616 // During the intermediate stages of SLP, it's very common to have 10617 // pattern like this (since optimizeGatherSequence is run only once 10618 // at the end): 10619 // %1 = extractelement <2 x i32> %a, i32 0 10620 // %2 = extractelement <2 x i32> %a, i32 1 10621 // %cond = icmp sgt i32 %1, %2 10622 // %3 = extractelement <2 x i32> %a, i32 0 10623 // %4 = extractelement <2 x i32> %a, i32 1 10624 // %select = select i1 %cond, i32 %3, i32 %4 10625 CmpInst::Predicate Pred; 10626 Instruction *L1; 10627 Instruction *L2; 10628 10629 Value *LHS = Select->getTrueValue(); 10630 Value *RHS = Select->getFalseValue(); 10631 Value *Cond = Select->getCondition(); 10632 10633 // TODO: Support inverse predicates. 10634 if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) { 10635 if (!isa<ExtractElementInst>(RHS) || 10636 !L2->isIdenticalTo(cast<Instruction>(RHS))) 10637 return RecurKind::None; 10638 } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) { 10639 if (!isa<ExtractElementInst>(LHS) || 10640 !L1->isIdenticalTo(cast<Instruction>(LHS))) 10641 return RecurKind::None; 10642 } else { 10643 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS)) 10644 return RecurKind::None; 10645 if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) || 10646 !L1->isIdenticalTo(cast<Instruction>(LHS)) || 10647 !L2->isIdenticalTo(cast<Instruction>(RHS))) 10648 return RecurKind::None; 10649 } 10650 10651 switch (Pred) { 10652 default: 10653 return RecurKind::None; 10654 case CmpInst::ICMP_SGT: 10655 case CmpInst::ICMP_SGE: 10656 return RecurKind::SMax; 10657 case CmpInst::ICMP_SLT: 10658 case CmpInst::ICMP_SLE: 10659 return RecurKind::SMin; 10660 case CmpInst::ICMP_UGT: 10661 case CmpInst::ICMP_UGE: 10662 return RecurKind::UMax; 10663 case CmpInst::ICMP_ULT: 10664 case CmpInst::ICMP_ULE: 10665 return RecurKind::UMin; 10666 } 10667 } 10668 return RecurKind::None; 10669 } 10670 10671 /// Get the index of the first operand. 10672 static unsigned getFirstOperandIndex(Instruction *I) { 10673 return isCmpSelMinMax(I) ? 1 : 0; 10674 } 10675 10676 /// Total number of operands in the reduction operation. 10677 static unsigned getNumberOfOperands(Instruction *I) { 10678 return isCmpSelMinMax(I) ? 3 : 2; 10679 } 10680 10681 /// Checks if the instruction is in basic block \p BB. 10682 /// For a cmp+sel min/max reduction check that both ops are in \p BB. 10683 static bool hasSameParent(Instruction *I, BasicBlock *BB) { 10684 if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) { 10685 auto *Sel = cast<SelectInst>(I); 10686 auto *Cmp = dyn_cast<Instruction>(Sel->getCondition()); 10687 return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB; 10688 } 10689 return I->getParent() == BB; 10690 } 10691 10692 /// Expected number of uses for reduction operations/reduced values. 10693 static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) { 10694 if (IsCmpSelMinMax) { 10695 // SelectInst must be used twice while the condition op must have single 10696 // use only. 10697 if (auto *Sel = dyn_cast<SelectInst>(I)) 10698 return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse(); 10699 return I->hasNUses(2); 10700 } 10701 10702 // Arithmetic reduction operation must be used once only. 10703 return I->hasOneUse(); 10704 } 10705 10706 /// Initializes the list of reduction operations. 10707 void initReductionOps(Instruction *I) { 10708 if (isCmpSelMinMax(I)) 10709 ReductionOps.assign(2, ReductionOpsType()); 10710 else 10711 ReductionOps.assign(1, ReductionOpsType()); 10712 } 10713 10714 /// Add all reduction operations for the reduction instruction \p I. 10715 void addReductionOps(Instruction *I) { 10716 if (isCmpSelMinMax(I)) { 10717 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition()); 10718 ReductionOps[1].emplace_back(I); 10719 } else { 10720 ReductionOps[0].emplace_back(I); 10721 } 10722 } 10723 10724 static Value *getLHS(RecurKind Kind, Instruction *I) { 10725 if (Kind == RecurKind::None) 10726 return nullptr; 10727 return I->getOperand(getFirstOperandIndex(I)); 10728 } 10729 static Value *getRHS(RecurKind Kind, Instruction *I) { 10730 if (Kind == RecurKind::None) 10731 return nullptr; 10732 return I->getOperand(getFirstOperandIndex(I) + 1); 10733 } 10734 10735 public: 10736 HorizontalReduction() = default; 10737 10738 /// Try to find a reduction tree. 10739 bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst, 10740 ScalarEvolution &SE, const DataLayout &DL, 10741 const TargetLibraryInfo &TLI) { 10742 assert((!Phi || is_contained(Phi->operands(), Inst)) && 10743 "Phi needs to use the binary operator"); 10744 assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || 10745 isa<IntrinsicInst>(Inst)) && 10746 "Expected binop, select, or intrinsic for reduction matching"); 10747 RdxKind = getRdxKind(Inst); 10748 10749 // We could have a initial reductions that is not an add. 10750 // r *= v1 + v2 + v3 + v4 10751 // In such a case start looking for a tree rooted in the first '+'. 10752 if (Phi) { 10753 if (getLHS(RdxKind, Inst) == Phi) { 10754 Phi = nullptr; 10755 Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst)); 10756 if (!Inst) 10757 return false; 10758 RdxKind = getRdxKind(Inst); 10759 } else if (getRHS(RdxKind, Inst) == Phi) { 10760 Phi = nullptr; 10761 Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst)); 10762 if (!Inst) 10763 return false; 10764 RdxKind = getRdxKind(Inst); 10765 } 10766 } 10767 10768 if (!isVectorizable(RdxKind, Inst)) 10769 return false; 10770 10771 // Analyze "regular" integer/FP types for reductions - no target-specific 10772 // types or pointers. 10773 Type *Ty = Inst->getType(); 10774 if (!isValidElementType(Ty) || Ty->isPointerTy()) 10775 return false; 10776 10777 // Though the ultimate reduction may have multiple uses, its condition must 10778 // have only single use. 10779 if (auto *Sel = dyn_cast<SelectInst>(Inst)) 10780 if (!Sel->getCondition()->hasOneUse()) 10781 return false; 10782 10783 ReductionRoot = Inst; 10784 10785 // Iterate through all the operands of the possible reduction tree and 10786 // gather all the reduced values, sorting them by their value id. 10787 BasicBlock *BB = Inst->getParent(); 10788 bool IsCmpSelMinMax = isCmpSelMinMax(Inst); 10789 SmallVector<Instruction *> Worklist(1, Inst); 10790 // Checks if the operands of the \p TreeN instruction are also reduction 10791 // operations or should be treated as reduced values or an extra argument, 10792 // which is not part of the reduction. 10793 auto &&CheckOperands = [this, IsCmpSelMinMax, 10794 BB](Instruction *TreeN, 10795 SmallVectorImpl<Value *> &ExtraArgs, 10796 SmallVectorImpl<Value *> &PossibleReducedVals, 10797 SmallVectorImpl<Instruction *> &ReductionOps) { 10798 for (int I = getFirstOperandIndex(TreeN), 10799 End = getNumberOfOperands(TreeN); 10800 I < End; ++I) { 10801 Value *EdgeVal = getRdxOperand(TreeN, I); 10802 ReducedValsToOps[EdgeVal].push_back(TreeN); 10803 auto *EdgeInst = dyn_cast<Instruction>(EdgeVal); 10804 // Edge has wrong parent - mark as an extra argument. 10805 if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) && 10806 !hasSameParent(EdgeInst, BB)) { 10807 ExtraArgs.push_back(EdgeVal); 10808 continue; 10809 } 10810 // If the edge is not an instruction, or it is different from the main 10811 // reduction opcode or has too many uses - possible reduced value. 10812 if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind || 10813 IsCmpSelMinMax != isCmpSelMinMax(EdgeInst) || 10814 !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) || 10815 !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) { 10816 PossibleReducedVals.push_back(EdgeVal); 10817 continue; 10818 } 10819 ReductionOps.push_back(EdgeInst); 10820 } 10821 }; 10822 // Try to regroup reduced values so that it gets more profitable to try to 10823 // reduce them. Values are grouped by their value ids, instructions - by 10824 // instruction op id and/or alternate op id, plus do extra analysis for 10825 // loads (grouping them by the distabce between pointers) and cmp 10826 // instructions (grouping them by the predicate). 10827 MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>> 10828 PossibleReducedVals; 10829 initReductionOps(Inst); 10830 while (!Worklist.empty()) { 10831 Instruction *TreeN = Worklist.pop_back_val(); 10832 SmallVector<Value *> Args; 10833 SmallVector<Value *> PossibleRedVals; 10834 SmallVector<Instruction *> PossibleReductionOps; 10835 CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps); 10836 // If too many extra args - mark the instruction itself as a reduction 10837 // value, not a reduction operation. 10838 if (Args.size() < 2) { 10839 addReductionOps(TreeN); 10840 // Add extra args. 10841 if (!Args.empty()) { 10842 assert(Args.size() == 1 && "Expected only single argument."); 10843 ExtraArgs[TreeN] = Args.front(); 10844 } 10845 // Add reduction values. The values are sorted for better vectorization 10846 // results. 10847 for (Value *V : PossibleRedVals) { 10848 size_t Key, Idx; 10849 std::tie(Key, Idx) = generateKeySubkey( 10850 V, &TLI, 10851 [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) { 10852 auto It = PossibleReducedVals.find(Key); 10853 if (It != PossibleReducedVals.end()) { 10854 for (const auto &LoadData : It->second) { 10855 auto *RLI = cast<LoadInst>(LoadData.second.front().first); 10856 if (getPointersDiff(RLI->getType(), 10857 RLI->getPointerOperand(), LI->getType(), 10858 LI->getPointerOperand(), DL, SE, 10859 /*StrictCheck=*/true)) 10860 return hash_value(RLI->getPointerOperand()); 10861 } 10862 } 10863 return hash_value(LI->getPointerOperand()); 10864 }, 10865 /*AllowAlternate=*/false); 10866 ++PossibleReducedVals[Key][Idx] 10867 .insert(std::make_pair(V, 0)) 10868 .first->second; 10869 } 10870 Worklist.append(PossibleReductionOps.rbegin(), 10871 PossibleReductionOps.rend()); 10872 } else { 10873 size_t Key, Idx; 10874 std::tie(Key, Idx) = generateKeySubkey( 10875 TreeN, &TLI, 10876 [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) { 10877 auto It = PossibleReducedVals.find(Key); 10878 if (It != PossibleReducedVals.end()) { 10879 for (const auto &LoadData : It->second) { 10880 auto *RLI = cast<LoadInst>(LoadData.second.front().first); 10881 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(), 10882 LI->getType(), LI->getPointerOperand(), 10883 DL, SE, /*StrictCheck=*/true)) 10884 return hash_value(RLI->getPointerOperand()); 10885 } 10886 } 10887 return hash_value(LI->getPointerOperand()); 10888 }, 10889 /*AllowAlternate=*/false); 10890 ++PossibleReducedVals[Key][Idx] 10891 .insert(std::make_pair(TreeN, 0)) 10892 .first->second; 10893 } 10894 } 10895 auto PossibleReducedValsVect = PossibleReducedVals.takeVector(); 10896 // Sort values by the total number of values kinds to start the reduction 10897 // from the longest possible reduced values sequences. 10898 for (auto &PossibleReducedVals : PossibleReducedValsVect) { 10899 auto PossibleRedVals = PossibleReducedVals.second.takeVector(); 10900 SmallVector<SmallVector<Value *>> PossibleRedValsVect; 10901 for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end(); 10902 It != E; ++It) { 10903 PossibleRedValsVect.emplace_back(); 10904 auto RedValsVect = It->second.takeVector(); 10905 stable_sort(RedValsVect, [](const auto &P1, const auto &P2) { 10906 return P1.second < P2.second; 10907 }); 10908 for (const std::pair<Value *, unsigned> &Data : RedValsVect) 10909 PossibleRedValsVect.back().append(Data.second, Data.first); 10910 } 10911 stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) { 10912 return P1.size() > P2.size(); 10913 }); 10914 ReducedVals.emplace_back(); 10915 for (ArrayRef<Value *> Data : PossibleRedValsVect) 10916 ReducedVals.back().append(Data.rbegin(), Data.rend()); 10917 } 10918 // Sort the reduced values by number of same/alternate opcode and/or pointer 10919 // operand. 10920 stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) { 10921 return P1.size() > P2.size(); 10922 }); 10923 return true; 10924 } 10925 10926 /// Attempt to vectorize the tree found by matchAssociativeReduction. 10927 Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) { 10928 constexpr int ReductionLimit = 4; 10929 constexpr unsigned RegMaxNumber = 4; 10930 constexpr unsigned RedValsMaxNumber = 128; 10931 // If there are a sufficient number of reduction values, reduce 10932 // to a nearby power-of-2. We can safely generate oversized 10933 // vectors and rely on the backend to split them to legal sizes. 10934 unsigned NumReducedVals = std::accumulate( 10935 ReducedVals.begin(), ReducedVals.end(), 0, 10936 [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); }); 10937 if (NumReducedVals < ReductionLimit) 10938 return nullptr; 10939 10940 IRBuilder<> Builder(cast<Instruction>(ReductionRoot)); 10941 10942 // Track the reduced values in case if they are replaced by extractelement 10943 // because of the vectorization. 10944 DenseMap<Value *, WeakTrackingVH> TrackedVals; 10945 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues; 10946 // The same extra argument may be used several times, so log each attempt 10947 // to use it. 10948 for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) { 10949 assert(Pair.first && "DebugLoc must be set."); 10950 ExternallyUsedValues[Pair.second].push_back(Pair.first); 10951 TrackedVals.try_emplace(Pair.second, Pair.second); 10952 } 10953 10954 // The compare instruction of a min/max is the insertion point for new 10955 // instructions and may be replaced with a new compare instruction. 10956 auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) { 10957 assert(isa<SelectInst>(RdxRootInst) && 10958 "Expected min/max reduction to have select root instruction"); 10959 Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition(); 10960 assert(isa<Instruction>(ScalarCond) && 10961 "Expected min/max reduction to have compare condition"); 10962 return cast<Instruction>(ScalarCond); 10963 }; 10964 10965 // The reduction root is used as the insertion point for new instructions, 10966 // so set it as externally used to prevent it from being deleted. 10967 ExternallyUsedValues[ReductionRoot]; 10968 SmallDenseSet<Value *> IgnoreList; 10969 for (ReductionOpsType &RdxOps : ReductionOps) 10970 for (Value *RdxOp : RdxOps) { 10971 if (!RdxOp) 10972 continue; 10973 IgnoreList.insert(RdxOp); 10974 } 10975 bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot)); 10976 10977 // Need to track reduced vals, they may be changed during vectorization of 10978 // subvectors. 10979 for (ArrayRef<Value *> Candidates : ReducedVals) 10980 for (Value *V : Candidates) 10981 TrackedVals.try_emplace(V, V); 10982 10983 DenseMap<Value *, unsigned> VectorizedVals; 10984 Value *VectorizedTree = nullptr; 10985 bool CheckForReusedReductionOps = false; 10986 // Try to vectorize elements based on their type. 10987 for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) { 10988 ArrayRef<Value *> OrigReducedVals = ReducedVals[I]; 10989 InstructionsState S = getSameOpcode(OrigReducedVals); 10990 SmallVector<Value *> Candidates; 10991 DenseMap<Value *, Value *> TrackedToOrig; 10992 for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) { 10993 Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second; 10994 // Check if the reduction value was not overriden by the extractelement 10995 // instruction because of the vectorization and exclude it, if it is not 10996 // compatible with other values. 10997 if (auto *Inst = dyn_cast<Instruction>(RdxVal)) 10998 if (isVectorLikeInstWithConstOps(Inst) && 10999 (!S.getOpcode() || !S.isOpcodeOrAlt(Inst))) 11000 continue; 11001 Candidates.push_back(RdxVal); 11002 TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]); 11003 } 11004 bool ShuffledExtracts = false; 11005 // Try to handle shuffled extractelements. 11006 if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() && 11007 I + 1 < E) { 11008 InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]); 11009 if (NextS.getOpcode() == Instruction::ExtractElement && 11010 !NextS.isAltShuffle()) { 11011 SmallVector<Value *> CommonCandidates(Candidates); 11012 for (Value *RV : ReducedVals[I + 1]) { 11013 Value *RdxVal = TrackedVals.find(RV)->second; 11014 // Check if the reduction value was not overriden by the 11015 // extractelement instruction because of the vectorization and 11016 // exclude it, if it is not compatible with other values. 11017 if (auto *Inst = dyn_cast<Instruction>(RdxVal)) 11018 if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst)) 11019 continue; 11020 CommonCandidates.push_back(RdxVal); 11021 TrackedToOrig.try_emplace(RdxVal, RV); 11022 } 11023 SmallVector<int> Mask; 11024 if (isFixedVectorShuffle(CommonCandidates, Mask)) { 11025 ++I; 11026 Candidates.swap(CommonCandidates); 11027 ShuffledExtracts = true; 11028 } 11029 } 11030 } 11031 unsigned NumReducedVals = Candidates.size(); 11032 if (NumReducedVals < ReductionLimit) 11033 continue; 11034 11035 unsigned MaxVecRegSize = V.getMaxVecRegSize(); 11036 unsigned EltSize = V.getVectorElementSize(Candidates[0]); 11037 unsigned MaxElts = RegMaxNumber * PowerOf2Floor(MaxVecRegSize / EltSize); 11038 11039 unsigned ReduxWidth = std::min<unsigned>( 11040 PowerOf2Floor(NumReducedVals), std::max(RedValsMaxNumber, MaxElts)); 11041 unsigned Start = 0; 11042 unsigned Pos = Start; 11043 // Restarts vectorization attempt with lower vector factor. 11044 unsigned PrevReduxWidth = ReduxWidth; 11045 bool CheckForReusedReductionOpsLocal = false; 11046 auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals, 11047 &CheckForReusedReductionOpsLocal, 11048 &PrevReduxWidth, &V, 11049 &IgnoreList](bool IgnoreVL = false) { 11050 bool IsAnyRedOpGathered = !IgnoreVL && V.isAnyGathered(IgnoreList); 11051 if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) { 11052 // Check if any of the reduction ops are gathered. If so, worth 11053 // trying again with less number of reduction ops. 11054 CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered; 11055 } 11056 ++Pos; 11057 if (Pos < NumReducedVals - ReduxWidth + 1) 11058 return IsAnyRedOpGathered; 11059 Pos = Start; 11060 ReduxWidth /= 2; 11061 return IsAnyRedOpGathered; 11062 }; 11063 while (Pos < NumReducedVals - ReduxWidth + 1 && 11064 ReduxWidth >= ReductionLimit) { 11065 // Dependency in tree of the reduction ops - drop this attempt, try 11066 // later. 11067 if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth && 11068 Start == 0) { 11069 CheckForReusedReductionOps = true; 11070 break; 11071 } 11072 PrevReduxWidth = ReduxWidth; 11073 ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth); 11074 // Beeing analyzed already - skip. 11075 if (V.areAnalyzedReductionVals(VL)) { 11076 (void)AdjustReducedVals(/*IgnoreVL=*/true); 11077 continue; 11078 } 11079 // Early exit if any of the reduction values were deleted during 11080 // previous vectorization attempts. 11081 if (any_of(VL, [&V](Value *RedVal) { 11082 auto *RedValI = dyn_cast<Instruction>(RedVal); 11083 if (!RedValI) 11084 return false; 11085 return V.isDeleted(RedValI); 11086 })) 11087 break; 11088 V.buildTree(VL, IgnoreList); 11089 if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) { 11090 if (!AdjustReducedVals()) 11091 V.analyzedReductionVals(VL); 11092 continue; 11093 } 11094 if (V.isLoadCombineReductionCandidate(RdxKind)) { 11095 if (!AdjustReducedVals()) 11096 V.analyzedReductionVals(VL); 11097 continue; 11098 } 11099 V.reorderTopToBottom(); 11100 // No need to reorder the root node at all. 11101 V.reorderBottomToTop(/*IgnoreReorder=*/true); 11102 // Keep extracted other reduction values, if they are used in the 11103 // vectorization trees. 11104 BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues( 11105 ExternallyUsedValues); 11106 for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) { 11107 if (Cnt == I || (ShuffledExtracts && Cnt == I - 1)) 11108 continue; 11109 for_each(ReducedVals[Cnt], 11110 [&LocalExternallyUsedValues, &TrackedVals](Value *V) { 11111 if (isa<Instruction>(V)) 11112 LocalExternallyUsedValues[TrackedVals[V]]; 11113 }); 11114 } 11115 // Number of uses of the candidates in the vector of values. 11116 SmallDenseMap<Value *, unsigned> NumUses; 11117 for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) { 11118 Value *V = Candidates[Cnt]; 11119 if (NumUses.count(V) > 0) 11120 continue; 11121 NumUses[V] = std::count(VL.begin(), VL.end(), V); 11122 } 11123 for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) { 11124 Value *V = Candidates[Cnt]; 11125 if (NumUses.count(V) > 0) 11126 continue; 11127 NumUses[V] = std::count(VL.begin(), VL.end(), V); 11128 } 11129 // Gather externally used values. 11130 SmallPtrSet<Value *, 4> Visited; 11131 for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) { 11132 Value *V = Candidates[Cnt]; 11133 if (!Visited.insert(V).second) 11134 continue; 11135 unsigned NumOps = VectorizedVals.lookup(V) + NumUses[V]; 11136 if (NumOps != ReducedValsToOps.find(V)->second.size()) 11137 LocalExternallyUsedValues[V]; 11138 } 11139 for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) { 11140 Value *V = Candidates[Cnt]; 11141 if (!Visited.insert(V).second) 11142 continue; 11143 unsigned NumOps = VectorizedVals.lookup(V) + NumUses[V]; 11144 if (NumOps != ReducedValsToOps.find(V)->second.size()) 11145 LocalExternallyUsedValues[V]; 11146 } 11147 V.buildExternalUses(LocalExternallyUsedValues); 11148 11149 V.computeMinimumValueSizes(); 11150 11151 // Intersect the fast-math-flags from all reduction operations. 11152 FastMathFlags RdxFMF; 11153 RdxFMF.set(); 11154 for (Value *U : IgnoreList) 11155 if (auto *FPMO = dyn_cast<FPMathOperator>(U)) 11156 RdxFMF &= FPMO->getFastMathFlags(); 11157 // Estimate cost. 11158 InstructionCost TreeCost = V.getTreeCost(VL); 11159 InstructionCost ReductionCost = 11160 getReductionCost(TTI, VL, ReduxWidth, RdxFMF); 11161 InstructionCost Cost = TreeCost + ReductionCost; 11162 if (!Cost.isValid()) { 11163 LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n"); 11164 return nullptr; 11165 } 11166 if (Cost >= -SLPCostThreshold) { 11167 V.getORE()->emit([&]() { 11168 return OptimizationRemarkMissed( 11169 SV_NAME, "HorSLPNotBeneficial", 11170 ReducedValsToOps.find(VL[0])->second.front()) 11171 << "Vectorizing horizontal reduction is possible" 11172 << "but not beneficial with cost " << ore::NV("Cost", Cost) 11173 << " and threshold " 11174 << ore::NV("Threshold", -SLPCostThreshold); 11175 }); 11176 if (!AdjustReducedVals()) 11177 V.analyzedReductionVals(VL); 11178 continue; 11179 } 11180 11181 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" 11182 << Cost << ". (HorRdx)\n"); 11183 V.getORE()->emit([&]() { 11184 return OptimizationRemark( 11185 SV_NAME, "VectorizedHorizontalReduction", 11186 ReducedValsToOps.find(VL[0])->second.front()) 11187 << "Vectorized horizontal reduction with cost " 11188 << ore::NV("Cost", Cost) << " and with tree size " 11189 << ore::NV("TreeSize", V.getTreeSize()); 11190 }); 11191 11192 Builder.setFastMathFlags(RdxFMF); 11193 11194 // Vectorize a tree. 11195 Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues); 11196 11197 // Emit a reduction. If the root is a select (min/max idiom), the insert 11198 // point is the compare condition of that select. 11199 Instruction *RdxRootInst = cast<Instruction>(ReductionRoot); 11200 if (IsCmpSelMinMax) 11201 Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst)); 11202 else 11203 Builder.SetInsertPoint(RdxRootInst); 11204 11205 // To prevent poison from leaking across what used to be sequential, 11206 // safe, scalar boolean logic operations, the reduction operand must be 11207 // frozen. 11208 if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst)) 11209 VectorizedRoot = Builder.CreateFreeze(VectorizedRoot); 11210 11211 Value *ReducedSubTree = 11212 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI); 11213 11214 if (!VectorizedTree) { 11215 // Initialize the final value in the reduction. 11216 VectorizedTree = ReducedSubTree; 11217 } else { 11218 // Update the final value in the reduction. 11219 Builder.SetCurrentDebugLocation( 11220 cast<Instruction>(ReductionOps.front().front())->getDebugLoc()); 11221 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 11222 ReducedSubTree, "op.rdx", ReductionOps); 11223 } 11224 // Count vectorized reduced values to exclude them from final reduction. 11225 for (Value *V : VL) 11226 ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0) 11227 .first->getSecond(); 11228 Pos += ReduxWidth; 11229 Start = Pos; 11230 ReduxWidth = PowerOf2Floor(NumReducedVals - Pos); 11231 } 11232 } 11233 if (VectorizedTree) { 11234 // Finish the reduction. 11235 // Need to add extra arguments and not vectorized possible reduction 11236 // values. 11237 // Try to avoid dependencies between the scalar remainders after 11238 // reductions. 11239 auto &&FinalGen = 11240 [this, &Builder, 11241 &TrackedVals](ArrayRef<std::pair<Instruction *, Value *>> InstVals) { 11242 unsigned Sz = InstVals.size(); 11243 SmallVector<std::pair<Instruction *, Value *>> ExtraReds(Sz / 2 + 11244 Sz % 2); 11245 for (unsigned I = 0, E = (Sz / 2) * 2; I < E; I += 2) { 11246 Instruction *RedOp = InstVals[I + 1].first; 11247 Builder.SetCurrentDebugLocation(RedOp->getDebugLoc()); 11248 Value *RdxVal1 = InstVals[I].second; 11249 Value *StableRdxVal1 = RdxVal1; 11250 auto It1 = TrackedVals.find(RdxVal1); 11251 if (It1 != TrackedVals.end()) 11252 StableRdxVal1 = It1->second; 11253 Value *RdxVal2 = InstVals[I + 1].second; 11254 Value *StableRdxVal2 = RdxVal2; 11255 auto It2 = TrackedVals.find(RdxVal2); 11256 if (It2 != TrackedVals.end()) 11257 StableRdxVal2 = It2->second; 11258 Value *ExtraRed = createOp(Builder, RdxKind, StableRdxVal1, 11259 StableRdxVal2, "op.rdx", ReductionOps); 11260 ExtraReds[I / 2] = std::make_pair(InstVals[I].first, ExtraRed); 11261 } 11262 if (Sz % 2 == 1) 11263 ExtraReds[Sz / 2] = InstVals.back(); 11264 return ExtraReds; 11265 }; 11266 SmallVector<std::pair<Instruction *, Value *>> ExtraReductions; 11267 SmallPtrSet<Value *, 8> Visited; 11268 for (ArrayRef<Value *> Candidates : ReducedVals) { 11269 for (Value *RdxVal : Candidates) { 11270 if (!Visited.insert(RdxVal).second) 11271 continue; 11272 unsigned NumOps = VectorizedVals.lookup(RdxVal); 11273 for (Instruction *RedOp : 11274 makeArrayRef(ReducedValsToOps.find(RdxVal)->second) 11275 .drop_back(NumOps)) 11276 ExtraReductions.emplace_back(RedOp, RdxVal); 11277 } 11278 } 11279 for (auto &Pair : ExternallyUsedValues) { 11280 // Add each externally used value to the final reduction. 11281 for (auto *I : Pair.second) 11282 ExtraReductions.emplace_back(I, Pair.first); 11283 } 11284 // Iterate through all not-vectorized reduction values/extra arguments. 11285 while (ExtraReductions.size() > 1) { 11286 SmallVector<std::pair<Instruction *, Value *>> NewReds = 11287 FinalGen(ExtraReductions); 11288 ExtraReductions.swap(NewReds); 11289 } 11290 // Final reduction. 11291 if (ExtraReductions.size() == 1) { 11292 Instruction *RedOp = ExtraReductions.back().first; 11293 Builder.SetCurrentDebugLocation(RedOp->getDebugLoc()); 11294 Value *RdxVal = ExtraReductions.back().second; 11295 Value *StableRdxVal = RdxVal; 11296 auto It = TrackedVals.find(RdxVal); 11297 if (It != TrackedVals.end()) 11298 StableRdxVal = It->second; 11299 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 11300 StableRdxVal, "op.rdx", ReductionOps); 11301 } 11302 11303 ReductionRoot->replaceAllUsesWith(VectorizedTree); 11304 11305 // The original scalar reduction is expected to have no remaining 11306 // uses outside the reduction tree itself. Assert that we got this 11307 // correct, replace internal uses with undef, and mark for eventual 11308 // deletion. 11309 #ifndef NDEBUG 11310 SmallSet<Value *, 4> IgnoreSet; 11311 for (ArrayRef<Value *> RdxOps : ReductionOps) 11312 IgnoreSet.insert(RdxOps.begin(), RdxOps.end()); 11313 #endif 11314 for (ArrayRef<Value *> RdxOps : ReductionOps) { 11315 for (Value *Ignore : RdxOps) { 11316 if (!Ignore) 11317 continue; 11318 #ifndef NDEBUG 11319 for (auto *U : Ignore->users()) { 11320 assert(IgnoreSet.count(U) && 11321 "All users must be either in the reduction ops list."); 11322 } 11323 #endif 11324 if (!Ignore->use_empty()) { 11325 Value *Undef = UndefValue::get(Ignore->getType()); 11326 Ignore->replaceAllUsesWith(Undef); 11327 } 11328 V.eraseInstruction(cast<Instruction>(Ignore)); 11329 } 11330 } 11331 } else if (!CheckForReusedReductionOps) { 11332 for (ReductionOpsType &RdxOps : ReductionOps) 11333 for (Value *RdxOp : RdxOps) 11334 V.analyzedReductionRoot(cast<Instruction>(RdxOp)); 11335 } 11336 return VectorizedTree; 11337 } 11338 11339 private: 11340 /// Calculate the cost of a reduction. 11341 InstructionCost getReductionCost(TargetTransformInfo *TTI, 11342 ArrayRef<Value *> ReducedVals, 11343 unsigned ReduxWidth, FastMathFlags FMF) { 11344 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 11345 Value *FirstReducedVal = ReducedVals.front(); 11346 Type *ScalarTy = FirstReducedVal->getType(); 11347 FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth); 11348 InstructionCost VectorCost = 0, ScalarCost; 11349 // If all of the reduced values are constant, the vector cost is 0, since 11350 // the reduction value can be calculated at the compile time. 11351 bool AllConsts = all_of(ReducedVals, isConstant); 11352 switch (RdxKind) { 11353 case RecurKind::Add: 11354 case RecurKind::Mul: 11355 case RecurKind::Or: 11356 case RecurKind::And: 11357 case RecurKind::Xor: 11358 case RecurKind::FAdd: 11359 case RecurKind::FMul: { 11360 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind); 11361 if (!AllConsts) 11362 VectorCost = 11363 TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind); 11364 ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind); 11365 break; 11366 } 11367 case RecurKind::FMax: 11368 case RecurKind::FMin: { 11369 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 11370 if (!AllConsts) { 11371 auto *VecCondTy = 11372 cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 11373 VectorCost = 11374 TTI->getMinMaxReductionCost(VectorTy, VecCondTy, 11375 /*IsUnsigned=*/false, CostKind); 11376 } 11377 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 11378 ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy, 11379 SclCondTy, RdxPred, CostKind) + 11380 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 11381 SclCondTy, RdxPred, CostKind); 11382 break; 11383 } 11384 case RecurKind::SMax: 11385 case RecurKind::SMin: 11386 case RecurKind::UMax: 11387 case RecurKind::UMin: { 11388 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 11389 if (!AllConsts) { 11390 auto *VecCondTy = 11391 cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 11392 bool IsUnsigned = 11393 RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin; 11394 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, 11395 IsUnsigned, CostKind); 11396 } 11397 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 11398 ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy, 11399 SclCondTy, RdxPred, CostKind) + 11400 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 11401 SclCondTy, RdxPred, CostKind); 11402 break; 11403 } 11404 default: 11405 llvm_unreachable("Expected arithmetic or min/max reduction operation"); 11406 } 11407 11408 // Scalar cost is repeated for N-1 elements. 11409 ScalarCost *= (ReduxWidth - 1); 11410 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost 11411 << " for reduction that starts with " << *FirstReducedVal 11412 << " (It is a splitting reduction)\n"); 11413 return VectorCost - ScalarCost; 11414 } 11415 11416 /// Emit a horizontal reduction of the vectorized value. 11417 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder, 11418 unsigned ReduxWidth, const TargetTransformInfo *TTI) { 11419 assert(VectorizedValue && "Need to have a vectorized tree node"); 11420 assert(isPowerOf2_32(ReduxWidth) && 11421 "We only handle power-of-two reductions for now"); 11422 assert(RdxKind != RecurKind::FMulAdd && 11423 "A call to the llvm.fmuladd intrinsic is not handled yet"); 11424 11425 ++NumVectorInstructions; 11426 return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind); 11427 } 11428 }; 11429 11430 } // end anonymous namespace 11431 11432 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) { 11433 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) 11434 return cast<FixedVectorType>(IE->getType())->getNumElements(); 11435 11436 unsigned AggregateSize = 1; 11437 auto *IV = cast<InsertValueInst>(InsertInst); 11438 Type *CurrentType = IV->getType(); 11439 do { 11440 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 11441 for (auto *Elt : ST->elements()) 11442 if (Elt != ST->getElementType(0)) // check homogeneity 11443 return None; 11444 AggregateSize *= ST->getNumElements(); 11445 CurrentType = ST->getElementType(0); 11446 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 11447 AggregateSize *= AT->getNumElements(); 11448 CurrentType = AT->getElementType(); 11449 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) { 11450 AggregateSize *= VT->getNumElements(); 11451 return AggregateSize; 11452 } else if (CurrentType->isSingleValueType()) { 11453 return AggregateSize; 11454 } else { 11455 return None; 11456 } 11457 } while (true); 11458 } 11459 11460 static void findBuildAggregate_rec(Instruction *LastInsertInst, 11461 TargetTransformInfo *TTI, 11462 SmallVectorImpl<Value *> &BuildVectorOpds, 11463 SmallVectorImpl<Value *> &InsertElts, 11464 unsigned OperandOffset) { 11465 do { 11466 Value *InsertedOperand = LastInsertInst->getOperand(1); 11467 Optional<unsigned> OperandIndex = 11468 getInsertIndex(LastInsertInst, OperandOffset); 11469 if (!OperandIndex) 11470 return; 11471 if (isa<InsertElementInst>(InsertedOperand) || 11472 isa<InsertValueInst>(InsertedOperand)) { 11473 findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI, 11474 BuildVectorOpds, InsertElts, *OperandIndex); 11475 11476 } else { 11477 BuildVectorOpds[*OperandIndex] = InsertedOperand; 11478 InsertElts[*OperandIndex] = LastInsertInst; 11479 } 11480 LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0)); 11481 } while (LastInsertInst != nullptr && 11482 (isa<InsertValueInst>(LastInsertInst) || 11483 isa<InsertElementInst>(LastInsertInst)) && 11484 LastInsertInst->hasOneUse()); 11485 } 11486 11487 /// Recognize construction of vectors like 11488 /// %ra = insertelement <4 x float> poison, float %s0, i32 0 11489 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1 11490 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2 11491 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3 11492 /// starting from the last insertelement or insertvalue instruction. 11493 /// 11494 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>}, 11495 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on. 11496 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples. 11497 /// 11498 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type. 11499 /// 11500 /// \return true if it matches. 11501 static bool findBuildAggregate(Instruction *LastInsertInst, 11502 TargetTransformInfo *TTI, 11503 SmallVectorImpl<Value *> &BuildVectorOpds, 11504 SmallVectorImpl<Value *> &InsertElts) { 11505 11506 assert((isa<InsertElementInst>(LastInsertInst) || 11507 isa<InsertValueInst>(LastInsertInst)) && 11508 "Expected insertelement or insertvalue instruction!"); 11509 11510 assert((BuildVectorOpds.empty() && InsertElts.empty()) && 11511 "Expected empty result vectors!"); 11512 11513 Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst); 11514 if (!AggregateSize) 11515 return false; 11516 BuildVectorOpds.resize(*AggregateSize); 11517 InsertElts.resize(*AggregateSize); 11518 11519 findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0); 11520 llvm::erase_value(BuildVectorOpds, nullptr); 11521 llvm::erase_value(InsertElts, nullptr); 11522 if (BuildVectorOpds.size() >= 2) 11523 return true; 11524 11525 return false; 11526 } 11527 11528 /// Try and get a reduction value from a phi node. 11529 /// 11530 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions 11531 /// if they come from either \p ParentBB or a containing loop latch. 11532 /// 11533 /// \returns A candidate reduction value if possible, or \code nullptr \endcode 11534 /// if not possible. 11535 static Value *getReductionValue(const DominatorTree *DT, PHINode *P, 11536 BasicBlock *ParentBB, LoopInfo *LI) { 11537 // There are situations where the reduction value is not dominated by the 11538 // reduction phi. Vectorizing such cases has been reported to cause 11539 // miscompiles. See PR25787. 11540 auto DominatedReduxValue = [&](Value *R) { 11541 return isa<Instruction>(R) && 11542 DT->dominates(P->getParent(), cast<Instruction>(R)->getParent()); 11543 }; 11544 11545 Value *Rdx = nullptr; 11546 11547 // Return the incoming value if it comes from the same BB as the phi node. 11548 if (P->getIncomingBlock(0) == ParentBB) { 11549 Rdx = P->getIncomingValue(0); 11550 } else if (P->getIncomingBlock(1) == ParentBB) { 11551 Rdx = P->getIncomingValue(1); 11552 } 11553 11554 if (Rdx && DominatedReduxValue(Rdx)) 11555 return Rdx; 11556 11557 // Otherwise, check whether we have a loop latch to look at. 11558 Loop *BBL = LI->getLoopFor(ParentBB); 11559 if (!BBL) 11560 return nullptr; 11561 BasicBlock *BBLatch = BBL->getLoopLatch(); 11562 if (!BBLatch) 11563 return nullptr; 11564 11565 // There is a loop latch, return the incoming value if it comes from 11566 // that. This reduction pattern occasionally turns up. 11567 if (P->getIncomingBlock(0) == BBLatch) { 11568 Rdx = P->getIncomingValue(0); 11569 } else if (P->getIncomingBlock(1) == BBLatch) { 11570 Rdx = P->getIncomingValue(1); 11571 } 11572 11573 if (Rdx && DominatedReduxValue(Rdx)) 11574 return Rdx; 11575 11576 return nullptr; 11577 } 11578 11579 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) { 11580 if (match(I, m_BinOp(m_Value(V0), m_Value(V1)))) 11581 return true; 11582 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1)))) 11583 return true; 11584 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1)))) 11585 return true; 11586 if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1)))) 11587 return true; 11588 if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1)))) 11589 return true; 11590 if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1)))) 11591 return true; 11592 if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1)))) 11593 return true; 11594 return false; 11595 } 11596 11597 /// Attempt to reduce a horizontal reduction. 11598 /// If it is legal to match a horizontal reduction feeding the phi node \a P 11599 /// with reduction operators \a Root (or one of its operands) in a basic block 11600 /// \a BB, then check if it can be done. If horizontal reduction is not found 11601 /// and root instruction is a binary operation, vectorization of the operands is 11602 /// attempted. 11603 /// \returns true if a horizontal reduction was matched and reduced or operands 11604 /// of one of the binary instruction were vectorized. 11605 /// \returns false if a horizontal reduction was not matched (or not possible) 11606 /// or no vectorization of any binary operation feeding \a Root instruction was 11607 /// performed. 11608 static bool tryToVectorizeHorReductionOrInstOperands( 11609 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, 11610 TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL, 11611 const TargetLibraryInfo &TLI, 11612 const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) { 11613 if (!ShouldVectorizeHor) 11614 return false; 11615 11616 if (!Root) 11617 return false; 11618 11619 if (Root->getParent() != BB || isa<PHINode>(Root)) 11620 return false; 11621 // Start analysis starting from Root instruction. If horizontal reduction is 11622 // found, try to vectorize it. If it is not a horizontal reduction or 11623 // vectorization is not possible or not effective, and currently analyzed 11624 // instruction is a binary operation, try to vectorize the operands, using 11625 // pre-order DFS traversal order. If the operands were not vectorized, repeat 11626 // the same procedure considering each operand as a possible root of the 11627 // horizontal reduction. 11628 // Interrupt the process if the Root instruction itself was vectorized or all 11629 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized. 11630 // Skip the analysis of CmpInsts. Compiler implements postanalysis of the 11631 // CmpInsts so we can skip extra attempts in 11632 // tryToVectorizeHorReductionOrInstOperands and save compile time. 11633 std::queue<std::pair<Instruction *, unsigned>> Stack; 11634 Stack.emplace(Root, 0); 11635 SmallPtrSet<Value *, 8> VisitedInstrs; 11636 SmallVector<WeakTrackingVH> PostponedInsts; 11637 bool Res = false; 11638 auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst, 11639 Value *&B0, 11640 Value *&B1) -> Value * { 11641 if (R.isAnalyzedReductionRoot(Inst)) 11642 return nullptr; 11643 bool IsBinop = matchRdxBop(Inst, B0, B1); 11644 bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value())); 11645 if (IsBinop || IsSelect) { 11646 HorizontalReduction HorRdx; 11647 if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI)) 11648 return HorRdx.tryToReduce(R, TTI); 11649 } 11650 return nullptr; 11651 }; 11652 while (!Stack.empty()) { 11653 Instruction *Inst; 11654 unsigned Level; 11655 std::tie(Inst, Level) = Stack.front(); 11656 Stack.pop(); 11657 // Do not try to analyze instruction that has already been vectorized. 11658 // This may happen when we vectorize instruction operands on a previous 11659 // iteration while stack was populated before that happened. 11660 if (R.isDeleted(Inst)) 11661 continue; 11662 Value *B0 = nullptr, *B1 = nullptr; 11663 if (Value *V = TryToReduce(Inst, B0, B1)) { 11664 Res = true; 11665 // Set P to nullptr to avoid re-analysis of phi node in 11666 // matchAssociativeReduction function unless this is the root node. 11667 P = nullptr; 11668 if (auto *I = dyn_cast<Instruction>(V)) { 11669 // Try to find another reduction. 11670 Stack.emplace(I, Level); 11671 continue; 11672 } 11673 } else { 11674 bool IsBinop = B0 && B1; 11675 if (P && IsBinop) { 11676 Inst = dyn_cast<Instruction>(B0); 11677 if (Inst == P) 11678 Inst = dyn_cast<Instruction>(B1); 11679 if (!Inst) { 11680 // Set P to nullptr to avoid re-analysis of phi node in 11681 // matchAssociativeReduction function unless this is the root node. 11682 P = nullptr; 11683 continue; 11684 } 11685 } 11686 // Set P to nullptr to avoid re-analysis of phi node in 11687 // matchAssociativeReduction function unless this is the root node. 11688 P = nullptr; 11689 // Do not try to vectorize CmpInst operands, this is done separately. 11690 // Final attempt for binop args vectorization should happen after the loop 11691 // to try to find reductions. 11692 if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst)) 11693 PostponedInsts.push_back(Inst); 11694 } 11695 11696 // Try to vectorize operands. 11697 // Continue analysis for the instruction from the same basic block only to 11698 // save compile time. 11699 if (++Level < RecursionMaxDepth) 11700 for (auto *Op : Inst->operand_values()) 11701 if (VisitedInstrs.insert(Op).second) 11702 if (auto *I = dyn_cast<Instruction>(Op)) 11703 // Do not try to vectorize CmpInst operands, this is done 11704 // separately. 11705 if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) && 11706 !R.isDeleted(I) && I->getParent() == BB) 11707 Stack.emplace(I, Level); 11708 } 11709 // Try to vectorized binops where reductions were not found. 11710 for (Value *V : PostponedInsts) 11711 if (auto *Inst = dyn_cast<Instruction>(V)) 11712 if (!R.isDeleted(Inst)) 11713 Res |= Vectorize(Inst, R); 11714 return Res; 11715 } 11716 11717 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V, 11718 BasicBlock *BB, BoUpSLP &R, 11719 TargetTransformInfo *TTI) { 11720 auto *I = dyn_cast_or_null<Instruction>(V); 11721 if (!I) 11722 return false; 11723 11724 if (!isa<BinaryOperator>(I)) 11725 P = nullptr; 11726 // Try to match and vectorize a horizontal reduction. 11727 auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool { 11728 return tryToVectorize(I, R); 11729 }; 11730 return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL, 11731 *TLI, ExtraVectorization); 11732 } 11733 11734 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI, 11735 BasicBlock *BB, BoUpSLP &R) { 11736 const DataLayout &DL = BB->getModule()->getDataLayout(); 11737 if (!R.canMapToVector(IVI->getType(), DL)) 11738 return false; 11739 11740 SmallVector<Value *, 16> BuildVectorOpds; 11741 SmallVector<Value *, 16> BuildVectorInsts; 11742 if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts)) 11743 return false; 11744 11745 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n"); 11746 // Aggregate value is unlikely to be processed in vector register. 11747 return tryToVectorizeList(BuildVectorOpds, R); 11748 } 11749 11750 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI, 11751 BasicBlock *BB, BoUpSLP &R) { 11752 SmallVector<Value *, 16> BuildVectorInsts; 11753 SmallVector<Value *, 16> BuildVectorOpds; 11754 SmallVector<int> Mask; 11755 if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) || 11756 (llvm::all_of( 11757 BuildVectorOpds, 11758 [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) && 11759 isFixedVectorShuffle(BuildVectorOpds, Mask))) 11760 return false; 11761 11762 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n"); 11763 return tryToVectorizeList(BuildVectorInsts, R); 11764 } 11765 11766 template <typename T> 11767 static bool 11768 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming, 11769 function_ref<unsigned(T *)> Limit, 11770 function_ref<bool(T *, T *)> Comparator, 11771 function_ref<bool(T *, T *)> AreCompatible, 11772 function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper, 11773 bool LimitForRegisterSize) { 11774 bool Changed = false; 11775 // Sort by type, parent, operands. 11776 stable_sort(Incoming, Comparator); 11777 11778 // Try to vectorize elements base on their type. 11779 SmallVector<T *> Candidates; 11780 for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) { 11781 // Look for the next elements with the same type, parent and operand 11782 // kinds. 11783 auto *SameTypeIt = IncIt; 11784 while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt)) 11785 ++SameTypeIt; 11786 11787 // Try to vectorize them. 11788 unsigned NumElts = (SameTypeIt - IncIt); 11789 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes (" 11790 << NumElts << ")\n"); 11791 // The vectorization is a 3-state attempt: 11792 // 1. Try to vectorize instructions with the same/alternate opcodes with the 11793 // size of maximal register at first. 11794 // 2. Try to vectorize remaining instructions with the same type, if 11795 // possible. This may result in the better vectorization results rather than 11796 // if we try just to vectorize instructions with the same/alternate opcodes. 11797 // 3. Final attempt to try to vectorize all instructions with the 11798 // same/alternate ops only, this may result in some extra final 11799 // vectorization. 11800 if (NumElts > 1 && 11801 TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) { 11802 // Success start over because instructions might have been changed. 11803 Changed = true; 11804 } else if (NumElts < Limit(*IncIt) && 11805 (Candidates.empty() || 11806 Candidates.front()->getType() == (*IncIt)->getType())) { 11807 Candidates.append(IncIt, std::next(IncIt, NumElts)); 11808 } 11809 // Final attempt to vectorize instructions with the same types. 11810 if (Candidates.size() > 1 && 11811 (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) { 11812 if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) { 11813 // Success start over because instructions might have been changed. 11814 Changed = true; 11815 } else if (LimitForRegisterSize) { 11816 // Try to vectorize using small vectors. 11817 for (auto *It = Candidates.begin(), *End = Candidates.end(); 11818 It != End;) { 11819 auto *SameTypeIt = It; 11820 while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It)) 11821 ++SameTypeIt; 11822 unsigned NumElts = (SameTypeIt - It); 11823 if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts), 11824 /*LimitForRegisterSize=*/false)) 11825 Changed = true; 11826 It = SameTypeIt; 11827 } 11828 } 11829 Candidates.clear(); 11830 } 11831 11832 // Start over at the next instruction of a different type (or the end). 11833 IncIt = SameTypeIt; 11834 } 11835 return Changed; 11836 } 11837 11838 /// Compare two cmp instructions. If IsCompatibility is true, function returns 11839 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding 11840 /// operands. If IsCompatibility is false, function implements strict weak 11841 /// ordering relation between two cmp instructions, returning true if the first 11842 /// instruction is "less" than the second, i.e. its predicate is less than the 11843 /// predicate of the second or the operands IDs are less than the operands IDs 11844 /// of the second cmp instruction. 11845 template <bool IsCompatibility> 11846 static bool compareCmp(Value *V, Value *V2, 11847 function_ref<bool(Instruction *)> IsDeleted) { 11848 auto *CI1 = cast<CmpInst>(V); 11849 auto *CI2 = cast<CmpInst>(V2); 11850 if (IsDeleted(CI2) || !isValidElementType(CI2->getType())) 11851 return false; 11852 if (CI1->getOperand(0)->getType()->getTypeID() < 11853 CI2->getOperand(0)->getType()->getTypeID()) 11854 return !IsCompatibility; 11855 if (CI1->getOperand(0)->getType()->getTypeID() > 11856 CI2->getOperand(0)->getType()->getTypeID()) 11857 return false; 11858 CmpInst::Predicate Pred1 = CI1->getPredicate(); 11859 CmpInst::Predicate Pred2 = CI2->getPredicate(); 11860 CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1); 11861 CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2); 11862 CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1); 11863 CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2); 11864 if (BasePred1 < BasePred2) 11865 return !IsCompatibility; 11866 if (BasePred1 > BasePred2) 11867 return false; 11868 // Compare operands. 11869 bool LEPreds = Pred1 <= Pred2; 11870 bool GEPreds = Pred1 >= Pred2; 11871 for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) { 11872 auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1); 11873 auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1); 11874 if (Op1->getValueID() < Op2->getValueID()) 11875 return !IsCompatibility; 11876 if (Op1->getValueID() > Op2->getValueID()) 11877 return false; 11878 if (auto *I1 = dyn_cast<Instruction>(Op1)) 11879 if (auto *I2 = dyn_cast<Instruction>(Op2)) { 11880 if (I1->getParent() != I2->getParent()) 11881 return false; 11882 InstructionsState S = getSameOpcode({I1, I2}); 11883 if (S.getOpcode()) 11884 continue; 11885 return false; 11886 } 11887 } 11888 return IsCompatibility; 11889 } 11890 11891 bool SLPVectorizerPass::vectorizeSimpleInstructions( 11892 SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R, 11893 bool AtTerminator) { 11894 bool OpsChanged = false; 11895 SmallVector<Instruction *, 4> PostponedCmps; 11896 for (auto *I : reverse(Instructions)) { 11897 if (R.isDeleted(I)) 11898 continue; 11899 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) { 11900 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R); 11901 } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) { 11902 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R); 11903 } else if (isa<CmpInst>(I)) { 11904 PostponedCmps.push_back(I); 11905 continue; 11906 } 11907 // Try to find reductions in buildvector sequnces. 11908 OpsChanged |= vectorizeRootInstruction(nullptr, I, BB, R, TTI); 11909 } 11910 if (AtTerminator) { 11911 // Try to find reductions first. 11912 for (Instruction *I : PostponedCmps) { 11913 if (R.isDeleted(I)) 11914 continue; 11915 for (Value *Op : I->operands()) 11916 OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI); 11917 } 11918 // Try to vectorize operands as vector bundles. 11919 for (Instruction *I : PostponedCmps) { 11920 if (R.isDeleted(I)) 11921 continue; 11922 OpsChanged |= tryToVectorize(I, R); 11923 } 11924 // Try to vectorize list of compares. 11925 // Sort by type, compare predicate, etc. 11926 auto &&CompareSorter = [&R](Value *V, Value *V2) { 11927 return compareCmp<false>(V, V2, 11928 [&R](Instruction *I) { return R.isDeleted(I); }); 11929 }; 11930 11931 auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) { 11932 if (V1 == V2) 11933 return true; 11934 return compareCmp<true>(V1, V2, 11935 [&R](Instruction *I) { return R.isDeleted(I); }); 11936 }; 11937 auto Limit = [&R](Value *V) { 11938 unsigned EltSize = R.getVectorElementSize(V); 11939 return std::max(2U, R.getMaxVecRegSize() / EltSize); 11940 }; 11941 11942 SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end()); 11943 OpsChanged |= tryToVectorizeSequence<Value>( 11944 Vals, Limit, CompareSorter, AreCompatibleCompares, 11945 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 11946 // Exclude possible reductions from other blocks. 11947 bool ArePossiblyReducedInOtherBlock = 11948 any_of(Candidates, [](Value *V) { 11949 return any_of(V->users(), [V](User *U) { 11950 return isa<SelectInst>(U) && 11951 cast<SelectInst>(U)->getParent() != 11952 cast<Instruction>(V)->getParent(); 11953 }); 11954 }); 11955 if (ArePossiblyReducedInOtherBlock) 11956 return false; 11957 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 11958 }, 11959 /*LimitForRegisterSize=*/true); 11960 Instructions.clear(); 11961 } else { 11962 // Insert in reverse order since the PostponedCmps vector was filled in 11963 // reverse order. 11964 Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend()); 11965 } 11966 return OpsChanged; 11967 } 11968 11969 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { 11970 bool Changed = false; 11971 SmallVector<Value *, 4> Incoming; 11972 SmallPtrSet<Value *, 16> VisitedInstrs; 11973 // Maps phi nodes to the non-phi nodes found in the use tree for each phi 11974 // node. Allows better to identify the chains that can be vectorized in the 11975 // better way. 11976 DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes; 11977 auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) { 11978 assert(isValidElementType(V1->getType()) && 11979 isValidElementType(V2->getType()) && 11980 "Expected vectorizable types only."); 11981 // It is fine to compare type IDs here, since we expect only vectorizable 11982 // types, like ints, floats and pointers, we don't care about other type. 11983 if (V1->getType()->getTypeID() < V2->getType()->getTypeID()) 11984 return true; 11985 if (V1->getType()->getTypeID() > V2->getType()->getTypeID()) 11986 return false; 11987 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 11988 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 11989 if (Opcodes1.size() < Opcodes2.size()) 11990 return true; 11991 if (Opcodes1.size() > Opcodes2.size()) 11992 return false; 11993 Optional<bool> ConstOrder; 11994 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 11995 // Undefs are compatible with any other value. 11996 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) { 11997 if (!ConstOrder) 11998 ConstOrder = 11999 !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]); 12000 continue; 12001 } 12002 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 12003 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 12004 DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent()); 12005 DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent()); 12006 if (!NodeI1) 12007 return NodeI2 != nullptr; 12008 if (!NodeI2) 12009 return false; 12010 assert((NodeI1 == NodeI2) == 12011 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 12012 "Different nodes should have different DFS numbers"); 12013 if (NodeI1 != NodeI2) 12014 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 12015 InstructionsState S = getSameOpcode({I1, I2}); 12016 if (S.getOpcode()) 12017 continue; 12018 return I1->getOpcode() < I2->getOpcode(); 12019 } 12020 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) { 12021 if (!ConstOrder) 12022 ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID(); 12023 continue; 12024 } 12025 if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID()) 12026 return true; 12027 if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID()) 12028 return false; 12029 } 12030 return ConstOrder && *ConstOrder; 12031 }; 12032 auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) { 12033 if (V1 == V2) 12034 return true; 12035 if (V1->getType() != V2->getType()) 12036 return false; 12037 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 12038 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 12039 if (Opcodes1.size() != Opcodes2.size()) 12040 return false; 12041 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 12042 // Undefs are compatible with any other value. 12043 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) 12044 continue; 12045 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 12046 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 12047 if (I1->getParent() != I2->getParent()) 12048 return false; 12049 InstructionsState S = getSameOpcode({I1, I2}); 12050 if (S.getOpcode()) 12051 continue; 12052 return false; 12053 } 12054 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) 12055 continue; 12056 if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID()) 12057 return false; 12058 } 12059 return true; 12060 }; 12061 auto Limit = [&R](Value *V) { 12062 unsigned EltSize = R.getVectorElementSize(V); 12063 return std::max(2U, R.getMaxVecRegSize() / EltSize); 12064 }; 12065 12066 bool HaveVectorizedPhiNodes = false; 12067 do { 12068 // Collect the incoming values from the PHIs. 12069 Incoming.clear(); 12070 for (Instruction &I : *BB) { 12071 PHINode *P = dyn_cast<PHINode>(&I); 12072 if (!P) 12073 break; 12074 12075 // No need to analyze deleted, vectorized and non-vectorizable 12076 // instructions. 12077 if (!VisitedInstrs.count(P) && !R.isDeleted(P) && 12078 isValidElementType(P->getType())) 12079 Incoming.push_back(P); 12080 } 12081 12082 // Find the corresponding non-phi nodes for better matching when trying to 12083 // build the tree. 12084 for (Value *V : Incoming) { 12085 SmallVectorImpl<Value *> &Opcodes = 12086 PHIToOpcodes.try_emplace(V).first->getSecond(); 12087 if (!Opcodes.empty()) 12088 continue; 12089 SmallVector<Value *, 4> Nodes(1, V); 12090 SmallPtrSet<Value *, 4> Visited; 12091 while (!Nodes.empty()) { 12092 auto *PHI = cast<PHINode>(Nodes.pop_back_val()); 12093 if (!Visited.insert(PHI).second) 12094 continue; 12095 for (Value *V : PHI->incoming_values()) { 12096 if (auto *PHI1 = dyn_cast<PHINode>((V))) { 12097 Nodes.push_back(PHI1); 12098 continue; 12099 } 12100 Opcodes.emplace_back(V); 12101 } 12102 } 12103 } 12104 12105 HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>( 12106 Incoming, Limit, PHICompare, AreCompatiblePHIs, 12107 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 12108 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 12109 }, 12110 /*LimitForRegisterSize=*/true); 12111 Changed |= HaveVectorizedPhiNodes; 12112 VisitedInstrs.insert(Incoming.begin(), Incoming.end()); 12113 } while (HaveVectorizedPhiNodes); 12114 12115 VisitedInstrs.clear(); 12116 12117 SmallVector<Instruction *, 8> PostProcessInstructions; 12118 SmallDenseSet<Instruction *, 4> KeyNodes; 12119 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 12120 // Skip instructions with scalable type. The num of elements is unknown at 12121 // compile-time for scalable type. 12122 if (isa<ScalableVectorType>(it->getType())) 12123 continue; 12124 12125 // Skip instructions marked for the deletion. 12126 if (R.isDeleted(&*it)) 12127 continue; 12128 // We may go through BB multiple times so skip the one we have checked. 12129 if (!VisitedInstrs.insert(&*it).second) { 12130 if (it->use_empty() && KeyNodes.contains(&*it) && 12131 vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 12132 it->isTerminator())) { 12133 // We would like to start over since some instructions are deleted 12134 // and the iterator may become invalid value. 12135 Changed = true; 12136 it = BB->begin(); 12137 e = BB->end(); 12138 } 12139 continue; 12140 } 12141 12142 if (isa<DbgInfoIntrinsic>(it)) 12143 continue; 12144 12145 // Try to vectorize reductions that use PHINodes. 12146 if (PHINode *P = dyn_cast<PHINode>(it)) { 12147 // Check that the PHI is a reduction PHI. 12148 if (P->getNumIncomingValues() == 2) { 12149 // Try to match and vectorize a horizontal reduction. 12150 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R, 12151 TTI)) { 12152 Changed = true; 12153 it = BB->begin(); 12154 e = BB->end(); 12155 continue; 12156 } 12157 } 12158 // Try to vectorize the incoming values of the PHI, to catch reductions 12159 // that feed into PHIs. 12160 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) { 12161 // Skip if the incoming block is the current BB for now. Also, bypass 12162 // unreachable IR for efficiency and to avoid crashing. 12163 // TODO: Collect the skipped incoming values and try to vectorize them 12164 // after processing BB. 12165 if (BB == P->getIncomingBlock(I) || 12166 !DT->isReachableFromEntry(P->getIncomingBlock(I))) 12167 continue; 12168 12169 Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I), 12170 P->getIncomingBlock(I), R, TTI); 12171 } 12172 continue; 12173 } 12174 12175 // Ran into an instruction without users, like terminator, or function call 12176 // with ignored return value, store. Ignore unused instructions (basing on 12177 // instruction type, except for CallInst and InvokeInst). 12178 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) || 12179 isa<InvokeInst>(it))) { 12180 KeyNodes.insert(&*it); 12181 bool OpsChanged = false; 12182 if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) { 12183 for (auto *V : it->operand_values()) { 12184 // Try to match and vectorize a horizontal reduction. 12185 OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI); 12186 } 12187 } 12188 // Start vectorization of post-process list of instructions from the 12189 // top-tree instructions to try to vectorize as many instructions as 12190 // possible. 12191 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 12192 it->isTerminator()); 12193 if (OpsChanged) { 12194 // We would like to start over since some instructions are deleted 12195 // and the iterator may become invalid value. 12196 Changed = true; 12197 it = BB->begin(); 12198 e = BB->end(); 12199 continue; 12200 } 12201 } 12202 12203 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) || 12204 isa<InsertValueInst>(it)) 12205 PostProcessInstructions.push_back(&*it); 12206 } 12207 12208 return Changed; 12209 } 12210 12211 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) { 12212 auto Changed = false; 12213 for (auto &Entry : GEPs) { 12214 // If the getelementptr list has fewer than two elements, there's nothing 12215 // to do. 12216 if (Entry.second.size() < 2) 12217 continue; 12218 12219 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length " 12220 << Entry.second.size() << ".\n"); 12221 12222 // Process the GEP list in chunks suitable for the target's supported 12223 // vector size. If a vector register can't hold 1 element, we are done. We 12224 // are trying to vectorize the index computations, so the maximum number of 12225 // elements is based on the size of the index expression, rather than the 12226 // size of the GEP itself (the target's pointer size). 12227 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 12228 unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin()); 12229 if (MaxVecRegSize < EltSize) 12230 continue; 12231 12232 unsigned MaxElts = MaxVecRegSize / EltSize; 12233 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) { 12234 auto Len = std::min<unsigned>(BE - BI, MaxElts); 12235 ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len); 12236 12237 // Initialize a set a candidate getelementptrs. Note that we use a 12238 // SetVector here to preserve program order. If the index computations 12239 // are vectorizable and begin with loads, we want to minimize the chance 12240 // of having to reorder them later. 12241 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end()); 12242 12243 // Some of the candidates may have already been vectorized after we 12244 // initially collected them. If so, they are marked as deleted, so remove 12245 // them from the set of candidates. 12246 Candidates.remove_if( 12247 [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); }); 12248 12249 // Remove from the set of candidates all pairs of getelementptrs with 12250 // constant differences. Such getelementptrs are likely not good 12251 // candidates for vectorization in a bottom-up phase since one can be 12252 // computed from the other. We also ensure all candidate getelementptr 12253 // indices are unique. 12254 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) { 12255 auto *GEPI = GEPList[I]; 12256 if (!Candidates.count(GEPI)) 12257 continue; 12258 auto *SCEVI = SE->getSCEV(GEPList[I]); 12259 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) { 12260 auto *GEPJ = GEPList[J]; 12261 auto *SCEVJ = SE->getSCEV(GEPList[J]); 12262 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) { 12263 Candidates.remove(GEPI); 12264 Candidates.remove(GEPJ); 12265 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) { 12266 Candidates.remove(GEPJ); 12267 } 12268 } 12269 } 12270 12271 // We break out of the above computation as soon as we know there are 12272 // fewer than two candidates remaining. 12273 if (Candidates.size() < 2) 12274 continue; 12275 12276 // Add the single, non-constant index of each candidate to the bundle. We 12277 // ensured the indices met these constraints when we originally collected 12278 // the getelementptrs. 12279 SmallVector<Value *, 16> Bundle(Candidates.size()); 12280 auto BundleIndex = 0u; 12281 for (auto *V : Candidates) { 12282 auto *GEP = cast<GetElementPtrInst>(V); 12283 auto *GEPIdx = GEP->idx_begin()->get(); 12284 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)); 12285 Bundle[BundleIndex++] = GEPIdx; 12286 } 12287 12288 // Try and vectorize the indices. We are currently only interested in 12289 // gather-like cases of the form: 12290 // 12291 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ... 12292 // 12293 // where the loads of "a", the loads of "b", and the subtractions can be 12294 // performed in parallel. It's likely that detecting this pattern in a 12295 // bottom-up phase will be simpler and less costly than building a 12296 // full-blown top-down phase beginning at the consecutive loads. 12297 Changed |= tryToVectorizeList(Bundle, R); 12298 } 12299 } 12300 return Changed; 12301 } 12302 12303 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) { 12304 bool Changed = false; 12305 // Sort by type, base pointers and values operand. Value operands must be 12306 // compatible (have the same opcode, same parent), otherwise it is 12307 // definitely not profitable to try to vectorize them. 12308 auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) { 12309 if (V->getPointerOperandType()->getTypeID() < 12310 V2->getPointerOperandType()->getTypeID()) 12311 return true; 12312 if (V->getPointerOperandType()->getTypeID() > 12313 V2->getPointerOperandType()->getTypeID()) 12314 return false; 12315 // UndefValues are compatible with all other values. 12316 if (isa<UndefValue>(V->getValueOperand()) || 12317 isa<UndefValue>(V2->getValueOperand())) 12318 return false; 12319 if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand())) 12320 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 12321 DomTreeNodeBase<llvm::BasicBlock> *NodeI1 = 12322 DT->getNode(I1->getParent()); 12323 DomTreeNodeBase<llvm::BasicBlock> *NodeI2 = 12324 DT->getNode(I2->getParent()); 12325 assert(NodeI1 && "Should only process reachable instructions"); 12326 assert(NodeI2 && "Should only process reachable instructions"); 12327 assert((NodeI1 == NodeI2) == 12328 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 12329 "Different nodes should have different DFS numbers"); 12330 if (NodeI1 != NodeI2) 12331 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 12332 InstructionsState S = getSameOpcode({I1, I2}); 12333 if (S.getOpcode()) 12334 return false; 12335 return I1->getOpcode() < I2->getOpcode(); 12336 } 12337 if (isa<Constant>(V->getValueOperand()) && 12338 isa<Constant>(V2->getValueOperand())) 12339 return false; 12340 return V->getValueOperand()->getValueID() < 12341 V2->getValueOperand()->getValueID(); 12342 }; 12343 12344 auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) { 12345 if (V1 == V2) 12346 return true; 12347 if (V1->getPointerOperandType() != V2->getPointerOperandType()) 12348 return false; 12349 // Undefs are compatible with any other value. 12350 if (isa<UndefValue>(V1->getValueOperand()) || 12351 isa<UndefValue>(V2->getValueOperand())) 12352 return true; 12353 if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand())) 12354 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 12355 if (I1->getParent() != I2->getParent()) 12356 return false; 12357 InstructionsState S = getSameOpcode({I1, I2}); 12358 return S.getOpcode() > 0; 12359 } 12360 if (isa<Constant>(V1->getValueOperand()) && 12361 isa<Constant>(V2->getValueOperand())) 12362 return true; 12363 return V1->getValueOperand()->getValueID() == 12364 V2->getValueOperand()->getValueID(); 12365 }; 12366 auto Limit = [&R, this](StoreInst *SI) { 12367 unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType()); 12368 return R.getMinVF(EltSize); 12369 }; 12370 12371 // Attempt to sort and vectorize each of the store-groups. 12372 for (auto &Pair : Stores) { 12373 if (Pair.second.size() < 2) 12374 continue; 12375 12376 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " 12377 << Pair.second.size() << ".\n"); 12378 12379 if (!isValidElementType(Pair.second.front()->getValueOperand()->getType())) 12380 continue; 12381 12382 Changed |= tryToVectorizeSequence<StoreInst>( 12383 Pair.second, Limit, StoreSorter, AreCompatibleStores, 12384 [this, &R](ArrayRef<StoreInst *> Candidates, bool) { 12385 return vectorizeStores(Candidates, R); 12386 }, 12387 /*LimitForRegisterSize=*/false); 12388 } 12389 return Changed; 12390 } 12391 12392 char SLPVectorizer::ID = 0; 12393 12394 static const char lv_name[] = "SLP Vectorizer"; 12395 12396 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false) 12397 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 12398 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 12399 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 12400 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 12401 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 12402 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) 12403 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 12404 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy) 12405 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) 12406 12407 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); } 12408