1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive 10 // stores that can be put together into vector-stores. Next, it attempts to 11 // construct vectorizable tree using the use-def chains. If a profitable tree 12 // was found, the SLP vectorizer performs vectorization on the tree. 13 // 14 // The pass is inspired by the work described in the paper: 15 // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h" 20 #include "llvm/ADT/DenseMap.h" 21 #include "llvm/ADT/DenseSet.h" 22 #include "llvm/ADT/Optional.h" 23 #include "llvm/ADT/PostOrderIterator.h" 24 #include "llvm/ADT/PriorityQueue.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SetOperations.h" 27 #include "llvm/ADT/SetVector.h" 28 #include "llvm/ADT/SmallBitVector.h" 29 #include "llvm/ADT/SmallPtrSet.h" 30 #include "llvm/ADT/SmallSet.h" 31 #include "llvm/ADT/SmallString.h" 32 #include "llvm/ADT/Statistic.h" 33 #include "llvm/ADT/iterator.h" 34 #include "llvm/ADT/iterator_range.h" 35 #include "llvm/Analysis/AliasAnalysis.h" 36 #include "llvm/Analysis/AssumptionCache.h" 37 #include "llvm/Analysis/CodeMetrics.h" 38 #include "llvm/Analysis/DemandedBits.h" 39 #include "llvm/Analysis/GlobalsModRef.h" 40 #include "llvm/Analysis/IVDescriptors.h" 41 #include "llvm/Analysis/LoopAccessAnalysis.h" 42 #include "llvm/Analysis/LoopInfo.h" 43 #include "llvm/Analysis/MemoryLocation.h" 44 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 45 #include "llvm/Analysis/ScalarEvolution.h" 46 #include "llvm/Analysis/ScalarEvolutionExpressions.h" 47 #include "llvm/Analysis/TargetLibraryInfo.h" 48 #include "llvm/Analysis/TargetTransformInfo.h" 49 #include "llvm/Analysis/ValueTracking.h" 50 #include "llvm/Analysis/VectorUtils.h" 51 #include "llvm/IR/Attributes.h" 52 #include "llvm/IR/BasicBlock.h" 53 #include "llvm/IR/Constant.h" 54 #include "llvm/IR/Constants.h" 55 #include "llvm/IR/DataLayout.h" 56 #include "llvm/IR/DebugLoc.h" 57 #include "llvm/IR/DerivedTypes.h" 58 #include "llvm/IR/Dominators.h" 59 #include "llvm/IR/Function.h" 60 #include "llvm/IR/IRBuilder.h" 61 #include "llvm/IR/InstrTypes.h" 62 #include "llvm/IR/Instruction.h" 63 #include "llvm/IR/Instructions.h" 64 #include "llvm/IR/IntrinsicInst.h" 65 #include "llvm/IR/Intrinsics.h" 66 #include "llvm/IR/Module.h" 67 #include "llvm/IR/NoFolder.h" 68 #include "llvm/IR/Operator.h" 69 #include "llvm/IR/PatternMatch.h" 70 #include "llvm/IR/Type.h" 71 #include "llvm/IR/Use.h" 72 #include "llvm/IR/User.h" 73 #include "llvm/IR/Value.h" 74 #include "llvm/IR/ValueHandle.h" 75 #include "llvm/IR/Verifier.h" 76 #include "llvm/InitializePasses.h" 77 #include "llvm/Pass.h" 78 #include "llvm/Support/Casting.h" 79 #include "llvm/Support/CommandLine.h" 80 #include "llvm/Support/Compiler.h" 81 #include "llvm/Support/DOTGraphTraits.h" 82 #include "llvm/Support/Debug.h" 83 #include "llvm/Support/ErrorHandling.h" 84 #include "llvm/Support/GraphWriter.h" 85 #include "llvm/Support/InstructionCost.h" 86 #include "llvm/Support/KnownBits.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/raw_ostream.h" 89 #include "llvm/Transforms/Utils/InjectTLIMappings.h" 90 #include "llvm/Transforms/Utils/LoopUtils.h" 91 #include "llvm/Transforms/Vectorize.h" 92 #include <algorithm> 93 #include <cassert> 94 #include <cstdint> 95 #include <iterator> 96 #include <memory> 97 #include <set> 98 #include <string> 99 #include <tuple> 100 #include <utility> 101 #include <vector> 102 103 using namespace llvm; 104 using namespace llvm::PatternMatch; 105 using namespace slpvectorizer; 106 107 #define SV_NAME "slp-vectorizer" 108 #define DEBUG_TYPE "SLP" 109 110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated"); 111 112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden, 113 cl::desc("Run the SLP vectorization passes")); 114 115 static cl::opt<int> 116 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden, 117 cl::desc("Only vectorize if you gain more than this " 118 "number ")); 119 120 static cl::opt<bool> 121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden, 122 cl::desc("Attempt to vectorize horizontal reductions")); 123 124 static cl::opt<bool> ShouldStartVectorizeHorAtStore( 125 "slp-vectorize-hor-store", cl::init(false), cl::Hidden, 126 cl::desc( 127 "Attempt to vectorize horizontal reductions feeding into a store")); 128 129 static cl::opt<int> 130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden, 131 cl::desc("Attempt to vectorize for this register size in bits")); 132 133 static cl::opt<unsigned> 134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden, 135 cl::desc("Maximum SLP vectorization factor (0=unlimited)")); 136 137 static cl::opt<int> 138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden, 139 cl::desc("Maximum depth of the lookup for consecutive stores.")); 140 141 /// Limits the size of scheduling regions in a block. 142 /// It avoid long compile times for _very_ large blocks where vector 143 /// instructions are spread over a wide range. 144 /// This limit is way higher than needed by real-world functions. 145 static cl::opt<int> 146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden, 147 cl::desc("Limit the size of the SLP scheduling region per block")); 148 149 static cl::opt<int> MinVectorRegSizeOption( 150 "slp-min-reg-size", cl::init(128), cl::Hidden, 151 cl::desc("Attempt to vectorize for this register size in bits")); 152 153 static cl::opt<unsigned> RecursionMaxDepth( 154 "slp-recursion-max-depth", cl::init(12), cl::Hidden, 155 cl::desc("Limit the recursion depth when building a vectorizable tree")); 156 157 static cl::opt<unsigned> MinTreeSize( 158 "slp-min-tree-size", cl::init(3), cl::Hidden, 159 cl::desc("Only vectorize small trees if they are fully vectorizable")); 160 161 // The maximum depth that the look-ahead score heuristic will explore. 162 // The higher this value, the higher the compilation time overhead. 163 static cl::opt<int> LookAheadMaxDepth( 164 "slp-max-look-ahead-depth", cl::init(2), cl::Hidden, 165 cl::desc("The maximum look-ahead depth for operand reordering scores")); 166 167 static cl::opt<bool> 168 ViewSLPTree("view-slp-tree", cl::Hidden, 169 cl::desc("Display the SLP trees with Graphviz")); 170 171 // Limit the number of alias checks. The limit is chosen so that 172 // it has no negative effect on the llvm benchmarks. 173 static const unsigned AliasedCheckLimit = 10; 174 175 // Another limit for the alias checks: The maximum distance between load/store 176 // instructions where alias checks are done. 177 // This limit is useful for very large basic blocks. 178 static const unsigned MaxMemDepDistance = 160; 179 180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling 181 /// regions to be handled. 182 static const int MinScheduleRegionSize = 16; 183 184 /// Predicate for the element types that the SLP vectorizer supports. 185 /// 186 /// The most important thing to filter here are types which are invalid in LLVM 187 /// vectors. We also filter target specific types which have absolutely no 188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just 189 /// avoids spending time checking the cost model and realizing that they will 190 /// be inevitably scalarized. 191 static bool isValidElementType(Type *Ty) { 192 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() && 193 !Ty->isPPC_FP128Ty(); 194 } 195 196 /// \returns True if the value is a constant (but not globals/constant 197 /// expressions). 198 static bool isConstant(Value *V) { 199 return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V); 200 } 201 202 /// Checks if \p V is one of vector-like instructions, i.e. undef, 203 /// insertelement/extractelement with constant indices for fixed vector type or 204 /// extractvalue instruction. 205 static bool isVectorLikeInstWithConstOps(Value *V) { 206 if (!isa<InsertElementInst, ExtractElementInst>(V) && 207 !isa<ExtractValueInst, UndefValue>(V)) 208 return false; 209 auto *I = dyn_cast<Instruction>(V); 210 if (!I || isa<ExtractValueInst>(I)) 211 return true; 212 if (!isa<FixedVectorType>(I->getOperand(0)->getType())) 213 return false; 214 if (isa<ExtractElementInst>(I)) 215 return isConstant(I->getOperand(1)); 216 assert(isa<InsertElementInst>(V) && "Expected only insertelement."); 217 return isConstant(I->getOperand(2)); 218 } 219 220 /// \returns true if all of the instructions in \p VL are in the same block or 221 /// false otherwise. 222 static bool allSameBlock(ArrayRef<Value *> VL) { 223 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 224 if (!I0) 225 return false; 226 if (all_of(VL, isVectorLikeInstWithConstOps)) 227 return true; 228 229 BasicBlock *BB = I0->getParent(); 230 for (int I = 1, E = VL.size(); I < E; I++) { 231 auto *II = dyn_cast<Instruction>(VL[I]); 232 if (!II) 233 return false; 234 235 if (BB != II->getParent()) 236 return false; 237 } 238 return true; 239 } 240 241 /// \returns True if all of the values in \p VL are constants (but not 242 /// globals/constant expressions). 243 static bool allConstant(ArrayRef<Value *> VL) { 244 // Constant expressions and globals can't be vectorized like normal integer/FP 245 // constants. 246 return all_of(VL, isConstant); 247 } 248 249 /// \returns True if all of the values in \p VL are identical or some of them 250 /// are UndefValue. 251 static bool isSplat(ArrayRef<Value *> VL) { 252 Value *FirstNonUndef = nullptr; 253 for (Value *V : VL) { 254 if (isa<UndefValue>(V)) 255 continue; 256 if (!FirstNonUndef) { 257 FirstNonUndef = V; 258 continue; 259 } 260 if (V != FirstNonUndef) 261 return false; 262 } 263 return FirstNonUndef != nullptr; 264 } 265 266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator. 267 static bool isCommutative(Instruction *I) { 268 if (auto *Cmp = dyn_cast<CmpInst>(I)) 269 return Cmp->isCommutative(); 270 if (auto *BO = dyn_cast<BinaryOperator>(I)) 271 return BO->isCommutative(); 272 // TODO: This should check for generic Instruction::isCommutative(), but 273 // we need to confirm that the caller code correctly handles Intrinsics 274 // for example (does not have 2 operands). 275 return false; 276 } 277 278 /// Checks if the given value is actually an undefined constant vector. 279 static bool isUndefVector(const Value *V) { 280 if (isa<UndefValue>(V)) 281 return true; 282 auto *C = dyn_cast<Constant>(V); 283 if (!C) 284 return false; 285 if (!C->containsUndefOrPoisonElement()) 286 return false; 287 auto *VecTy = dyn_cast<FixedVectorType>(C->getType()); 288 if (!VecTy) 289 return false; 290 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) { 291 if (Constant *Elem = C->getAggregateElement(I)) 292 if (!isa<UndefValue>(Elem)) 293 return false; 294 } 295 return true; 296 } 297 298 /// Checks if the vector of instructions can be represented as a shuffle, like: 299 /// %x0 = extractelement <4 x i8> %x, i32 0 300 /// %x3 = extractelement <4 x i8> %x, i32 3 301 /// %y1 = extractelement <4 x i8> %y, i32 1 302 /// %y2 = extractelement <4 x i8> %y, i32 2 303 /// %x0x0 = mul i8 %x0, %x0 304 /// %x3x3 = mul i8 %x3, %x3 305 /// %y1y1 = mul i8 %y1, %y1 306 /// %y2y2 = mul i8 %y2, %y2 307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0 308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1 309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2 310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3 311 /// ret <4 x i8> %ins4 312 /// can be transformed into: 313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5, 314 /// i32 6> 315 /// %2 = mul <4 x i8> %1, %1 316 /// ret <4 x i8> %2 317 /// We convert this initially to something like: 318 /// %x0 = extractelement <4 x i8> %x, i32 0 319 /// %x3 = extractelement <4 x i8> %x, i32 3 320 /// %y1 = extractelement <4 x i8> %y, i32 1 321 /// %y2 = extractelement <4 x i8> %y, i32 2 322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0 323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1 324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2 325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3 326 /// %5 = mul <4 x i8> %4, %4 327 /// %6 = extractelement <4 x i8> %5, i32 0 328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0 329 /// %7 = extractelement <4 x i8> %5, i32 1 330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1 331 /// %8 = extractelement <4 x i8> %5, i32 2 332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2 333 /// %9 = extractelement <4 x i8> %5, i32 3 334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3 335 /// ret <4 x i8> %ins4 336 /// InstCombiner transforms this into a shuffle and vector mul 337 /// Mask will return the Shuffle Mask equivalent to the extracted elements. 338 /// TODO: Can we split off and reuse the shuffle mask detection from 339 /// TargetTransformInfo::getInstructionThroughput? 340 static Optional<TargetTransformInfo::ShuffleKind> 341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) { 342 const auto *It = 343 find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); }); 344 if (It == VL.end()) 345 return None; 346 auto *EI0 = cast<ExtractElementInst>(*It); 347 if (isa<ScalableVectorType>(EI0->getVectorOperandType())) 348 return None; 349 unsigned Size = 350 cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements(); 351 Value *Vec1 = nullptr; 352 Value *Vec2 = nullptr; 353 enum ShuffleMode { Unknown, Select, Permute }; 354 ShuffleMode CommonShuffleMode = Unknown; 355 Mask.assign(VL.size(), UndefMaskElem); 356 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 357 // Undef can be represented as an undef element in a vector. 358 if (isa<UndefValue>(VL[I])) 359 continue; 360 auto *EI = cast<ExtractElementInst>(VL[I]); 361 if (isa<ScalableVectorType>(EI->getVectorOperandType())) 362 return None; 363 auto *Vec = EI->getVectorOperand(); 364 // We can extractelement from undef or poison vector. 365 if (isUndefVector(Vec)) 366 continue; 367 // All vector operands must have the same number of vector elements. 368 if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size) 369 return None; 370 if (isa<UndefValue>(EI->getIndexOperand())) 371 continue; 372 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand()); 373 if (!Idx) 374 return None; 375 // Undefined behavior if Idx is negative or >= Size. 376 if (Idx->getValue().uge(Size)) 377 continue; 378 unsigned IntIdx = Idx->getValue().getZExtValue(); 379 Mask[I] = IntIdx; 380 // For correct shuffling we have to have at most 2 different vector operands 381 // in all extractelement instructions. 382 if (!Vec1 || Vec1 == Vec) { 383 Vec1 = Vec; 384 } else if (!Vec2 || Vec2 == Vec) { 385 Vec2 = Vec; 386 Mask[I] += Size; 387 } else { 388 return None; 389 } 390 if (CommonShuffleMode == Permute) 391 continue; 392 // If the extract index is not the same as the operation number, it is a 393 // permutation. 394 if (IntIdx != I) { 395 CommonShuffleMode = Permute; 396 continue; 397 } 398 CommonShuffleMode = Select; 399 } 400 // If we're not crossing lanes in different vectors, consider it as blending. 401 if (CommonShuffleMode == Select && Vec2) 402 return TargetTransformInfo::SK_Select; 403 // If Vec2 was never used, we have a permutation of a single vector, otherwise 404 // we have permutation of 2 vectors. 405 return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc 406 : TargetTransformInfo::SK_PermuteSingleSrc; 407 } 408 409 namespace { 410 411 /// Main data required for vectorization of instructions. 412 struct InstructionsState { 413 /// The very first instruction in the list with the main opcode. 414 Value *OpValue = nullptr; 415 416 /// The main/alternate instruction. 417 Instruction *MainOp = nullptr; 418 Instruction *AltOp = nullptr; 419 420 /// The main/alternate opcodes for the list of instructions. 421 unsigned getOpcode() const { 422 return MainOp ? MainOp->getOpcode() : 0; 423 } 424 425 unsigned getAltOpcode() const { 426 return AltOp ? AltOp->getOpcode() : 0; 427 } 428 429 /// Some of the instructions in the list have alternate opcodes. 430 bool isAltShuffle() const { return AltOp != MainOp; } 431 432 bool isOpcodeOrAlt(Instruction *I) const { 433 unsigned CheckedOpcode = I->getOpcode(); 434 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode; 435 } 436 437 InstructionsState() = delete; 438 InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp) 439 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {} 440 }; 441 442 } // end anonymous namespace 443 444 /// Chooses the correct key for scheduling data. If \p Op has the same (or 445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p 446 /// OpValue. 447 static Value *isOneOf(const InstructionsState &S, Value *Op) { 448 auto *I = dyn_cast<Instruction>(Op); 449 if (I && S.isOpcodeOrAlt(I)) 450 return Op; 451 return S.OpValue; 452 } 453 454 /// \returns true if \p Opcode is allowed as part of of the main/alternate 455 /// instruction for SLP vectorization. 456 /// 457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the 458 /// "shuffled out" lane would result in division by zero. 459 static bool isValidForAlternation(unsigned Opcode) { 460 if (Instruction::isIntDivRem(Opcode)) 461 return false; 462 463 return true; 464 } 465 466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 467 unsigned BaseIndex = 0); 468 469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e. 470 /// compatible instructions or constants, or just some other regular values. 471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0, 472 Value *Op1) { 473 return (isConstant(BaseOp0) && isConstant(Op0)) || 474 (isConstant(BaseOp1) && isConstant(Op1)) || 475 (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) && 476 !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) || 477 getSameOpcode({BaseOp0, Op0}).getOpcode() || 478 getSameOpcode({BaseOp1, Op1}).getOpcode(); 479 } 480 481 /// \returns analysis of the Instructions in \p VL described in 482 /// InstructionsState, the Opcode that we suppose the whole list 483 /// could be vectorized even if its structure is diverse. 484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 485 unsigned BaseIndex) { 486 // Make sure these are all Instructions. 487 if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); })) 488 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 489 490 bool IsCastOp = isa<CastInst>(VL[BaseIndex]); 491 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]); 492 bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]); 493 CmpInst::Predicate BasePred = 494 IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate() 495 : CmpInst::BAD_ICMP_PREDICATE; 496 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode(); 497 unsigned AltOpcode = Opcode; 498 unsigned AltIndex = BaseIndex; 499 500 // Check for one alternate opcode from another BinaryOperator. 501 // TODO - generalize to support all operators (types, calls etc.). 502 for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) { 503 unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode(); 504 if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) { 505 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 506 continue; 507 if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) && 508 isValidForAlternation(Opcode)) { 509 AltOpcode = InstOpcode; 510 AltIndex = Cnt; 511 continue; 512 } 513 } else if (IsCastOp && isa<CastInst>(VL[Cnt])) { 514 Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType(); 515 Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType(); 516 if (Ty0 == Ty1) { 517 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 518 continue; 519 if (Opcode == AltOpcode) { 520 assert(isValidForAlternation(Opcode) && 521 isValidForAlternation(InstOpcode) && 522 "Cast isn't safe for alternation, logic needs to be updated!"); 523 AltOpcode = InstOpcode; 524 AltIndex = Cnt; 525 continue; 526 } 527 } 528 } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) { 529 auto *BaseInst = cast<Instruction>(VL[BaseIndex]); 530 auto *Inst = cast<Instruction>(VL[Cnt]); 531 Type *Ty0 = BaseInst->getOperand(0)->getType(); 532 Type *Ty1 = Inst->getOperand(0)->getType(); 533 if (Ty0 == Ty1) { 534 Value *BaseOp0 = BaseInst->getOperand(0); 535 Value *BaseOp1 = BaseInst->getOperand(1); 536 Value *Op0 = Inst->getOperand(0); 537 Value *Op1 = Inst->getOperand(1); 538 CmpInst::Predicate CurrentPred = 539 cast<CmpInst>(VL[Cnt])->getPredicate(); 540 CmpInst::Predicate SwappedCurrentPred = 541 CmpInst::getSwappedPredicate(CurrentPred); 542 // Check for compatible operands. If the corresponding operands are not 543 // compatible - need to perform alternate vectorization. 544 if (InstOpcode == Opcode) { 545 if (BasePred == CurrentPred && 546 areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1)) 547 continue; 548 if (BasePred == SwappedCurrentPred && 549 areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0)) 550 continue; 551 if (E == 2 && 552 (BasePred == CurrentPred || BasePred == SwappedCurrentPred)) 553 continue; 554 auto *AltInst = cast<CmpInst>(VL[AltIndex]); 555 CmpInst::Predicate AltPred = AltInst->getPredicate(); 556 Value *AltOp0 = AltInst->getOperand(0); 557 Value *AltOp1 = AltInst->getOperand(1); 558 // Check if operands are compatible with alternate operands. 559 if (AltPred == CurrentPred && 560 areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1)) 561 continue; 562 if (AltPred == SwappedCurrentPred && 563 areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0)) 564 continue; 565 } 566 if (BaseIndex == AltIndex && BasePred != CurrentPred) { 567 assert(isValidForAlternation(Opcode) && 568 isValidForAlternation(InstOpcode) && 569 "Cast isn't safe for alternation, logic needs to be updated!"); 570 AltIndex = Cnt; 571 continue; 572 } 573 auto *AltInst = cast<CmpInst>(VL[AltIndex]); 574 CmpInst::Predicate AltPred = AltInst->getPredicate(); 575 if (BasePred == CurrentPred || BasePred == SwappedCurrentPred || 576 AltPred == CurrentPred || AltPred == SwappedCurrentPred) 577 continue; 578 } 579 } else if (InstOpcode == Opcode || InstOpcode == AltOpcode) 580 continue; 581 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 582 } 583 584 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]), 585 cast<Instruction>(VL[AltIndex])); 586 } 587 588 /// \returns true if all of the values in \p VL have the same type or false 589 /// otherwise. 590 static bool allSameType(ArrayRef<Value *> VL) { 591 Type *Ty = VL[0]->getType(); 592 for (int i = 1, e = VL.size(); i < e; i++) 593 if (VL[i]->getType() != Ty) 594 return false; 595 596 return true; 597 } 598 599 /// \returns True if Extract{Value,Element} instruction extracts element Idx. 600 static Optional<unsigned> getExtractIndex(Instruction *E) { 601 unsigned Opcode = E->getOpcode(); 602 assert((Opcode == Instruction::ExtractElement || 603 Opcode == Instruction::ExtractValue) && 604 "Expected extractelement or extractvalue instruction."); 605 if (Opcode == Instruction::ExtractElement) { 606 auto *CI = dyn_cast<ConstantInt>(E->getOperand(1)); 607 if (!CI) 608 return None; 609 return CI->getZExtValue(); 610 } 611 ExtractValueInst *EI = cast<ExtractValueInst>(E); 612 if (EI->getNumIndices() != 1) 613 return None; 614 return *EI->idx_begin(); 615 } 616 617 /// \returns True if in-tree use also needs extract. This refers to 618 /// possible scalar operand in vectorized instruction. 619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, 620 TargetLibraryInfo *TLI) { 621 unsigned Opcode = UserInst->getOpcode(); 622 switch (Opcode) { 623 case Instruction::Load: { 624 LoadInst *LI = cast<LoadInst>(UserInst); 625 return (LI->getPointerOperand() == Scalar); 626 } 627 case Instruction::Store: { 628 StoreInst *SI = cast<StoreInst>(UserInst); 629 return (SI->getPointerOperand() == Scalar); 630 } 631 case Instruction::Call: { 632 CallInst *CI = cast<CallInst>(UserInst); 633 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 634 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 635 if (hasVectorInstrinsicScalarOpd(ID, i)) 636 return (CI->getArgOperand(i) == Scalar); 637 } 638 LLVM_FALLTHROUGH; 639 } 640 default: 641 return false; 642 } 643 } 644 645 /// \returns the AA location that is being access by the instruction. 646 static MemoryLocation getLocation(Instruction *I) { 647 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 648 return MemoryLocation::get(SI); 649 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 650 return MemoryLocation::get(LI); 651 return MemoryLocation(); 652 } 653 654 /// \returns True if the instruction is not a volatile or atomic load/store. 655 static bool isSimple(Instruction *I) { 656 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 657 return LI->isSimple(); 658 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 659 return SI->isSimple(); 660 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) 661 return !MI->isVolatile(); 662 return true; 663 } 664 665 /// Shuffles \p Mask in accordance with the given \p SubMask. 666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) { 667 if (SubMask.empty()) 668 return; 669 if (Mask.empty()) { 670 Mask.append(SubMask.begin(), SubMask.end()); 671 return; 672 } 673 SmallVector<int> NewMask(SubMask.size(), UndefMaskElem); 674 int TermValue = std::min(Mask.size(), SubMask.size()); 675 for (int I = 0, E = SubMask.size(); I < E; ++I) { 676 if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem || 677 Mask[SubMask[I]] >= TermValue) 678 continue; 679 NewMask[I] = Mask[SubMask[I]]; 680 } 681 Mask.swap(NewMask); 682 } 683 684 /// Order may have elements assigned special value (size) which is out of 685 /// bounds. Such indices only appear on places which correspond to undef values 686 /// (see canReuseExtract for details) and used in order to avoid undef values 687 /// have effect on operands ordering. 688 /// The first loop below simply finds all unused indices and then the next loop 689 /// nest assigns these indices for undef values positions. 690 /// As an example below Order has two undef positions and they have assigned 691 /// values 3 and 7 respectively: 692 /// before: 6 9 5 4 9 2 1 0 693 /// after: 6 3 5 4 7 2 1 0 694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) { 695 const unsigned Sz = Order.size(); 696 SmallBitVector UnusedIndices(Sz, /*t=*/true); 697 SmallBitVector MaskedIndices(Sz); 698 for (unsigned I = 0; I < Sz; ++I) { 699 if (Order[I] < Sz) 700 UnusedIndices.reset(Order[I]); 701 else 702 MaskedIndices.set(I); 703 } 704 if (MaskedIndices.none()) 705 return; 706 assert(UnusedIndices.count() == MaskedIndices.count() && 707 "Non-synced masked/available indices."); 708 int Idx = UnusedIndices.find_first(); 709 int MIdx = MaskedIndices.find_first(); 710 while (MIdx >= 0) { 711 assert(Idx >= 0 && "Indices must be synced."); 712 Order[MIdx] = Idx; 713 Idx = UnusedIndices.find_next(Idx); 714 MIdx = MaskedIndices.find_next(MIdx); 715 } 716 } 717 718 namespace llvm { 719 720 static void inversePermutation(ArrayRef<unsigned> Indices, 721 SmallVectorImpl<int> &Mask) { 722 Mask.clear(); 723 const unsigned E = Indices.size(); 724 Mask.resize(E, UndefMaskElem); 725 for (unsigned I = 0; I < E; ++I) 726 Mask[Indices[I]] = I; 727 } 728 729 /// \returns inserting index of InsertElement or InsertValue instruction, 730 /// using Offset as base offset for index. 731 static Optional<int> getInsertIndex(Value *InsertInst, unsigned Offset) { 732 int Index = Offset; 733 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) { 734 if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) { 735 auto *VT = cast<FixedVectorType>(IE->getType()); 736 if (CI->getValue().uge(VT->getNumElements())) 737 return UndefMaskElem; 738 Index *= VT->getNumElements(); 739 Index += CI->getZExtValue(); 740 return Index; 741 } 742 if (isa<UndefValue>(IE->getOperand(2))) 743 return UndefMaskElem; 744 return None; 745 } 746 747 auto *IV = cast<InsertValueInst>(InsertInst); 748 Type *CurrentType = IV->getType(); 749 for (unsigned I : IV->indices()) { 750 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 751 Index *= ST->getNumElements(); 752 CurrentType = ST->getElementType(I); 753 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 754 Index *= AT->getNumElements(); 755 CurrentType = AT->getElementType(); 756 } else { 757 return None; 758 } 759 Index += I; 760 } 761 return Index; 762 } 763 764 /// Reorders the list of scalars in accordance with the given \p Order and then 765 /// the \p Mask. \p Order - is the original order of the scalars, need to 766 /// reorder scalars into an unordered state at first according to the given 767 /// order. Then the ordered scalars are shuffled once again in accordance with 768 /// the provided mask. 769 static void reorderScalars(SmallVectorImpl<Value *> &Scalars, 770 ArrayRef<int> Mask) { 771 assert(!Mask.empty() && "Expected non-empty mask."); 772 SmallVector<Value *> Prev(Scalars.size(), 773 UndefValue::get(Scalars.front()->getType())); 774 Prev.swap(Scalars); 775 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 776 if (Mask[I] != UndefMaskElem) 777 Scalars[Mask[I]] = Prev[I]; 778 } 779 780 namespace slpvectorizer { 781 782 /// Bottom Up SLP Vectorizer. 783 class BoUpSLP { 784 struct TreeEntry; 785 struct ScheduleData; 786 787 public: 788 using ValueList = SmallVector<Value *, 8>; 789 using InstrList = SmallVector<Instruction *, 16>; 790 using ValueSet = SmallPtrSet<Value *, 16>; 791 using StoreList = SmallVector<StoreInst *, 8>; 792 using ExtraValueToDebugLocsMap = 793 MapVector<Value *, SmallVector<Instruction *, 2>>; 794 using OrdersType = SmallVector<unsigned, 4>; 795 796 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, 797 TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li, 798 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB, 799 const DataLayout *DL, OptimizationRemarkEmitter *ORE) 800 : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC), 801 DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) { 802 CodeMetrics::collectEphemeralValues(F, AC, EphValues); 803 // Use the vector register size specified by the target unless overridden 804 // by a command-line option. 805 // TODO: It would be better to limit the vectorization factor based on 806 // data type rather than just register size. For example, x86 AVX has 807 // 256-bit registers, but it does not support integer operations 808 // at that width (that requires AVX2). 809 if (MaxVectorRegSizeOption.getNumOccurrences()) 810 MaxVecRegSize = MaxVectorRegSizeOption; 811 else 812 MaxVecRegSize = 813 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) 814 .getFixedSize(); 815 816 if (MinVectorRegSizeOption.getNumOccurrences()) 817 MinVecRegSize = MinVectorRegSizeOption; 818 else 819 MinVecRegSize = TTI->getMinVectorRegisterBitWidth(); 820 } 821 822 /// Vectorize the tree that starts with the elements in \p VL. 823 /// Returns the vectorized root. 824 Value *vectorizeTree(); 825 826 /// Vectorize the tree but with the list of externally used values \p 827 /// ExternallyUsedValues. Values in this MapVector can be replaced but the 828 /// generated extractvalue instructions. 829 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues); 830 831 /// \returns the cost incurred by unwanted spills and fills, caused by 832 /// holding live values over call sites. 833 InstructionCost getSpillCost() const; 834 835 /// \returns the vectorization cost of the subtree that starts at \p VL. 836 /// A negative number means that this is profitable. 837 InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None); 838 839 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for 840 /// the purpose of scheduling and extraction in the \p UserIgnoreLst. 841 void buildTree(ArrayRef<Value *> Roots, 842 ArrayRef<Value *> UserIgnoreLst = None); 843 844 /// Builds external uses of the vectorized scalars, i.e. the list of 845 /// vectorized scalars to be extracted, their lanes and their scalar users. \p 846 /// ExternallyUsedValues contains additional list of external uses to handle 847 /// vectorization of reductions. 848 void 849 buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {}); 850 851 /// Clear the internal data structures that are created by 'buildTree'. 852 void deleteTree() { 853 VectorizableTree.clear(); 854 ScalarToTreeEntry.clear(); 855 MustGather.clear(); 856 ExternalUses.clear(); 857 for (auto &Iter : BlocksSchedules) { 858 BlockScheduling *BS = Iter.second.get(); 859 BS->clear(); 860 } 861 MinBWs.clear(); 862 InstrElementSize.clear(); 863 } 864 865 unsigned getTreeSize() const { return VectorizableTree.size(); } 866 867 /// Perform LICM and CSE on the newly generated gather sequences. 868 void optimizeGatherSequence(); 869 870 /// Checks if the specified gather tree entry \p TE can be represented as a 871 /// shuffled vector entry + (possibly) permutation with other gathers. It 872 /// implements the checks only for possibly ordered scalars (Loads, 873 /// ExtractElement, ExtractValue), which can be part of the graph. 874 Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE); 875 876 /// Gets reordering data for the given tree entry. If the entry is vectorized 877 /// - just return ReorderIndices, otherwise check if the scalars can be 878 /// reordered and return the most optimal order. 879 /// \param TopToBottom If true, include the order of vectorized stores and 880 /// insertelement nodes, otherwise skip them. 881 Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom); 882 883 /// Reorders the current graph to the most profitable order starting from the 884 /// root node to the leaf nodes. The best order is chosen only from the nodes 885 /// of the same size (vectorization factor). Smaller nodes are considered 886 /// parts of subgraph with smaller VF and they are reordered independently. We 887 /// can make it because we still need to extend smaller nodes to the wider VF 888 /// and we can merge reordering shuffles with the widening shuffles. 889 void reorderTopToBottom(); 890 891 /// Reorders the current graph to the most profitable order starting from 892 /// leaves to the root. It allows to rotate small subgraphs and reduce the 893 /// number of reshuffles if the leaf nodes use the same order. In this case we 894 /// can merge the orders and just shuffle user node instead of shuffling its 895 /// operands. Plus, even the leaf nodes have different orders, it allows to 896 /// sink reordering in the graph closer to the root node and merge it later 897 /// during analysis. 898 void reorderBottomToTop(bool IgnoreReorder = false); 899 900 /// \return The vector element size in bits to use when vectorizing the 901 /// expression tree ending at \p V. If V is a store, the size is the width of 902 /// the stored value. Otherwise, the size is the width of the largest loaded 903 /// value reaching V. This method is used by the vectorizer to calculate 904 /// vectorization factors. 905 unsigned getVectorElementSize(Value *V); 906 907 /// Compute the minimum type sizes required to represent the entries in a 908 /// vectorizable tree. 909 void computeMinimumValueSizes(); 910 911 // \returns maximum vector register size as set by TTI or overridden by cl::opt. 912 unsigned getMaxVecRegSize() const { 913 return MaxVecRegSize; 914 } 915 916 // \returns minimum vector register size as set by cl::opt. 917 unsigned getMinVecRegSize() const { 918 return MinVecRegSize; 919 } 920 921 unsigned getMinVF(unsigned Sz) const { 922 return std::max(2U, getMinVecRegSize() / Sz); 923 } 924 925 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const { 926 unsigned MaxVF = MaxVFOption.getNumOccurrences() ? 927 MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode); 928 return MaxVF ? MaxVF : UINT_MAX; 929 } 930 931 /// Check if homogeneous aggregate is isomorphic to some VectorType. 932 /// Accepts homogeneous multidimensional aggregate of scalars/vectors like 933 /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> }, 934 /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on. 935 /// 936 /// \returns number of elements in vector if isomorphism exists, 0 otherwise. 937 unsigned canMapToVector(Type *T, const DataLayout &DL) const; 938 939 /// \returns True if the VectorizableTree is both tiny and not fully 940 /// vectorizable. We do not vectorize such trees. 941 bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const; 942 943 /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values 944 /// can be load combined in the backend. Load combining may not be allowed in 945 /// the IR optimizer, so we do not want to alter the pattern. For example, 946 /// partially transforming a scalar bswap() pattern into vector code is 947 /// effectively impossible for the backend to undo. 948 /// TODO: If load combining is allowed in the IR optimizer, this analysis 949 /// may not be necessary. 950 bool isLoadCombineReductionCandidate(RecurKind RdxKind) const; 951 952 /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values 953 /// can be load combined in the backend. Load combining may not be allowed in 954 /// the IR optimizer, so we do not want to alter the pattern. For example, 955 /// partially transforming a scalar bswap() pattern into vector code is 956 /// effectively impossible for the backend to undo. 957 /// TODO: If load combining is allowed in the IR optimizer, this analysis 958 /// may not be necessary. 959 bool isLoadCombineCandidate() const; 960 961 OptimizationRemarkEmitter *getORE() { return ORE; } 962 963 /// This structure holds any data we need about the edges being traversed 964 /// during buildTree_rec(). We keep track of: 965 /// (i) the user TreeEntry index, and 966 /// (ii) the index of the edge. 967 struct EdgeInfo { 968 EdgeInfo() = default; 969 EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx) 970 : UserTE(UserTE), EdgeIdx(EdgeIdx) {} 971 /// The user TreeEntry. 972 TreeEntry *UserTE = nullptr; 973 /// The operand index of the use. 974 unsigned EdgeIdx = UINT_MAX; 975 #ifndef NDEBUG 976 friend inline raw_ostream &operator<<(raw_ostream &OS, 977 const BoUpSLP::EdgeInfo &EI) { 978 EI.dump(OS); 979 return OS; 980 } 981 /// Debug print. 982 void dump(raw_ostream &OS) const { 983 OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null") 984 << " EdgeIdx:" << EdgeIdx << "}"; 985 } 986 LLVM_DUMP_METHOD void dump() const { dump(dbgs()); } 987 #endif 988 }; 989 990 /// A helper data structure to hold the operands of a vector of instructions. 991 /// This supports a fixed vector length for all operand vectors. 992 class VLOperands { 993 /// For each operand we need (i) the value, and (ii) the opcode that it 994 /// would be attached to if the expression was in a left-linearized form. 995 /// This is required to avoid illegal operand reordering. 996 /// For example: 997 /// \verbatim 998 /// 0 Op1 999 /// |/ 1000 /// Op1 Op2 Linearized + Op2 1001 /// \ / ----------> |/ 1002 /// - - 1003 /// 1004 /// Op1 - Op2 (0 + Op1) - Op2 1005 /// \endverbatim 1006 /// 1007 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'. 1008 /// 1009 /// Another way to think of this is to track all the operations across the 1010 /// path from the operand all the way to the root of the tree and to 1011 /// calculate the operation that corresponds to this path. For example, the 1012 /// path from Op2 to the root crosses the RHS of the '-', therefore the 1013 /// corresponding operation is a '-' (which matches the one in the 1014 /// linearized tree, as shown above). 1015 /// 1016 /// For lack of a better term, we refer to this operation as Accumulated 1017 /// Path Operation (APO). 1018 struct OperandData { 1019 OperandData() = default; 1020 OperandData(Value *V, bool APO, bool IsUsed) 1021 : V(V), APO(APO), IsUsed(IsUsed) {} 1022 /// The operand value. 1023 Value *V = nullptr; 1024 /// TreeEntries only allow a single opcode, or an alternate sequence of 1025 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the 1026 /// APO. It is set to 'true' if 'V' is attached to an inverse operation 1027 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise 1028 /// (e.g., Add/Mul) 1029 bool APO = false; 1030 /// Helper data for the reordering function. 1031 bool IsUsed = false; 1032 }; 1033 1034 /// During operand reordering, we are trying to select the operand at lane 1035 /// that matches best with the operand at the neighboring lane. Our 1036 /// selection is based on the type of value we are looking for. For example, 1037 /// if the neighboring lane has a load, we need to look for a load that is 1038 /// accessing a consecutive address. These strategies are summarized in the 1039 /// 'ReorderingMode' enumerator. 1040 enum class ReorderingMode { 1041 Load, ///< Matching loads to consecutive memory addresses 1042 Opcode, ///< Matching instructions based on opcode (same or alternate) 1043 Constant, ///< Matching constants 1044 Splat, ///< Matching the same instruction multiple times (broadcast) 1045 Failed, ///< We failed to create a vectorizable group 1046 }; 1047 1048 using OperandDataVec = SmallVector<OperandData, 2>; 1049 1050 /// A vector of operand vectors. 1051 SmallVector<OperandDataVec, 4> OpsVec; 1052 1053 const DataLayout &DL; 1054 ScalarEvolution &SE; 1055 const BoUpSLP &R; 1056 1057 /// \returns the operand data at \p OpIdx and \p Lane. 1058 OperandData &getData(unsigned OpIdx, unsigned Lane) { 1059 return OpsVec[OpIdx][Lane]; 1060 } 1061 1062 /// \returns the operand data at \p OpIdx and \p Lane. Const version. 1063 const OperandData &getData(unsigned OpIdx, unsigned Lane) const { 1064 return OpsVec[OpIdx][Lane]; 1065 } 1066 1067 /// Clears the used flag for all entries. 1068 void clearUsed() { 1069 for (unsigned OpIdx = 0, NumOperands = getNumOperands(); 1070 OpIdx != NumOperands; ++OpIdx) 1071 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes; 1072 ++Lane) 1073 OpsVec[OpIdx][Lane].IsUsed = false; 1074 } 1075 1076 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2. 1077 void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) { 1078 std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]); 1079 } 1080 1081 // The hard-coded scores listed here are not very important, though it shall 1082 // be higher for better matches to improve the resulting cost. When 1083 // computing the scores of matching one sub-tree with another, we are 1084 // basically counting the number of values that are matching. So even if all 1085 // scores are set to 1, we would still get a decent matching result. 1086 // However, sometimes we have to break ties. For example we may have to 1087 // choose between matching loads vs matching opcodes. This is what these 1088 // scores are helping us with: they provide the order of preference. Also, 1089 // this is important if the scalar is externally used or used in another 1090 // tree entry node in the different lane. 1091 1092 /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]). 1093 static const int ScoreConsecutiveLoads = 4; 1094 /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]). 1095 static const int ScoreReversedLoads = 3; 1096 /// ExtractElementInst from same vector and consecutive indexes. 1097 static const int ScoreConsecutiveExtracts = 4; 1098 /// ExtractElementInst from same vector and reversed indices. 1099 static const int ScoreReversedExtracts = 3; 1100 /// Constants. 1101 static const int ScoreConstants = 2; 1102 /// Instructions with the same opcode. 1103 static const int ScoreSameOpcode = 2; 1104 /// Instructions with alt opcodes (e.g, add + sub). 1105 static const int ScoreAltOpcodes = 1; 1106 /// Identical instructions (a.k.a. splat or broadcast). 1107 static const int ScoreSplat = 1; 1108 /// Matching with an undef is preferable to failing. 1109 static const int ScoreUndef = 1; 1110 /// Score for failing to find a decent match. 1111 static const int ScoreFail = 0; 1112 /// Score if all users are vectorized. 1113 static const int ScoreAllUserVectorized = 1; 1114 1115 /// \returns the score of placing \p V1 and \p V2 in consecutive lanes. 1116 /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p 1117 /// MainAltOps. 1118 static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL, 1119 ScalarEvolution &SE, int NumLanes, 1120 ArrayRef<Value *> MainAltOps) { 1121 if (V1 == V2) 1122 return VLOperands::ScoreSplat; 1123 1124 auto *LI1 = dyn_cast<LoadInst>(V1); 1125 auto *LI2 = dyn_cast<LoadInst>(V2); 1126 if (LI1 && LI2) { 1127 if (LI1->getParent() != LI2->getParent()) 1128 return VLOperands::ScoreFail; 1129 1130 Optional<int> Dist = getPointersDiff( 1131 LI1->getType(), LI1->getPointerOperand(), LI2->getType(), 1132 LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true); 1133 if (!Dist || *Dist == 0) 1134 return VLOperands::ScoreFail; 1135 // The distance is too large - still may be profitable to use masked 1136 // loads/gathers. 1137 if (std::abs(*Dist) > NumLanes / 2) 1138 return VLOperands::ScoreAltOpcodes; 1139 // This still will detect consecutive loads, but we might have "holes" 1140 // in some cases. It is ok for non-power-2 vectorization and may produce 1141 // better results. It should not affect current vectorization. 1142 return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads 1143 : VLOperands::ScoreReversedLoads; 1144 } 1145 1146 auto *C1 = dyn_cast<Constant>(V1); 1147 auto *C2 = dyn_cast<Constant>(V2); 1148 if (C1 && C2) 1149 return VLOperands::ScoreConstants; 1150 1151 // Extracts from consecutive indexes of the same vector better score as 1152 // the extracts could be optimized away. 1153 Value *EV1; 1154 ConstantInt *Ex1Idx; 1155 if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) { 1156 // Undefs are always profitable for extractelements. 1157 if (isa<UndefValue>(V2)) 1158 return VLOperands::ScoreConsecutiveExtracts; 1159 Value *EV2 = nullptr; 1160 ConstantInt *Ex2Idx = nullptr; 1161 if (match(V2, 1162 m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx), 1163 m_Undef())))) { 1164 // Undefs are always profitable for extractelements. 1165 if (!Ex2Idx) 1166 return VLOperands::ScoreConsecutiveExtracts; 1167 if (isUndefVector(EV2) && EV2->getType() == EV1->getType()) 1168 return VLOperands::ScoreConsecutiveExtracts; 1169 if (EV2 == EV1) { 1170 int Idx1 = Ex1Idx->getZExtValue(); 1171 int Idx2 = Ex2Idx->getZExtValue(); 1172 int Dist = Idx2 - Idx1; 1173 // The distance is too large - still may be profitable to use 1174 // shuffles. 1175 if (std::abs(Dist) == 0) 1176 return VLOperands::ScoreSplat; 1177 if (std::abs(Dist) > NumLanes / 2) 1178 return VLOperands::ScoreSameOpcode; 1179 return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts 1180 : VLOperands::ScoreReversedExtracts; 1181 } 1182 return VLOperands::ScoreAltOpcodes; 1183 } 1184 return VLOperands::ScoreFail; 1185 } 1186 1187 auto *I1 = dyn_cast<Instruction>(V1); 1188 auto *I2 = dyn_cast<Instruction>(V2); 1189 if (I1 && I2) { 1190 if (I1->getParent() != I2->getParent()) 1191 return VLOperands::ScoreFail; 1192 SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end()); 1193 Ops.push_back(I1); 1194 Ops.push_back(I2); 1195 InstructionsState S = getSameOpcode(Ops); 1196 // Note: Only consider instructions with <= 2 operands to avoid 1197 // complexity explosion. 1198 if (S.getOpcode() && 1199 (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() || 1200 !S.isAltShuffle()) && 1201 all_of(Ops, [&S](Value *V) { 1202 return cast<Instruction>(V)->getNumOperands() == 1203 S.MainOp->getNumOperands(); 1204 })) 1205 return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes 1206 : VLOperands::ScoreSameOpcode; 1207 } 1208 1209 if (isa<UndefValue>(V2)) 1210 return VLOperands::ScoreUndef; 1211 1212 return VLOperands::ScoreFail; 1213 } 1214 1215 /// \param Lane lane of the operands under analysis. 1216 /// \param OpIdx operand index in \p Lane lane we're looking the best 1217 /// candidate for. 1218 /// \param Idx operand index of the current candidate value. 1219 /// \returns The additional score due to possible broadcasting of the 1220 /// elements in the lane. It is more profitable to have power-of-2 unique 1221 /// elements in the lane, it will be vectorized with higher probability 1222 /// after removing duplicates. Currently the SLP vectorizer supports only 1223 /// vectorization of the power-of-2 number of unique scalars. 1224 int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { 1225 Value *IdxLaneV = getData(Idx, Lane).V; 1226 if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V) 1227 return 0; 1228 SmallPtrSet<Value *, 4> Uniques; 1229 for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) { 1230 if (Ln == Lane) 1231 continue; 1232 Value *OpIdxLnV = getData(OpIdx, Ln).V; 1233 if (!isa<Instruction>(OpIdxLnV)) 1234 return 0; 1235 Uniques.insert(OpIdxLnV); 1236 } 1237 int UniquesCount = Uniques.size(); 1238 int UniquesCntWithIdxLaneV = 1239 Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1; 1240 Value *OpIdxLaneV = getData(OpIdx, Lane).V; 1241 int UniquesCntWithOpIdxLaneV = 1242 Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1; 1243 if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV) 1244 return 0; 1245 return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) - 1246 UniquesCntWithOpIdxLaneV) - 1247 (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV); 1248 } 1249 1250 /// \param Lane lane of the operands under analysis. 1251 /// \param OpIdx operand index in \p Lane lane we're looking the best 1252 /// candidate for. 1253 /// \param Idx operand index of the current candidate value. 1254 /// \returns The additional score for the scalar which users are all 1255 /// vectorized. 1256 int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { 1257 Value *IdxLaneV = getData(Idx, Lane).V; 1258 Value *OpIdxLaneV = getData(OpIdx, Lane).V; 1259 // Do not care about number of uses for vector-like instructions 1260 // (extractelement/extractvalue with constant indices), they are extracts 1261 // themselves and already externally used. Vectorization of such 1262 // instructions does not add extra extractelement instruction, just may 1263 // remove it. 1264 if (isVectorLikeInstWithConstOps(IdxLaneV) && 1265 isVectorLikeInstWithConstOps(OpIdxLaneV)) 1266 return VLOperands::ScoreAllUserVectorized; 1267 auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV); 1268 if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV)) 1269 return 0; 1270 return R.areAllUsersVectorized(IdxLaneI, None) 1271 ? VLOperands::ScoreAllUserVectorized 1272 : 0; 1273 } 1274 1275 /// Go through the operands of \p LHS and \p RHS recursively until \p 1276 /// MaxLevel, and return the cummulative score. For example: 1277 /// \verbatim 1278 /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1] 1279 /// \ / \ / \ / \ / 1280 /// + + + + 1281 /// G1 G2 G3 G4 1282 /// \endverbatim 1283 /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at 1284 /// each level recursively, accumulating the score. It starts from matching 1285 /// the additions at level 0, then moves on to the loads (level 1). The 1286 /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and 1287 /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while 1288 /// {A[0],C[0]} has a score of VLOperands::ScoreFail. 1289 /// Please note that the order of the operands does not matter, as we 1290 /// evaluate the score of all profitable combinations of operands. In 1291 /// other words the score of G1 and G4 is the same as G1 and G2. This 1292 /// heuristic is based on ideas described in: 1293 /// Look-ahead SLP: Auto-vectorization in the presence of commutative 1294 /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha, 1295 /// Luís F. W. Góes 1296 int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel, 1297 ArrayRef<Value *> MainAltOps) { 1298 1299 // Get the shallow score of V1 and V2. 1300 int ShallowScoreAtThisLevel = 1301 getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps); 1302 1303 // If reached MaxLevel, 1304 // or if V1 and V2 are not instructions, 1305 // or if they are SPLAT, 1306 // or if they are not consecutive, 1307 // or if profitable to vectorize loads or extractelements, early return 1308 // the current cost. 1309 auto *I1 = dyn_cast<Instruction>(LHS); 1310 auto *I2 = dyn_cast<Instruction>(RHS); 1311 if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 || 1312 ShallowScoreAtThisLevel == VLOperands::ScoreFail || 1313 (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) || 1314 (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) || 1315 (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) && 1316 ShallowScoreAtThisLevel)) 1317 return ShallowScoreAtThisLevel; 1318 assert(I1 && I2 && "Should have early exited."); 1319 1320 // Contains the I2 operand indexes that got matched with I1 operands. 1321 SmallSet<unsigned, 4> Op2Used; 1322 1323 // Recursion towards the operands of I1 and I2. We are trying all possible 1324 // operand pairs, and keeping track of the best score. 1325 for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands(); 1326 OpIdx1 != NumOperands1; ++OpIdx1) { 1327 // Try to pair op1I with the best operand of I2. 1328 int MaxTmpScore = 0; 1329 unsigned MaxOpIdx2 = 0; 1330 bool FoundBest = false; 1331 // If I2 is commutative try all combinations. 1332 unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1; 1333 unsigned ToIdx = isCommutative(I2) 1334 ? I2->getNumOperands() 1335 : std::min(I2->getNumOperands(), OpIdx1 + 1); 1336 assert(FromIdx <= ToIdx && "Bad index"); 1337 for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) { 1338 // Skip operands already paired with OpIdx1. 1339 if (Op2Used.count(OpIdx2)) 1340 continue; 1341 // Recursively calculate the cost at each level 1342 int TmpScore = 1343 getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2), 1344 CurrLevel + 1, MaxLevel, None); 1345 // Look for the best score. 1346 if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) { 1347 MaxTmpScore = TmpScore; 1348 MaxOpIdx2 = OpIdx2; 1349 FoundBest = true; 1350 } 1351 } 1352 if (FoundBest) { 1353 // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it. 1354 Op2Used.insert(MaxOpIdx2); 1355 ShallowScoreAtThisLevel += MaxTmpScore; 1356 } 1357 } 1358 return ShallowScoreAtThisLevel; 1359 } 1360 1361 /// Score scaling factor for fully compatible instructions but with 1362 /// different number of external uses. Allows better selection of the 1363 /// instructions with less external uses. 1364 static const int ScoreScaleFactor = 10; 1365 1366 /// \Returns the look-ahead score, which tells us how much the sub-trees 1367 /// rooted at \p LHS and \p RHS match, the more they match the higher the 1368 /// score. This helps break ties in an informed way when we cannot decide on 1369 /// the order of the operands by just considering the immediate 1370 /// predecessors. 1371 int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps, 1372 int Lane, unsigned OpIdx, unsigned Idx, 1373 bool &IsUsed) { 1374 int Score = 1375 getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps); 1376 if (Score) { 1377 int SplatScore = getSplatScore(Lane, OpIdx, Idx); 1378 if (Score <= -SplatScore) { 1379 // Set the minimum score for splat-like sequence to avoid setting 1380 // failed state. 1381 Score = 1; 1382 } else { 1383 Score += SplatScore; 1384 // Scale score to see the difference between different operands 1385 // and similar operands but all vectorized/not all vectorized 1386 // uses. It does not affect actual selection of the best 1387 // compatible operand in general, just allows to select the 1388 // operand with all vectorized uses. 1389 Score *= ScoreScaleFactor; 1390 Score += getExternalUseScore(Lane, OpIdx, Idx); 1391 IsUsed = true; 1392 } 1393 } 1394 return Score; 1395 } 1396 1397 /// Best defined scores per lanes between the passes. Used to choose the 1398 /// best operand (with the highest score) between the passes. 1399 /// The key - {Operand Index, Lane}. 1400 /// The value - the best score between the passes for the lane and the 1401 /// operand. 1402 SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8> 1403 BestScoresPerLanes; 1404 1405 // Search all operands in Ops[*][Lane] for the one that matches best 1406 // Ops[OpIdx][LastLane] and return its opreand index. 1407 // If no good match can be found, return None. 1408 Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane, 1409 ArrayRef<ReorderingMode> ReorderingModes, 1410 ArrayRef<Value *> MainAltOps) { 1411 unsigned NumOperands = getNumOperands(); 1412 1413 // The operand of the previous lane at OpIdx. 1414 Value *OpLastLane = getData(OpIdx, LastLane).V; 1415 1416 // Our strategy mode for OpIdx. 1417 ReorderingMode RMode = ReorderingModes[OpIdx]; 1418 if (RMode == ReorderingMode::Failed) 1419 return None; 1420 1421 // The linearized opcode of the operand at OpIdx, Lane. 1422 bool OpIdxAPO = getData(OpIdx, Lane).APO; 1423 1424 // The best operand index and its score. 1425 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we 1426 // are using the score to differentiate between the two. 1427 struct BestOpData { 1428 Optional<unsigned> Idx = None; 1429 unsigned Score = 0; 1430 } BestOp; 1431 BestOp.Score = 1432 BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0) 1433 .first->second; 1434 1435 // Track if the operand must be marked as used. If the operand is set to 1436 // Score 1 explicitly (because of non power-of-2 unique scalars, we may 1437 // want to reestimate the operands again on the following iterations). 1438 bool IsUsed = 1439 RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant; 1440 // Iterate through all unused operands and look for the best. 1441 for (unsigned Idx = 0; Idx != NumOperands; ++Idx) { 1442 // Get the operand at Idx and Lane. 1443 OperandData &OpData = getData(Idx, Lane); 1444 Value *Op = OpData.V; 1445 bool OpAPO = OpData.APO; 1446 1447 // Skip already selected operands. 1448 if (OpData.IsUsed) 1449 continue; 1450 1451 // Skip if we are trying to move the operand to a position with a 1452 // different opcode in the linearized tree form. This would break the 1453 // semantics. 1454 if (OpAPO != OpIdxAPO) 1455 continue; 1456 1457 // Look for an operand that matches the current mode. 1458 switch (RMode) { 1459 case ReorderingMode::Load: 1460 case ReorderingMode::Constant: 1461 case ReorderingMode::Opcode: { 1462 bool LeftToRight = Lane > LastLane; 1463 Value *OpLeft = (LeftToRight) ? OpLastLane : Op; 1464 Value *OpRight = (LeftToRight) ? Op : OpLastLane; 1465 int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane, 1466 OpIdx, Idx, IsUsed); 1467 if (Score > static_cast<int>(BestOp.Score)) { 1468 BestOp.Idx = Idx; 1469 BestOp.Score = Score; 1470 BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score; 1471 } 1472 break; 1473 } 1474 case ReorderingMode::Splat: 1475 if (Op == OpLastLane) 1476 BestOp.Idx = Idx; 1477 break; 1478 case ReorderingMode::Failed: 1479 llvm_unreachable("Not expected Failed reordering mode."); 1480 } 1481 } 1482 1483 if (BestOp.Idx) { 1484 getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed; 1485 return BestOp.Idx; 1486 } 1487 // If we could not find a good match return None. 1488 return None; 1489 } 1490 1491 /// Helper for reorderOperandVecs. 1492 /// \returns the lane that we should start reordering from. This is the one 1493 /// which has the least number of operands that can freely move about or 1494 /// less profitable because it already has the most optimal set of operands. 1495 unsigned getBestLaneToStartReordering() const { 1496 unsigned Min = UINT_MAX; 1497 unsigned SameOpNumber = 0; 1498 // std::pair<unsigned, unsigned> is used to implement a simple voting 1499 // algorithm and choose the lane with the least number of operands that 1500 // can freely move about or less profitable because it already has the 1501 // most optimal set of operands. The first unsigned is a counter for 1502 // voting, the second unsigned is the counter of lanes with instructions 1503 // with same/alternate opcodes and same parent basic block. 1504 MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap; 1505 // Try to be closer to the original results, if we have multiple lanes 1506 // with same cost. If 2 lanes have the same cost, use the one with the 1507 // lowest index. 1508 for (int I = getNumLanes(); I > 0; --I) { 1509 unsigned Lane = I - 1; 1510 OperandsOrderData NumFreeOpsHash = 1511 getMaxNumOperandsThatCanBeReordered(Lane); 1512 // Compare the number of operands that can move and choose the one with 1513 // the least number. 1514 if (NumFreeOpsHash.NumOfAPOs < Min) { 1515 Min = NumFreeOpsHash.NumOfAPOs; 1516 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; 1517 HashMap.clear(); 1518 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1519 } else if (NumFreeOpsHash.NumOfAPOs == Min && 1520 NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) { 1521 // Select the most optimal lane in terms of number of operands that 1522 // should be moved around. 1523 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; 1524 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1525 } else if (NumFreeOpsHash.NumOfAPOs == Min && 1526 NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) { 1527 auto It = HashMap.find(NumFreeOpsHash.Hash); 1528 if (It == HashMap.end()) 1529 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1530 else 1531 ++It->second.first; 1532 } 1533 } 1534 // Select the lane with the minimum counter. 1535 unsigned BestLane = 0; 1536 unsigned CntMin = UINT_MAX; 1537 for (const auto &Data : reverse(HashMap)) { 1538 if (Data.second.first < CntMin) { 1539 CntMin = Data.second.first; 1540 BestLane = Data.second.second; 1541 } 1542 } 1543 return BestLane; 1544 } 1545 1546 /// Data structure that helps to reorder operands. 1547 struct OperandsOrderData { 1548 /// The best number of operands with the same APOs, which can be 1549 /// reordered. 1550 unsigned NumOfAPOs = UINT_MAX; 1551 /// Number of operands with the same/alternate instruction opcode and 1552 /// parent. 1553 unsigned NumOpsWithSameOpcodeParent = 0; 1554 /// Hash for the actual operands ordering. 1555 /// Used to count operands, actually their position id and opcode 1556 /// value. It is used in the voting mechanism to find the lane with the 1557 /// least number of operands that can freely move about or less profitable 1558 /// because it already has the most optimal set of operands. Can be 1559 /// replaced with SmallVector<unsigned> instead but hash code is faster 1560 /// and requires less memory. 1561 unsigned Hash = 0; 1562 }; 1563 /// \returns the maximum number of operands that are allowed to be reordered 1564 /// for \p Lane and the number of compatible instructions(with the same 1565 /// parent/opcode). This is used as a heuristic for selecting the first lane 1566 /// to start operand reordering. 1567 OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const { 1568 unsigned CntTrue = 0; 1569 unsigned NumOperands = getNumOperands(); 1570 // Operands with the same APO can be reordered. We therefore need to count 1571 // how many of them we have for each APO, like this: Cnt[APO] = x. 1572 // Since we only have two APOs, namely true and false, we can avoid using 1573 // a map. Instead we can simply count the number of operands that 1574 // correspond to one of them (in this case the 'true' APO), and calculate 1575 // the other by subtracting it from the total number of operands. 1576 // Operands with the same instruction opcode and parent are more 1577 // profitable since we don't need to move them in many cases, with a high 1578 // probability such lane already can be vectorized effectively. 1579 bool AllUndefs = true; 1580 unsigned NumOpsWithSameOpcodeParent = 0; 1581 Instruction *OpcodeI = nullptr; 1582 BasicBlock *Parent = nullptr; 1583 unsigned Hash = 0; 1584 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1585 const OperandData &OpData = getData(OpIdx, Lane); 1586 if (OpData.APO) 1587 ++CntTrue; 1588 // Use Boyer-Moore majority voting for finding the majority opcode and 1589 // the number of times it occurs. 1590 if (auto *I = dyn_cast<Instruction>(OpData.V)) { 1591 if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() || 1592 I->getParent() != Parent) { 1593 if (NumOpsWithSameOpcodeParent == 0) { 1594 NumOpsWithSameOpcodeParent = 1; 1595 OpcodeI = I; 1596 Parent = I->getParent(); 1597 } else { 1598 --NumOpsWithSameOpcodeParent; 1599 } 1600 } else { 1601 ++NumOpsWithSameOpcodeParent; 1602 } 1603 } 1604 Hash = hash_combine( 1605 Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1))); 1606 AllUndefs = AllUndefs && isa<UndefValue>(OpData.V); 1607 } 1608 if (AllUndefs) 1609 return {}; 1610 OperandsOrderData Data; 1611 Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue); 1612 Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent; 1613 Data.Hash = Hash; 1614 return Data; 1615 } 1616 1617 /// Go through the instructions in VL and append their operands. 1618 void appendOperandsOfVL(ArrayRef<Value *> VL) { 1619 assert(!VL.empty() && "Bad VL"); 1620 assert((empty() || VL.size() == getNumLanes()) && 1621 "Expected same number of lanes"); 1622 assert(isa<Instruction>(VL[0]) && "Expected instruction"); 1623 unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands(); 1624 OpsVec.resize(NumOperands); 1625 unsigned NumLanes = VL.size(); 1626 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1627 OpsVec[OpIdx].resize(NumLanes); 1628 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 1629 assert(isa<Instruction>(VL[Lane]) && "Expected instruction"); 1630 // Our tree has just 3 nodes: the root and two operands. 1631 // It is therefore trivial to get the APO. We only need to check the 1632 // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or 1633 // RHS operand. The LHS operand of both add and sub is never attached 1634 // to an inversese operation in the linearized form, therefore its APO 1635 // is false. The RHS is true only if VL[Lane] is an inverse operation. 1636 1637 // Since operand reordering is performed on groups of commutative 1638 // operations or alternating sequences (e.g., +, -), we can safely 1639 // tell the inverse operations by checking commutativity. 1640 bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane])); 1641 bool APO = (OpIdx == 0) ? false : IsInverseOperation; 1642 OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx), 1643 APO, false}; 1644 } 1645 } 1646 } 1647 1648 /// \returns the number of operands. 1649 unsigned getNumOperands() const { return OpsVec.size(); } 1650 1651 /// \returns the number of lanes. 1652 unsigned getNumLanes() const { return OpsVec[0].size(); } 1653 1654 /// \returns the operand value at \p OpIdx and \p Lane. 1655 Value *getValue(unsigned OpIdx, unsigned Lane) const { 1656 return getData(OpIdx, Lane).V; 1657 } 1658 1659 /// \returns true if the data structure is empty. 1660 bool empty() const { return OpsVec.empty(); } 1661 1662 /// Clears the data. 1663 void clear() { OpsVec.clear(); } 1664 1665 /// \Returns true if there are enough operands identical to \p Op to fill 1666 /// the whole vector. 1667 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow. 1668 bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) { 1669 bool OpAPO = getData(OpIdx, Lane).APO; 1670 for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) { 1671 if (Ln == Lane) 1672 continue; 1673 // This is set to true if we found a candidate for broadcast at Lane. 1674 bool FoundCandidate = false; 1675 for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) { 1676 OperandData &Data = getData(OpI, Ln); 1677 if (Data.APO != OpAPO || Data.IsUsed) 1678 continue; 1679 if (Data.V == Op) { 1680 FoundCandidate = true; 1681 Data.IsUsed = true; 1682 break; 1683 } 1684 } 1685 if (!FoundCandidate) 1686 return false; 1687 } 1688 return true; 1689 } 1690 1691 public: 1692 /// Initialize with all the operands of the instruction vector \p RootVL. 1693 VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL, 1694 ScalarEvolution &SE, const BoUpSLP &R) 1695 : DL(DL), SE(SE), R(R) { 1696 // Append all the operands of RootVL. 1697 appendOperandsOfVL(RootVL); 1698 } 1699 1700 /// \Returns a value vector with the operands across all lanes for the 1701 /// opearnd at \p OpIdx. 1702 ValueList getVL(unsigned OpIdx) const { 1703 ValueList OpVL(OpsVec[OpIdx].size()); 1704 assert(OpsVec[OpIdx].size() == getNumLanes() && 1705 "Expected same num of lanes across all operands"); 1706 for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane) 1707 OpVL[Lane] = OpsVec[OpIdx][Lane].V; 1708 return OpVL; 1709 } 1710 1711 // Performs operand reordering for 2 or more operands. 1712 // The original operands are in OrigOps[OpIdx][Lane]. 1713 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'. 1714 void reorder() { 1715 unsigned NumOperands = getNumOperands(); 1716 unsigned NumLanes = getNumLanes(); 1717 // Each operand has its own mode. We are using this mode to help us select 1718 // the instructions for each lane, so that they match best with the ones 1719 // we have selected so far. 1720 SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands); 1721 1722 // This is a greedy single-pass algorithm. We are going over each lane 1723 // once and deciding on the best order right away with no back-tracking. 1724 // However, in order to increase its effectiveness, we start with the lane 1725 // that has operands that can move the least. For example, given the 1726 // following lanes: 1727 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd 1728 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st 1729 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd 1730 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th 1731 // we will start at Lane 1, since the operands of the subtraction cannot 1732 // be reordered. Then we will visit the rest of the lanes in a circular 1733 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3. 1734 1735 // Find the first lane that we will start our search from. 1736 unsigned FirstLane = getBestLaneToStartReordering(); 1737 1738 // Initialize the modes. 1739 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1740 Value *OpLane0 = getValue(OpIdx, FirstLane); 1741 // Keep track if we have instructions with all the same opcode on one 1742 // side. 1743 if (isa<LoadInst>(OpLane0)) 1744 ReorderingModes[OpIdx] = ReorderingMode::Load; 1745 else if (isa<Instruction>(OpLane0)) { 1746 // Check if OpLane0 should be broadcast. 1747 if (shouldBroadcast(OpLane0, OpIdx, FirstLane)) 1748 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1749 else 1750 ReorderingModes[OpIdx] = ReorderingMode::Opcode; 1751 } 1752 else if (isa<Constant>(OpLane0)) 1753 ReorderingModes[OpIdx] = ReorderingMode::Constant; 1754 else if (isa<Argument>(OpLane0)) 1755 // Our best hope is a Splat. It may save some cost in some cases. 1756 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1757 else 1758 // NOTE: This should be unreachable. 1759 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1760 } 1761 1762 // Check that we don't have same operands. No need to reorder if operands 1763 // are just perfect diamond or shuffled diamond match. Do not do it only 1764 // for possible broadcasts or non-power of 2 number of scalars (just for 1765 // now). 1766 auto &&SkipReordering = [this]() { 1767 SmallPtrSet<Value *, 4> UniqueValues; 1768 ArrayRef<OperandData> Op0 = OpsVec.front(); 1769 for (const OperandData &Data : Op0) 1770 UniqueValues.insert(Data.V); 1771 for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) { 1772 if (any_of(Op, [&UniqueValues](const OperandData &Data) { 1773 return !UniqueValues.contains(Data.V); 1774 })) 1775 return false; 1776 } 1777 // TODO: Check if we can remove a check for non-power-2 number of 1778 // scalars after full support of non-power-2 vectorization. 1779 return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size()); 1780 }; 1781 1782 // If the initial strategy fails for any of the operand indexes, then we 1783 // perform reordering again in a second pass. This helps avoid assigning 1784 // high priority to the failed strategy, and should improve reordering for 1785 // the non-failed operand indexes. 1786 for (int Pass = 0; Pass != 2; ++Pass) { 1787 // Check if no need to reorder operands since they're are perfect or 1788 // shuffled diamond match. 1789 // Need to to do it to avoid extra external use cost counting for 1790 // shuffled matches, which may cause regressions. 1791 if (SkipReordering()) 1792 break; 1793 // Skip the second pass if the first pass did not fail. 1794 bool StrategyFailed = false; 1795 // Mark all operand data as free to use. 1796 clearUsed(); 1797 // We keep the original operand order for the FirstLane, so reorder the 1798 // rest of the lanes. We are visiting the nodes in a circular fashion, 1799 // using FirstLane as the center point and increasing the radius 1800 // distance. 1801 SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands); 1802 for (unsigned I = 0; I < NumOperands; ++I) 1803 MainAltOps[I].push_back(getData(I, FirstLane).V); 1804 1805 for (unsigned Distance = 1; Distance != NumLanes; ++Distance) { 1806 // Visit the lane on the right and then the lane on the left. 1807 for (int Direction : {+1, -1}) { 1808 int Lane = FirstLane + Direction * Distance; 1809 if (Lane < 0 || Lane >= (int)NumLanes) 1810 continue; 1811 int LastLane = Lane - Direction; 1812 assert(LastLane >= 0 && LastLane < (int)NumLanes && 1813 "Out of bounds"); 1814 // Look for a good match for each operand. 1815 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1816 // Search for the operand that matches SortedOps[OpIdx][Lane-1]. 1817 Optional<unsigned> BestIdx = getBestOperand( 1818 OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]); 1819 // By not selecting a value, we allow the operands that follow to 1820 // select a better matching value. We will get a non-null value in 1821 // the next run of getBestOperand(). 1822 if (BestIdx) { 1823 // Swap the current operand with the one returned by 1824 // getBestOperand(). 1825 swap(OpIdx, BestIdx.getValue(), Lane); 1826 } else { 1827 // We failed to find a best operand, set mode to 'Failed'. 1828 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1829 // Enable the second pass. 1830 StrategyFailed = true; 1831 } 1832 // Try to get the alternate opcode and follow it during analysis. 1833 if (MainAltOps[OpIdx].size() != 2) { 1834 OperandData &AltOp = getData(OpIdx, Lane); 1835 InstructionsState OpS = 1836 getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V}); 1837 if (OpS.getOpcode() && OpS.isAltShuffle()) 1838 MainAltOps[OpIdx].push_back(AltOp.V); 1839 } 1840 } 1841 } 1842 } 1843 // Skip second pass if the strategy did not fail. 1844 if (!StrategyFailed) 1845 break; 1846 } 1847 } 1848 1849 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1850 LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) { 1851 switch (RMode) { 1852 case ReorderingMode::Load: 1853 return "Load"; 1854 case ReorderingMode::Opcode: 1855 return "Opcode"; 1856 case ReorderingMode::Constant: 1857 return "Constant"; 1858 case ReorderingMode::Splat: 1859 return "Splat"; 1860 case ReorderingMode::Failed: 1861 return "Failed"; 1862 } 1863 llvm_unreachable("Unimplemented Reordering Type"); 1864 } 1865 1866 LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode, 1867 raw_ostream &OS) { 1868 return OS << getModeStr(RMode); 1869 } 1870 1871 /// Debug print. 1872 LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) { 1873 printMode(RMode, dbgs()); 1874 } 1875 1876 friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) { 1877 return printMode(RMode, OS); 1878 } 1879 1880 LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const { 1881 const unsigned Indent = 2; 1882 unsigned Cnt = 0; 1883 for (const OperandDataVec &OpDataVec : OpsVec) { 1884 OS << "Operand " << Cnt++ << "\n"; 1885 for (const OperandData &OpData : OpDataVec) { 1886 OS.indent(Indent) << "{"; 1887 if (Value *V = OpData.V) 1888 OS << *V; 1889 else 1890 OS << "null"; 1891 OS << ", APO:" << OpData.APO << "}\n"; 1892 } 1893 OS << "\n"; 1894 } 1895 return OS; 1896 } 1897 1898 /// Debug print. 1899 LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 1900 #endif 1901 }; 1902 1903 /// Checks if the instruction is marked for deletion. 1904 bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); } 1905 1906 /// Marks values operands for later deletion by replacing them with Undefs. 1907 void eraseInstructions(ArrayRef<Value *> AV); 1908 1909 ~BoUpSLP(); 1910 1911 private: 1912 /// Checks if all users of \p I are the part of the vectorization tree. 1913 bool areAllUsersVectorized(Instruction *I, 1914 ArrayRef<Value *> VectorizedVals) const; 1915 1916 /// \returns the cost of the vectorizable entry. 1917 InstructionCost getEntryCost(const TreeEntry *E, 1918 ArrayRef<Value *> VectorizedVals); 1919 1920 /// This is the recursive part of buildTree. 1921 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, 1922 const EdgeInfo &EI); 1923 1924 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can 1925 /// be vectorized to use the original vector (or aggregate "bitcast" to a 1926 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise 1927 /// returns false, setting \p CurrentOrder to either an empty vector or a 1928 /// non-identity permutation that allows to reuse extract instructions. 1929 bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 1930 SmallVectorImpl<unsigned> &CurrentOrder) const; 1931 1932 /// Vectorize a single entry in the tree. 1933 Value *vectorizeTree(TreeEntry *E); 1934 1935 /// Vectorize a single entry in the tree, starting in \p VL. 1936 Value *vectorizeTree(ArrayRef<Value *> VL); 1937 1938 /// \returns the scalarization cost for this type. Scalarization in this 1939 /// context means the creation of vectors from a group of scalars. If \p 1940 /// NeedToShuffle is true, need to add a cost of reshuffling some of the 1941 /// vector elements. 1942 InstructionCost getGatherCost(FixedVectorType *Ty, 1943 const DenseSet<unsigned> &ShuffledIndices, 1944 bool NeedToShuffle) const; 1945 1946 /// Checks if the gathered \p VL can be represented as shuffle(s) of previous 1947 /// tree entries. 1948 /// \returns ShuffleKind, if gathered values can be represented as shuffles of 1949 /// previous tree entries. \p Mask is filled with the shuffle mask. 1950 Optional<TargetTransformInfo::ShuffleKind> 1951 isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 1952 SmallVectorImpl<const TreeEntry *> &Entries); 1953 1954 /// \returns the scalarization cost for this list of values. Assuming that 1955 /// this subtree gets vectorized, we may need to extract the values from the 1956 /// roots. This method calculates the cost of extracting the values. 1957 InstructionCost getGatherCost(ArrayRef<Value *> VL) const; 1958 1959 /// Set the Builder insert point to one after the last instruction in 1960 /// the bundle 1961 void setInsertPointAfterBundle(const TreeEntry *E); 1962 1963 /// \returns a vector from a collection of scalars in \p VL. 1964 Value *gather(ArrayRef<Value *> VL); 1965 1966 /// \returns whether the VectorizableTree is fully vectorizable and will 1967 /// be beneficial even the tree height is tiny. 1968 bool isFullyVectorizableTinyTree(bool ForReduction) const; 1969 1970 /// Reorder commutative or alt operands to get better probability of 1971 /// generating vectorized code. 1972 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 1973 SmallVectorImpl<Value *> &Left, 1974 SmallVectorImpl<Value *> &Right, 1975 const DataLayout &DL, 1976 ScalarEvolution &SE, 1977 const BoUpSLP &R); 1978 struct TreeEntry { 1979 using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>; 1980 TreeEntry(VecTreeTy &Container) : Container(Container) {} 1981 1982 /// \returns true if the scalars in VL are equal to this entry. 1983 bool isSame(ArrayRef<Value *> VL) const { 1984 auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) { 1985 if (Mask.size() != VL.size() && VL.size() == Scalars.size()) 1986 return std::equal(VL.begin(), VL.end(), Scalars.begin()); 1987 return VL.size() == Mask.size() && 1988 std::equal(VL.begin(), VL.end(), Mask.begin(), 1989 [Scalars](Value *V, int Idx) { 1990 return (isa<UndefValue>(V) && 1991 Idx == UndefMaskElem) || 1992 (Idx != UndefMaskElem && V == Scalars[Idx]); 1993 }); 1994 }; 1995 if (!ReorderIndices.empty()) { 1996 // TODO: implement matching if the nodes are just reordered, still can 1997 // treat the vector as the same if the list of scalars matches VL 1998 // directly, without reordering. 1999 SmallVector<int> Mask; 2000 inversePermutation(ReorderIndices, Mask); 2001 if (VL.size() == Scalars.size()) 2002 return IsSame(Scalars, Mask); 2003 if (VL.size() == ReuseShuffleIndices.size()) { 2004 ::addMask(Mask, ReuseShuffleIndices); 2005 return IsSame(Scalars, Mask); 2006 } 2007 return false; 2008 } 2009 return IsSame(Scalars, ReuseShuffleIndices); 2010 } 2011 2012 /// \returns true if current entry has same operands as \p TE. 2013 bool hasEqualOperands(const TreeEntry &TE) const { 2014 if (TE.getNumOperands() != getNumOperands()) 2015 return false; 2016 SmallBitVector Used(getNumOperands()); 2017 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) { 2018 unsigned PrevCount = Used.count(); 2019 for (unsigned K = 0; K < E; ++K) { 2020 if (Used.test(K)) 2021 continue; 2022 if (getOperand(K) == TE.getOperand(I)) { 2023 Used.set(K); 2024 break; 2025 } 2026 } 2027 // Check if we actually found the matching operand. 2028 if (PrevCount == Used.count()) 2029 return false; 2030 } 2031 return true; 2032 } 2033 2034 /// \return Final vectorization factor for the node. Defined by the total 2035 /// number of vectorized scalars, including those, used several times in the 2036 /// entry and counted in the \a ReuseShuffleIndices, if any. 2037 unsigned getVectorFactor() const { 2038 if (!ReuseShuffleIndices.empty()) 2039 return ReuseShuffleIndices.size(); 2040 return Scalars.size(); 2041 }; 2042 2043 /// A vector of scalars. 2044 ValueList Scalars; 2045 2046 /// The Scalars are vectorized into this value. It is initialized to Null. 2047 Value *VectorizedValue = nullptr; 2048 2049 /// Do we need to gather this sequence or vectorize it 2050 /// (either with vector instruction or with scatter/gather 2051 /// intrinsics for store/load)? 2052 enum EntryState { Vectorize, ScatterVectorize, NeedToGather }; 2053 EntryState State; 2054 2055 /// Does this sequence require some shuffling? 2056 SmallVector<int, 4> ReuseShuffleIndices; 2057 2058 /// Does this entry require reordering? 2059 SmallVector<unsigned, 4> ReorderIndices; 2060 2061 /// Points back to the VectorizableTree. 2062 /// 2063 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has 2064 /// to be a pointer and needs to be able to initialize the child iterator. 2065 /// Thus we need a reference back to the container to translate the indices 2066 /// to entries. 2067 VecTreeTy &Container; 2068 2069 /// The TreeEntry index containing the user of this entry. We can actually 2070 /// have multiple users so the data structure is not truly a tree. 2071 SmallVector<EdgeInfo, 1> UserTreeIndices; 2072 2073 /// The index of this treeEntry in VectorizableTree. 2074 int Idx = -1; 2075 2076 private: 2077 /// The operands of each instruction in each lane Operands[op_index][lane]. 2078 /// Note: This helps avoid the replication of the code that performs the 2079 /// reordering of operands during buildTree_rec() and vectorizeTree(). 2080 SmallVector<ValueList, 2> Operands; 2081 2082 /// The main/alternate instruction. 2083 Instruction *MainOp = nullptr; 2084 Instruction *AltOp = nullptr; 2085 2086 public: 2087 /// Set this bundle's \p OpIdx'th operand to \p OpVL. 2088 void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) { 2089 if (Operands.size() < OpIdx + 1) 2090 Operands.resize(OpIdx + 1); 2091 assert(Operands[OpIdx].empty() && "Already resized?"); 2092 assert(OpVL.size() <= Scalars.size() && 2093 "Number of operands is greater than the number of scalars."); 2094 Operands[OpIdx].resize(OpVL.size()); 2095 copy(OpVL, Operands[OpIdx].begin()); 2096 } 2097 2098 /// Set the operands of this bundle in their original order. 2099 void setOperandsInOrder() { 2100 assert(Operands.empty() && "Already initialized?"); 2101 auto *I0 = cast<Instruction>(Scalars[0]); 2102 Operands.resize(I0->getNumOperands()); 2103 unsigned NumLanes = Scalars.size(); 2104 for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands(); 2105 OpIdx != NumOperands; ++OpIdx) { 2106 Operands[OpIdx].resize(NumLanes); 2107 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 2108 auto *I = cast<Instruction>(Scalars[Lane]); 2109 assert(I->getNumOperands() == NumOperands && 2110 "Expected same number of operands"); 2111 Operands[OpIdx][Lane] = I->getOperand(OpIdx); 2112 } 2113 } 2114 } 2115 2116 /// Reorders operands of the node to the given mask \p Mask. 2117 void reorderOperands(ArrayRef<int> Mask) { 2118 for (ValueList &Operand : Operands) 2119 reorderScalars(Operand, Mask); 2120 } 2121 2122 /// \returns the \p OpIdx operand of this TreeEntry. 2123 ValueList &getOperand(unsigned OpIdx) { 2124 assert(OpIdx < Operands.size() && "Off bounds"); 2125 return Operands[OpIdx]; 2126 } 2127 2128 /// \returns the \p OpIdx operand of this TreeEntry. 2129 ArrayRef<Value *> getOperand(unsigned OpIdx) const { 2130 assert(OpIdx < Operands.size() && "Off bounds"); 2131 return Operands[OpIdx]; 2132 } 2133 2134 /// \returns the number of operands. 2135 unsigned getNumOperands() const { return Operands.size(); } 2136 2137 /// \return the single \p OpIdx operand. 2138 Value *getSingleOperand(unsigned OpIdx) const { 2139 assert(OpIdx < Operands.size() && "Off bounds"); 2140 assert(!Operands[OpIdx].empty() && "No operand available"); 2141 return Operands[OpIdx][0]; 2142 } 2143 2144 /// Some of the instructions in the list have alternate opcodes. 2145 bool isAltShuffle() const { return MainOp != AltOp; } 2146 2147 bool isOpcodeOrAlt(Instruction *I) const { 2148 unsigned CheckedOpcode = I->getOpcode(); 2149 return (getOpcode() == CheckedOpcode || 2150 getAltOpcode() == CheckedOpcode); 2151 } 2152 2153 /// Chooses the correct key for scheduling data. If \p Op has the same (or 2154 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is 2155 /// \p OpValue. 2156 Value *isOneOf(Value *Op) const { 2157 auto *I = dyn_cast<Instruction>(Op); 2158 if (I && isOpcodeOrAlt(I)) 2159 return Op; 2160 return MainOp; 2161 } 2162 2163 void setOperations(const InstructionsState &S) { 2164 MainOp = S.MainOp; 2165 AltOp = S.AltOp; 2166 } 2167 2168 Instruction *getMainOp() const { 2169 return MainOp; 2170 } 2171 2172 Instruction *getAltOp() const { 2173 return AltOp; 2174 } 2175 2176 /// The main/alternate opcodes for the list of instructions. 2177 unsigned getOpcode() const { 2178 return MainOp ? MainOp->getOpcode() : 0; 2179 } 2180 2181 unsigned getAltOpcode() const { 2182 return AltOp ? AltOp->getOpcode() : 0; 2183 } 2184 2185 /// When ReuseReorderShuffleIndices is empty it just returns position of \p 2186 /// V within vector of Scalars. Otherwise, try to remap on its reuse index. 2187 int findLaneForValue(Value *V) const { 2188 unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V)); 2189 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 2190 if (!ReorderIndices.empty()) 2191 FoundLane = ReorderIndices[FoundLane]; 2192 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 2193 if (!ReuseShuffleIndices.empty()) { 2194 FoundLane = std::distance(ReuseShuffleIndices.begin(), 2195 find(ReuseShuffleIndices, FoundLane)); 2196 } 2197 return FoundLane; 2198 } 2199 2200 #ifndef NDEBUG 2201 /// Debug printer. 2202 LLVM_DUMP_METHOD void dump() const { 2203 dbgs() << Idx << ".\n"; 2204 for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) { 2205 dbgs() << "Operand " << OpI << ":\n"; 2206 for (const Value *V : Operands[OpI]) 2207 dbgs().indent(2) << *V << "\n"; 2208 } 2209 dbgs() << "Scalars: \n"; 2210 for (Value *V : Scalars) 2211 dbgs().indent(2) << *V << "\n"; 2212 dbgs() << "State: "; 2213 switch (State) { 2214 case Vectorize: 2215 dbgs() << "Vectorize\n"; 2216 break; 2217 case ScatterVectorize: 2218 dbgs() << "ScatterVectorize\n"; 2219 break; 2220 case NeedToGather: 2221 dbgs() << "NeedToGather\n"; 2222 break; 2223 } 2224 dbgs() << "MainOp: "; 2225 if (MainOp) 2226 dbgs() << *MainOp << "\n"; 2227 else 2228 dbgs() << "NULL\n"; 2229 dbgs() << "AltOp: "; 2230 if (AltOp) 2231 dbgs() << *AltOp << "\n"; 2232 else 2233 dbgs() << "NULL\n"; 2234 dbgs() << "VectorizedValue: "; 2235 if (VectorizedValue) 2236 dbgs() << *VectorizedValue << "\n"; 2237 else 2238 dbgs() << "NULL\n"; 2239 dbgs() << "ReuseShuffleIndices: "; 2240 if (ReuseShuffleIndices.empty()) 2241 dbgs() << "Empty"; 2242 else 2243 for (int ReuseIdx : ReuseShuffleIndices) 2244 dbgs() << ReuseIdx << ", "; 2245 dbgs() << "\n"; 2246 dbgs() << "ReorderIndices: "; 2247 for (unsigned ReorderIdx : ReorderIndices) 2248 dbgs() << ReorderIdx << ", "; 2249 dbgs() << "\n"; 2250 dbgs() << "UserTreeIndices: "; 2251 for (const auto &EInfo : UserTreeIndices) 2252 dbgs() << EInfo << ", "; 2253 dbgs() << "\n"; 2254 } 2255 #endif 2256 }; 2257 2258 #ifndef NDEBUG 2259 void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost, 2260 InstructionCost VecCost, 2261 InstructionCost ScalarCost) const { 2262 dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump(); 2263 dbgs() << "SLP: Costs:\n"; 2264 dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n"; 2265 dbgs() << "SLP: VectorCost = " << VecCost << "\n"; 2266 dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n"; 2267 dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = " << 2268 ReuseShuffleCost + VecCost - ScalarCost << "\n"; 2269 } 2270 #endif 2271 2272 /// Create a new VectorizableTree entry. 2273 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle, 2274 const InstructionsState &S, 2275 const EdgeInfo &UserTreeIdx, 2276 ArrayRef<int> ReuseShuffleIndices = None, 2277 ArrayRef<unsigned> ReorderIndices = None) { 2278 TreeEntry::EntryState EntryState = 2279 Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather; 2280 return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx, 2281 ReuseShuffleIndices, ReorderIndices); 2282 } 2283 2284 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, 2285 TreeEntry::EntryState EntryState, 2286 Optional<ScheduleData *> Bundle, 2287 const InstructionsState &S, 2288 const EdgeInfo &UserTreeIdx, 2289 ArrayRef<int> ReuseShuffleIndices = None, 2290 ArrayRef<unsigned> ReorderIndices = None) { 2291 assert(((!Bundle && EntryState == TreeEntry::NeedToGather) || 2292 (Bundle && EntryState != TreeEntry::NeedToGather)) && 2293 "Need to vectorize gather entry?"); 2294 VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree)); 2295 TreeEntry *Last = VectorizableTree.back().get(); 2296 Last->Idx = VectorizableTree.size() - 1; 2297 Last->State = EntryState; 2298 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(), 2299 ReuseShuffleIndices.end()); 2300 if (ReorderIndices.empty()) { 2301 Last->Scalars.assign(VL.begin(), VL.end()); 2302 Last->setOperations(S); 2303 } else { 2304 // Reorder scalars and build final mask. 2305 Last->Scalars.assign(VL.size(), nullptr); 2306 transform(ReorderIndices, Last->Scalars.begin(), 2307 [VL](unsigned Idx) -> Value * { 2308 if (Idx >= VL.size()) 2309 return UndefValue::get(VL.front()->getType()); 2310 return VL[Idx]; 2311 }); 2312 InstructionsState S = getSameOpcode(Last->Scalars); 2313 Last->setOperations(S); 2314 Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end()); 2315 } 2316 if (Last->State != TreeEntry::NeedToGather) { 2317 for (Value *V : VL) { 2318 assert(!getTreeEntry(V) && "Scalar already in tree!"); 2319 ScalarToTreeEntry[V] = Last; 2320 } 2321 // Update the scheduler bundle to point to this TreeEntry. 2322 unsigned Lane = 0; 2323 for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember; 2324 BundleMember = BundleMember->NextInBundle) { 2325 BundleMember->TE = Last; 2326 BundleMember->Lane = Lane; 2327 ++Lane; 2328 } 2329 assert((!Bundle.getValue() || Lane == VL.size()) && 2330 "Bundle and VL out of sync"); 2331 } else { 2332 MustGather.insert(VL.begin(), VL.end()); 2333 } 2334 2335 if (UserTreeIdx.UserTE) 2336 Last->UserTreeIndices.push_back(UserTreeIdx); 2337 2338 return Last; 2339 } 2340 2341 /// -- Vectorization State -- 2342 /// Holds all of the tree entries. 2343 TreeEntry::VecTreeTy VectorizableTree; 2344 2345 #ifndef NDEBUG 2346 /// Debug printer. 2347 LLVM_DUMP_METHOD void dumpVectorizableTree() const { 2348 for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) { 2349 VectorizableTree[Id]->dump(); 2350 dbgs() << "\n"; 2351 } 2352 } 2353 #endif 2354 2355 TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); } 2356 2357 const TreeEntry *getTreeEntry(Value *V) const { 2358 return ScalarToTreeEntry.lookup(V); 2359 } 2360 2361 /// Maps a specific scalar to its tree entry. 2362 SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry; 2363 2364 /// Maps a value to the proposed vectorizable size. 2365 SmallDenseMap<Value *, unsigned> InstrElementSize; 2366 2367 /// A list of scalars that we found that we need to keep as scalars. 2368 ValueSet MustGather; 2369 2370 /// This POD struct describes one external user in the vectorized tree. 2371 struct ExternalUser { 2372 ExternalUser(Value *S, llvm::User *U, int L) 2373 : Scalar(S), User(U), Lane(L) {} 2374 2375 // Which scalar in our function. 2376 Value *Scalar; 2377 2378 // Which user that uses the scalar. 2379 llvm::User *User; 2380 2381 // Which lane does the scalar belong to. 2382 int Lane; 2383 }; 2384 using UserList = SmallVector<ExternalUser, 16>; 2385 2386 /// Checks if two instructions may access the same memory. 2387 /// 2388 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it 2389 /// is invariant in the calling loop. 2390 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1, 2391 Instruction *Inst2) { 2392 // First check if the result is already in the cache. 2393 AliasCacheKey key = std::make_pair(Inst1, Inst2); 2394 Optional<bool> &result = AliasCache[key]; 2395 if (result.hasValue()) { 2396 return result.getValue(); 2397 } 2398 bool aliased = true; 2399 if (Loc1.Ptr && isSimple(Inst1)) 2400 aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1)); 2401 // Store the result in the cache. 2402 result = aliased; 2403 return aliased; 2404 } 2405 2406 using AliasCacheKey = std::pair<Instruction *, Instruction *>; 2407 2408 /// Cache for alias results. 2409 /// TODO: consider moving this to the AliasAnalysis itself. 2410 DenseMap<AliasCacheKey, Optional<bool>> AliasCache; 2411 2412 /// Removes an instruction from its block and eventually deletes it. 2413 /// It's like Instruction::eraseFromParent() except that the actual deletion 2414 /// is delayed until BoUpSLP is destructed. 2415 /// This is required to ensure that there are no incorrect collisions in the 2416 /// AliasCache, which can happen if a new instruction is allocated at the 2417 /// same address as a previously deleted instruction. 2418 void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) { 2419 auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first; 2420 It->getSecond() = It->getSecond() && ReplaceOpsWithUndef; 2421 } 2422 2423 /// Temporary store for deleted instructions. Instructions will be deleted 2424 /// eventually when the BoUpSLP is destructed. 2425 DenseMap<Instruction *, bool> DeletedInstructions; 2426 2427 /// A list of values that need to extracted out of the tree. 2428 /// This list holds pairs of (Internal Scalar : External User). External User 2429 /// can be nullptr, it means that this Internal Scalar will be used later, 2430 /// after vectorization. 2431 UserList ExternalUses; 2432 2433 /// Values used only by @llvm.assume calls. 2434 SmallPtrSet<const Value *, 32> EphValues; 2435 2436 /// Holds all of the instructions that we gathered. 2437 SetVector<Instruction *> GatherShuffleSeq; 2438 2439 /// A list of blocks that we are going to CSE. 2440 SetVector<BasicBlock *> CSEBlocks; 2441 2442 /// Contains all scheduling relevant data for an instruction. 2443 /// A ScheduleData either represents a single instruction or a member of an 2444 /// instruction bundle (= a group of instructions which is combined into a 2445 /// vector instruction). 2446 struct ScheduleData { 2447 // The initial value for the dependency counters. It means that the 2448 // dependencies are not calculated yet. 2449 enum { InvalidDeps = -1 }; 2450 2451 ScheduleData() = default; 2452 2453 void init(int BlockSchedulingRegionID, Value *OpVal) { 2454 FirstInBundle = this; 2455 NextInBundle = nullptr; 2456 NextLoadStore = nullptr; 2457 IsScheduled = false; 2458 SchedulingRegionID = BlockSchedulingRegionID; 2459 clearDependencies(); 2460 OpValue = OpVal; 2461 TE = nullptr; 2462 Lane = -1; 2463 } 2464 2465 /// Verify basic self consistency properties 2466 void verify() { 2467 if (hasValidDependencies()) { 2468 assert(UnscheduledDeps <= Dependencies && "invariant"); 2469 } else { 2470 assert(UnscheduledDeps == Dependencies && "invariant"); 2471 } 2472 2473 if (IsScheduled) { 2474 assert(isSchedulingEntity() && hasValidDependencies() && 2475 UnscheduledDeps == 0 && 2476 "unexpected scheduled state"); 2477 } 2478 } 2479 2480 /// Returns true if the dependency information has been calculated. 2481 /// Note that depenendency validity can vary between instructions within 2482 /// a single bundle. 2483 bool hasValidDependencies() const { return Dependencies != InvalidDeps; } 2484 2485 /// Returns true for single instructions and for bundle representatives 2486 /// (= the head of a bundle). 2487 bool isSchedulingEntity() const { return FirstInBundle == this; } 2488 2489 /// Returns true if it represents an instruction bundle and not only a 2490 /// single instruction. 2491 bool isPartOfBundle() const { 2492 return NextInBundle != nullptr || FirstInBundle != this; 2493 } 2494 2495 /// Returns true if it is ready for scheduling, i.e. it has no more 2496 /// unscheduled depending instructions/bundles. 2497 bool isReady() const { 2498 assert(isSchedulingEntity() && 2499 "can't consider non-scheduling entity for ready list"); 2500 return unscheduledDepsInBundle() == 0 && !IsScheduled; 2501 } 2502 2503 /// Modifies the number of unscheduled dependencies for this instruction, 2504 /// and returns the number of remaining dependencies for the containing 2505 /// bundle. 2506 int incrementUnscheduledDeps(int Incr) { 2507 assert(hasValidDependencies() && 2508 "increment of unscheduled deps would be meaningless"); 2509 UnscheduledDeps += Incr; 2510 return FirstInBundle->unscheduledDepsInBundle(); 2511 } 2512 2513 /// Sets the number of unscheduled dependencies to the number of 2514 /// dependencies. 2515 void resetUnscheduledDeps() { 2516 UnscheduledDeps = Dependencies; 2517 } 2518 2519 /// Clears all dependency information. 2520 void clearDependencies() { 2521 Dependencies = InvalidDeps; 2522 resetUnscheduledDeps(); 2523 MemoryDependencies.clear(); 2524 } 2525 2526 int unscheduledDepsInBundle() const { 2527 assert(isSchedulingEntity() && "only meaningful on the bundle"); 2528 int Sum = 0; 2529 for (const ScheduleData *BundleMember = this; BundleMember; 2530 BundleMember = BundleMember->NextInBundle) { 2531 if (BundleMember->UnscheduledDeps == InvalidDeps) 2532 return InvalidDeps; 2533 Sum += BundleMember->UnscheduledDeps; 2534 } 2535 return Sum; 2536 } 2537 2538 void dump(raw_ostream &os) const { 2539 if (!isSchedulingEntity()) { 2540 os << "/ " << *Inst; 2541 } else if (NextInBundle) { 2542 os << '[' << *Inst; 2543 ScheduleData *SD = NextInBundle; 2544 while (SD) { 2545 os << ';' << *SD->Inst; 2546 SD = SD->NextInBundle; 2547 } 2548 os << ']'; 2549 } else { 2550 os << *Inst; 2551 } 2552 } 2553 2554 Instruction *Inst = nullptr; 2555 2556 /// Points to the head in an instruction bundle (and always to this for 2557 /// single instructions). 2558 ScheduleData *FirstInBundle = nullptr; 2559 2560 /// Single linked list of all instructions in a bundle. Null if it is a 2561 /// single instruction. 2562 ScheduleData *NextInBundle = nullptr; 2563 2564 /// Single linked list of all memory instructions (e.g. load, store, call) 2565 /// in the block - until the end of the scheduling region. 2566 ScheduleData *NextLoadStore = nullptr; 2567 2568 /// The dependent memory instructions. 2569 /// This list is derived on demand in calculateDependencies(). 2570 SmallVector<ScheduleData *, 4> MemoryDependencies; 2571 2572 /// This ScheduleData is in the current scheduling region if this matches 2573 /// the current SchedulingRegionID of BlockScheduling. 2574 int SchedulingRegionID = 0; 2575 2576 /// Used for getting a "good" final ordering of instructions. 2577 int SchedulingPriority = 0; 2578 2579 /// The number of dependencies. Constitutes of the number of users of the 2580 /// instruction plus the number of dependent memory instructions (if any). 2581 /// This value is calculated on demand. 2582 /// If InvalidDeps, the number of dependencies is not calculated yet. 2583 int Dependencies = InvalidDeps; 2584 2585 /// The number of dependencies minus the number of dependencies of scheduled 2586 /// instructions. As soon as this is zero, the instruction/bundle gets ready 2587 /// for scheduling. 2588 /// Note that this is negative as long as Dependencies is not calculated. 2589 int UnscheduledDeps = InvalidDeps; 2590 2591 /// True if this instruction is scheduled (or considered as scheduled in the 2592 /// dry-run). 2593 bool IsScheduled = false; 2594 2595 /// Opcode of the current instruction in the schedule data. 2596 Value *OpValue = nullptr; 2597 2598 /// The TreeEntry that this instruction corresponds to. 2599 TreeEntry *TE = nullptr; 2600 2601 /// The lane of this node in the TreeEntry. 2602 int Lane = -1; 2603 }; 2604 2605 #ifndef NDEBUG 2606 friend inline raw_ostream &operator<<(raw_ostream &os, 2607 const BoUpSLP::ScheduleData &SD) { 2608 SD.dump(os); 2609 return os; 2610 } 2611 #endif 2612 2613 friend struct GraphTraits<BoUpSLP *>; 2614 friend struct DOTGraphTraits<BoUpSLP *>; 2615 2616 /// Contains all scheduling data for a basic block. 2617 struct BlockScheduling { 2618 BlockScheduling(BasicBlock *BB) 2619 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {} 2620 2621 void clear() { 2622 ReadyInsts.clear(); 2623 ScheduleStart = nullptr; 2624 ScheduleEnd = nullptr; 2625 FirstLoadStoreInRegion = nullptr; 2626 LastLoadStoreInRegion = nullptr; 2627 2628 // Reduce the maximum schedule region size by the size of the 2629 // previous scheduling run. 2630 ScheduleRegionSizeLimit -= ScheduleRegionSize; 2631 if (ScheduleRegionSizeLimit < MinScheduleRegionSize) 2632 ScheduleRegionSizeLimit = MinScheduleRegionSize; 2633 ScheduleRegionSize = 0; 2634 2635 // Make a new scheduling region, i.e. all existing ScheduleData is not 2636 // in the new region yet. 2637 ++SchedulingRegionID; 2638 } 2639 2640 ScheduleData *getScheduleData(Value *V) { 2641 ScheduleData *SD = ScheduleDataMap[V]; 2642 if (SD && SD->SchedulingRegionID == SchedulingRegionID) 2643 return SD; 2644 return nullptr; 2645 } 2646 2647 ScheduleData *getScheduleData(Value *V, Value *Key) { 2648 if (V == Key) 2649 return getScheduleData(V); 2650 auto I = ExtraScheduleDataMap.find(V); 2651 if (I != ExtraScheduleDataMap.end()) { 2652 ScheduleData *SD = I->second[Key]; 2653 if (SD && SD->SchedulingRegionID == SchedulingRegionID) 2654 return SD; 2655 } 2656 return nullptr; 2657 } 2658 2659 bool isInSchedulingRegion(ScheduleData *SD) const { 2660 return SD->SchedulingRegionID == SchedulingRegionID; 2661 } 2662 2663 /// Marks an instruction as scheduled and puts all dependent ready 2664 /// instructions into the ready-list. 2665 template <typename ReadyListType> 2666 void schedule(ScheduleData *SD, ReadyListType &ReadyList) { 2667 SD->IsScheduled = true; 2668 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n"); 2669 2670 for (ScheduleData *BundleMember = SD; BundleMember; 2671 BundleMember = BundleMember->NextInBundle) { 2672 if (BundleMember->Inst != BundleMember->OpValue) 2673 continue; 2674 2675 // Handle the def-use chain dependencies. 2676 2677 // Decrement the unscheduled counter and insert to ready list if ready. 2678 auto &&DecrUnsched = [this, &ReadyList](Instruction *I) { 2679 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) { 2680 if (OpDef && OpDef->hasValidDependencies() && 2681 OpDef->incrementUnscheduledDeps(-1) == 0) { 2682 // There are no more unscheduled dependencies after 2683 // decrementing, so we can put the dependent instruction 2684 // into the ready list. 2685 ScheduleData *DepBundle = OpDef->FirstInBundle; 2686 assert(!DepBundle->IsScheduled && 2687 "already scheduled bundle gets ready"); 2688 ReadyList.insert(DepBundle); 2689 LLVM_DEBUG(dbgs() 2690 << "SLP: gets ready (def): " << *DepBundle << "\n"); 2691 } 2692 }); 2693 }; 2694 2695 // If BundleMember is a vector bundle, its operands may have been 2696 // reordered during buildTree(). We therefore need to get its operands 2697 // through the TreeEntry. 2698 if (TreeEntry *TE = BundleMember->TE) { 2699 int Lane = BundleMember->Lane; 2700 assert(Lane >= 0 && "Lane not set"); 2701 2702 // Since vectorization tree is being built recursively this assertion 2703 // ensures that the tree entry has all operands set before reaching 2704 // this code. Couple of exceptions known at the moment are extracts 2705 // where their second (immediate) operand is not added. Since 2706 // immediates do not affect scheduler behavior this is considered 2707 // okay. 2708 auto *In = TE->getMainOp(); 2709 assert(In && 2710 (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) || 2711 In->getNumOperands() == TE->getNumOperands()) && 2712 "Missed TreeEntry operands?"); 2713 (void)In; // fake use to avoid build failure when assertions disabled 2714 2715 for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands(); 2716 OpIdx != NumOperands; ++OpIdx) 2717 if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane])) 2718 DecrUnsched(I); 2719 } else { 2720 // If BundleMember is a stand-alone instruction, no operand reordering 2721 // has taken place, so we directly access its operands. 2722 for (Use &U : BundleMember->Inst->operands()) 2723 if (auto *I = dyn_cast<Instruction>(U.get())) 2724 DecrUnsched(I); 2725 } 2726 // Handle the memory dependencies. 2727 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) { 2728 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) { 2729 // There are no more unscheduled dependencies after decrementing, 2730 // so we can put the dependent instruction into the ready list. 2731 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle; 2732 assert(!DepBundle->IsScheduled && 2733 "already scheduled bundle gets ready"); 2734 ReadyList.insert(DepBundle); 2735 LLVM_DEBUG(dbgs() 2736 << "SLP: gets ready (mem): " << *DepBundle << "\n"); 2737 } 2738 } 2739 } 2740 } 2741 2742 /// Verify basic self consistency properties of the data structure. 2743 void verify() { 2744 if (!ScheduleStart) 2745 return; 2746 2747 assert(ScheduleStart->getParent() == ScheduleEnd->getParent() && 2748 ScheduleStart->comesBefore(ScheduleEnd) && 2749 "Not a valid scheduling region?"); 2750 2751 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 2752 auto *SD = getScheduleData(I); 2753 assert(SD && "primary scheduledata must exist in window"); 2754 assert(isInSchedulingRegion(SD) && 2755 "primary schedule data not in window?"); 2756 doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); }); 2757 } 2758 2759 for (auto *SD : ReadyInsts) { 2760 assert(SD->isSchedulingEntity() && SD->isReady() && 2761 "item in ready list not ready?"); 2762 } 2763 } 2764 2765 void doForAllOpcodes(Value *V, 2766 function_ref<void(ScheduleData *SD)> Action) { 2767 if (ScheduleData *SD = getScheduleData(V)) 2768 Action(SD); 2769 auto I = ExtraScheduleDataMap.find(V); 2770 if (I != ExtraScheduleDataMap.end()) 2771 for (auto &P : I->second) 2772 if (P.second->SchedulingRegionID == SchedulingRegionID) 2773 Action(P.second); 2774 } 2775 2776 /// Put all instructions into the ReadyList which are ready for scheduling. 2777 template <typename ReadyListType> 2778 void initialFillReadyList(ReadyListType &ReadyList) { 2779 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 2780 doForAllOpcodes(I, [&](ScheduleData *SD) { 2781 if (SD->isSchedulingEntity() && SD->isReady()) { 2782 ReadyList.insert(SD); 2783 LLVM_DEBUG(dbgs() 2784 << "SLP: initially in ready list: " << *SD << "\n"); 2785 } 2786 }); 2787 } 2788 } 2789 2790 /// Build a bundle from the ScheduleData nodes corresponding to the 2791 /// scalar instruction for each lane. 2792 ScheduleData *buildBundle(ArrayRef<Value *> VL); 2793 2794 /// Checks if a bundle of instructions can be scheduled, i.e. has no 2795 /// cyclic dependencies. This is only a dry-run, no instructions are 2796 /// actually moved at this stage. 2797 /// \returns the scheduling bundle. The returned Optional value is non-None 2798 /// if \p VL is allowed to be scheduled. 2799 Optional<ScheduleData *> 2800 tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 2801 const InstructionsState &S); 2802 2803 /// Un-bundles a group of instructions. 2804 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue); 2805 2806 /// Allocates schedule data chunk. 2807 ScheduleData *allocateScheduleDataChunks(); 2808 2809 /// Extends the scheduling region so that V is inside the region. 2810 /// \returns true if the region size is within the limit. 2811 bool extendSchedulingRegion(Value *V, const InstructionsState &S); 2812 2813 /// Initialize the ScheduleData structures for new instructions in the 2814 /// scheduling region. 2815 void initScheduleData(Instruction *FromI, Instruction *ToI, 2816 ScheduleData *PrevLoadStore, 2817 ScheduleData *NextLoadStore); 2818 2819 /// Updates the dependency information of a bundle and of all instructions/ 2820 /// bundles which depend on the original bundle. 2821 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList, 2822 BoUpSLP *SLP); 2823 2824 /// Sets all instruction in the scheduling region to un-scheduled. 2825 void resetSchedule(); 2826 2827 BasicBlock *BB; 2828 2829 /// Simple memory allocation for ScheduleData. 2830 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks; 2831 2832 /// The size of a ScheduleData array in ScheduleDataChunks. 2833 int ChunkSize; 2834 2835 /// The allocator position in the current chunk, which is the last entry 2836 /// of ScheduleDataChunks. 2837 int ChunkPos; 2838 2839 /// Attaches ScheduleData to Instruction. 2840 /// Note that the mapping survives during all vectorization iterations, i.e. 2841 /// ScheduleData structures are recycled. 2842 DenseMap<Value *, ScheduleData *> ScheduleDataMap; 2843 2844 /// Attaches ScheduleData to Instruction with the leading key. 2845 DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>> 2846 ExtraScheduleDataMap; 2847 2848 /// The ready-list for scheduling (only used for the dry-run). 2849 SetVector<ScheduleData *> ReadyInsts; 2850 2851 /// The first instruction of the scheduling region. 2852 Instruction *ScheduleStart = nullptr; 2853 2854 /// The first instruction _after_ the scheduling region. 2855 Instruction *ScheduleEnd = nullptr; 2856 2857 /// The first memory accessing instruction in the scheduling region 2858 /// (can be null). 2859 ScheduleData *FirstLoadStoreInRegion = nullptr; 2860 2861 /// The last memory accessing instruction in the scheduling region 2862 /// (can be null). 2863 ScheduleData *LastLoadStoreInRegion = nullptr; 2864 2865 /// The current size of the scheduling region. 2866 int ScheduleRegionSize = 0; 2867 2868 /// The maximum size allowed for the scheduling region. 2869 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget; 2870 2871 /// The ID of the scheduling region. For a new vectorization iteration this 2872 /// is incremented which "removes" all ScheduleData from the region. 2873 // Make sure that the initial SchedulingRegionID is greater than the 2874 // initial SchedulingRegionID in ScheduleData (which is 0). 2875 int SchedulingRegionID = 1; 2876 }; 2877 2878 /// Attaches the BlockScheduling structures to basic blocks. 2879 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules; 2880 2881 /// Performs the "real" scheduling. Done before vectorization is actually 2882 /// performed in a basic block. 2883 void scheduleBlock(BlockScheduling *BS); 2884 2885 /// List of users to ignore during scheduling and that don't need extracting. 2886 ArrayRef<Value *> UserIgnoreList; 2887 2888 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of 2889 /// sorted SmallVectors of unsigned. 2890 struct OrdersTypeDenseMapInfo { 2891 static OrdersType getEmptyKey() { 2892 OrdersType V; 2893 V.push_back(~1U); 2894 return V; 2895 } 2896 2897 static OrdersType getTombstoneKey() { 2898 OrdersType V; 2899 V.push_back(~2U); 2900 return V; 2901 } 2902 2903 static unsigned getHashValue(const OrdersType &V) { 2904 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 2905 } 2906 2907 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) { 2908 return LHS == RHS; 2909 } 2910 }; 2911 2912 // Analysis and block reference. 2913 Function *F; 2914 ScalarEvolution *SE; 2915 TargetTransformInfo *TTI; 2916 TargetLibraryInfo *TLI; 2917 AAResults *AA; 2918 LoopInfo *LI; 2919 DominatorTree *DT; 2920 AssumptionCache *AC; 2921 DemandedBits *DB; 2922 const DataLayout *DL; 2923 OptimizationRemarkEmitter *ORE; 2924 2925 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt. 2926 unsigned MinVecRegSize; // Set by cl::opt (default: 128). 2927 2928 /// Instruction builder to construct the vectorized tree. 2929 IRBuilder<> Builder; 2930 2931 /// A map of scalar integer values to the smallest bit width with which they 2932 /// can legally be represented. The values map to (width, signed) pairs, 2933 /// where "width" indicates the minimum bit width and "signed" is True if the 2934 /// value must be signed-extended, rather than zero-extended, back to its 2935 /// original width. 2936 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs; 2937 }; 2938 2939 } // end namespace slpvectorizer 2940 2941 template <> struct GraphTraits<BoUpSLP *> { 2942 using TreeEntry = BoUpSLP::TreeEntry; 2943 2944 /// NodeRef has to be a pointer per the GraphWriter. 2945 using NodeRef = TreeEntry *; 2946 2947 using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy; 2948 2949 /// Add the VectorizableTree to the index iterator to be able to return 2950 /// TreeEntry pointers. 2951 struct ChildIteratorType 2952 : public iterator_adaptor_base< 2953 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> { 2954 ContainerTy &VectorizableTree; 2955 2956 ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W, 2957 ContainerTy &VT) 2958 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {} 2959 2960 NodeRef operator*() { return I->UserTE; } 2961 }; 2962 2963 static NodeRef getEntryNode(BoUpSLP &R) { 2964 return R.VectorizableTree[0].get(); 2965 } 2966 2967 static ChildIteratorType child_begin(NodeRef N) { 2968 return {N->UserTreeIndices.begin(), N->Container}; 2969 } 2970 2971 static ChildIteratorType child_end(NodeRef N) { 2972 return {N->UserTreeIndices.end(), N->Container}; 2973 } 2974 2975 /// For the node iterator we just need to turn the TreeEntry iterator into a 2976 /// TreeEntry* iterator so that it dereferences to NodeRef. 2977 class nodes_iterator { 2978 using ItTy = ContainerTy::iterator; 2979 ItTy It; 2980 2981 public: 2982 nodes_iterator(const ItTy &It2) : It(It2) {} 2983 NodeRef operator*() { return It->get(); } 2984 nodes_iterator operator++() { 2985 ++It; 2986 return *this; 2987 } 2988 bool operator!=(const nodes_iterator &N2) const { return N2.It != It; } 2989 }; 2990 2991 static nodes_iterator nodes_begin(BoUpSLP *R) { 2992 return nodes_iterator(R->VectorizableTree.begin()); 2993 } 2994 2995 static nodes_iterator nodes_end(BoUpSLP *R) { 2996 return nodes_iterator(R->VectorizableTree.end()); 2997 } 2998 2999 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); } 3000 }; 3001 3002 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits { 3003 using TreeEntry = BoUpSLP::TreeEntry; 3004 3005 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 3006 3007 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) { 3008 std::string Str; 3009 raw_string_ostream OS(Str); 3010 if (isSplat(Entry->Scalars)) 3011 OS << "<splat> "; 3012 for (auto V : Entry->Scalars) { 3013 OS << *V; 3014 if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) { 3015 return EU.Scalar == V; 3016 })) 3017 OS << " <extract>"; 3018 OS << "\n"; 3019 } 3020 return Str; 3021 } 3022 3023 static std::string getNodeAttributes(const TreeEntry *Entry, 3024 const BoUpSLP *) { 3025 if (Entry->State == TreeEntry::NeedToGather) 3026 return "color=red"; 3027 return ""; 3028 } 3029 }; 3030 3031 } // end namespace llvm 3032 3033 BoUpSLP::~BoUpSLP() { 3034 for (const auto &Pair : DeletedInstructions) { 3035 // Replace operands of ignored instructions with Undefs in case if they were 3036 // marked for deletion. 3037 if (Pair.getSecond()) { 3038 Value *Undef = UndefValue::get(Pair.getFirst()->getType()); 3039 Pair.getFirst()->replaceAllUsesWith(Undef); 3040 } 3041 Pair.getFirst()->dropAllReferences(); 3042 } 3043 for (const auto &Pair : DeletedInstructions) { 3044 assert(Pair.getFirst()->use_empty() && 3045 "trying to erase instruction with users."); 3046 Pair.getFirst()->eraseFromParent(); 3047 } 3048 #ifdef EXPENSIVE_CHECKS 3049 // If we could guarantee that this call is not extremely slow, we could 3050 // remove the ifdef limitation (see PR47712). 3051 assert(!verifyFunction(*F, &dbgs())); 3052 #endif 3053 } 3054 3055 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) { 3056 for (auto *V : AV) { 3057 if (auto *I = dyn_cast<Instruction>(V)) 3058 eraseInstruction(I, /*ReplaceOpsWithUndef=*/true); 3059 }; 3060 } 3061 3062 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses 3063 /// contains original mask for the scalars reused in the node. Procedure 3064 /// transform this mask in accordance with the given \p Mask. 3065 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) { 3066 assert(!Mask.empty() && Reuses.size() == Mask.size() && 3067 "Expected non-empty mask."); 3068 SmallVector<int> Prev(Reuses.begin(), Reuses.end()); 3069 Prev.swap(Reuses); 3070 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 3071 if (Mask[I] != UndefMaskElem) 3072 Reuses[Mask[I]] = Prev[I]; 3073 } 3074 3075 /// Reorders the given \p Order according to the given \p Mask. \p Order - is 3076 /// the original order of the scalars. Procedure transforms the provided order 3077 /// in accordance with the given \p Mask. If the resulting \p Order is just an 3078 /// identity order, \p Order is cleared. 3079 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) { 3080 assert(!Mask.empty() && "Expected non-empty mask."); 3081 SmallVector<int> MaskOrder; 3082 if (Order.empty()) { 3083 MaskOrder.resize(Mask.size()); 3084 std::iota(MaskOrder.begin(), MaskOrder.end(), 0); 3085 } else { 3086 inversePermutation(Order, MaskOrder); 3087 } 3088 reorderReuses(MaskOrder, Mask); 3089 if (ShuffleVectorInst::isIdentityMask(MaskOrder)) { 3090 Order.clear(); 3091 return; 3092 } 3093 Order.assign(Mask.size(), Mask.size()); 3094 for (unsigned I = 0, E = Mask.size(); I < E; ++I) 3095 if (MaskOrder[I] != UndefMaskElem) 3096 Order[MaskOrder[I]] = I; 3097 fixupOrderingIndices(Order); 3098 } 3099 3100 Optional<BoUpSLP::OrdersType> 3101 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) { 3102 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only."); 3103 unsigned NumScalars = TE.Scalars.size(); 3104 OrdersType CurrentOrder(NumScalars, NumScalars); 3105 SmallVector<int> Positions; 3106 SmallBitVector UsedPositions(NumScalars); 3107 const TreeEntry *STE = nullptr; 3108 // Try to find all gathered scalars that are gets vectorized in other 3109 // vectorize node. Here we can have only one single tree vector node to 3110 // correctly identify order of the gathered scalars. 3111 for (unsigned I = 0; I < NumScalars; ++I) { 3112 Value *V = TE.Scalars[I]; 3113 if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V)) 3114 continue; 3115 if (const auto *LocalSTE = getTreeEntry(V)) { 3116 if (!STE) 3117 STE = LocalSTE; 3118 else if (STE != LocalSTE) 3119 // Take the order only from the single vector node. 3120 return None; 3121 unsigned Lane = 3122 std::distance(STE->Scalars.begin(), find(STE->Scalars, V)); 3123 if (Lane >= NumScalars) 3124 return None; 3125 if (CurrentOrder[Lane] != NumScalars) { 3126 if (Lane != I) 3127 continue; 3128 UsedPositions.reset(CurrentOrder[Lane]); 3129 } 3130 // The partial identity (where only some elements of the gather node are 3131 // in the identity order) is good. 3132 CurrentOrder[Lane] = I; 3133 UsedPositions.set(I); 3134 } 3135 } 3136 // Need to keep the order if we have a vector entry and at least 2 scalars or 3137 // the vectorized entry has just 2 scalars. 3138 if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) { 3139 auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) { 3140 for (unsigned I = 0; I < NumScalars; ++I) 3141 if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars) 3142 return false; 3143 return true; 3144 }; 3145 if (IsIdentityOrder(CurrentOrder)) { 3146 CurrentOrder.clear(); 3147 return CurrentOrder; 3148 } 3149 auto *It = CurrentOrder.begin(); 3150 for (unsigned I = 0; I < NumScalars;) { 3151 if (UsedPositions.test(I)) { 3152 ++I; 3153 continue; 3154 } 3155 if (*It == NumScalars) { 3156 *It = I; 3157 ++I; 3158 } 3159 ++It; 3160 } 3161 return CurrentOrder; 3162 } 3163 return None; 3164 } 3165 3166 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE, 3167 bool TopToBottom) { 3168 // No need to reorder if need to shuffle reuses, still need to shuffle the 3169 // node. 3170 if (!TE.ReuseShuffleIndices.empty()) 3171 return None; 3172 if (TE.State == TreeEntry::Vectorize && 3173 (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) || 3174 (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) && 3175 !TE.isAltShuffle()) 3176 return TE.ReorderIndices; 3177 if (TE.State == TreeEntry::NeedToGather) { 3178 // TODO: add analysis of other gather nodes with extractelement 3179 // instructions and other values/instructions, not only undefs. 3180 if (((TE.getOpcode() == Instruction::ExtractElement && 3181 !TE.isAltShuffle()) || 3182 (all_of(TE.Scalars, 3183 [](Value *V) { 3184 return isa<UndefValue, ExtractElementInst>(V); 3185 }) && 3186 any_of(TE.Scalars, 3187 [](Value *V) { return isa<ExtractElementInst>(V); }))) && 3188 all_of(TE.Scalars, 3189 [](Value *V) { 3190 auto *EE = dyn_cast<ExtractElementInst>(V); 3191 return !EE || isa<FixedVectorType>(EE->getVectorOperandType()); 3192 }) && 3193 allSameType(TE.Scalars)) { 3194 // Check that gather of extractelements can be represented as 3195 // just a shuffle of a single vector. 3196 OrdersType CurrentOrder; 3197 bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder); 3198 if (Reuse || !CurrentOrder.empty()) { 3199 if (!CurrentOrder.empty()) 3200 fixupOrderingIndices(CurrentOrder); 3201 return CurrentOrder; 3202 } 3203 } 3204 if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE)) 3205 return CurrentOrder; 3206 } 3207 return None; 3208 } 3209 3210 void BoUpSLP::reorderTopToBottom() { 3211 // Maps VF to the graph nodes. 3212 DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries; 3213 // ExtractElement gather nodes which can be vectorized and need to handle 3214 // their ordering. 3215 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3216 // Find all reorderable nodes with the given VF. 3217 // Currently the are vectorized stores,loads,extracts + some gathering of 3218 // extracts. 3219 for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders]( 3220 const std::unique_ptr<TreeEntry> &TE) { 3221 if (Optional<OrdersType> CurrentOrder = 3222 getReorderingData(*TE.get(), /*TopToBottom=*/true)) { 3223 // Do not include ordering for nodes used in the alt opcode vectorization, 3224 // better to reorder them during bottom-to-top stage. If follow the order 3225 // here, it causes reordering of the whole graph though actually it is 3226 // profitable just to reorder the subgraph that starts from the alternate 3227 // opcode vectorization node. Such nodes already end-up with the shuffle 3228 // instruction and it is just enough to change this shuffle rather than 3229 // rotate the scalars for the whole graph. 3230 unsigned Cnt = 0; 3231 const TreeEntry *UserTE = TE.get(); 3232 while (UserTE && Cnt < RecursionMaxDepth) { 3233 if (UserTE->UserTreeIndices.size() != 1) 3234 break; 3235 if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) { 3236 return EI.UserTE->State == TreeEntry::Vectorize && 3237 EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0; 3238 })) 3239 return; 3240 if (UserTE->UserTreeIndices.empty()) 3241 UserTE = nullptr; 3242 else 3243 UserTE = UserTE->UserTreeIndices.back().UserTE; 3244 ++Cnt; 3245 } 3246 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 3247 if (TE->State != TreeEntry::Vectorize) 3248 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3249 } 3250 }); 3251 3252 // Reorder the graph nodes according to their vectorization factor. 3253 for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1; 3254 VF /= 2) { 3255 auto It = VFToOrderedEntries.find(VF); 3256 if (It == VFToOrderedEntries.end()) 3257 continue; 3258 // Try to find the most profitable order. We just are looking for the most 3259 // used order and reorder scalar elements in the nodes according to this 3260 // mostly used order. 3261 ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef(); 3262 // All operands are reordered and used only in this node - propagate the 3263 // most used order to the user node. 3264 MapVector<OrdersType, unsigned, 3265 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3266 OrdersUses; 3267 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3268 for (const TreeEntry *OpTE : OrderedEntries) { 3269 // No need to reorder this nodes, still need to extend and to use shuffle, 3270 // just need to merge reordering shuffle and the reuse shuffle. 3271 if (!OpTE->ReuseShuffleIndices.empty()) 3272 continue; 3273 // Count number of orders uses. 3274 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3275 if (OpTE->State == TreeEntry::NeedToGather) 3276 return GathersToOrders.find(OpTE)->second; 3277 return OpTE->ReorderIndices; 3278 }(); 3279 // Stores actually store the mask, not the order, need to invert. 3280 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3281 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3282 SmallVector<int> Mask; 3283 inversePermutation(Order, Mask); 3284 unsigned E = Order.size(); 3285 OrdersType CurrentOrder(E, E); 3286 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3287 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3288 }); 3289 fixupOrderingIndices(CurrentOrder); 3290 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 3291 } else { 3292 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 3293 } 3294 } 3295 // Set order of the user node. 3296 if (OrdersUses.empty()) 3297 continue; 3298 // Choose the most used order. 3299 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3300 unsigned Cnt = OrdersUses.front().second; 3301 for (const auto &Pair : drop_begin(OrdersUses)) { 3302 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3303 BestOrder = Pair.first; 3304 Cnt = Pair.second; 3305 } 3306 } 3307 // Set order of the user node. 3308 if (BestOrder.empty()) 3309 continue; 3310 SmallVector<int> Mask; 3311 inversePermutation(BestOrder, Mask); 3312 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3313 unsigned E = BestOrder.size(); 3314 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3315 return I < E ? static_cast<int>(I) : UndefMaskElem; 3316 }); 3317 // Do an actual reordering, if profitable. 3318 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 3319 // Just do the reordering for the nodes with the given VF. 3320 if (TE->Scalars.size() != VF) { 3321 if (TE->ReuseShuffleIndices.size() == VF) { 3322 // Need to reorder the reuses masks of the operands with smaller VF to 3323 // be able to find the match between the graph nodes and scalar 3324 // operands of the given node during vectorization/cost estimation. 3325 assert(all_of(TE->UserTreeIndices, 3326 [VF, &TE](const EdgeInfo &EI) { 3327 return EI.UserTE->Scalars.size() == VF || 3328 EI.UserTE->Scalars.size() == 3329 TE->Scalars.size(); 3330 }) && 3331 "All users must be of VF size."); 3332 // Update ordering of the operands with the smaller VF than the given 3333 // one. 3334 reorderReuses(TE->ReuseShuffleIndices, Mask); 3335 } 3336 continue; 3337 } 3338 if (TE->State == TreeEntry::Vectorize && 3339 isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst, 3340 InsertElementInst>(TE->getMainOp()) && 3341 !TE->isAltShuffle()) { 3342 // Build correct orders for extract{element,value}, loads and 3343 // stores. 3344 reorderOrder(TE->ReorderIndices, Mask); 3345 if (isa<InsertElementInst, StoreInst>(TE->getMainOp())) 3346 TE->reorderOperands(Mask); 3347 } else { 3348 // Reorder the node and its operands. 3349 TE->reorderOperands(Mask); 3350 assert(TE->ReorderIndices.empty() && 3351 "Expected empty reorder sequence."); 3352 reorderScalars(TE->Scalars, Mask); 3353 } 3354 if (!TE->ReuseShuffleIndices.empty()) { 3355 // Apply reversed order to keep the original ordering of the reused 3356 // elements to avoid extra reorder indices shuffling. 3357 OrdersType CurrentOrder; 3358 reorderOrder(CurrentOrder, MaskOrder); 3359 SmallVector<int> NewReuses; 3360 inversePermutation(CurrentOrder, NewReuses); 3361 addMask(NewReuses, TE->ReuseShuffleIndices); 3362 TE->ReuseShuffleIndices.swap(NewReuses); 3363 } 3364 } 3365 } 3366 } 3367 3368 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) { 3369 SetVector<TreeEntry *> OrderedEntries; 3370 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3371 // Find all reorderable leaf nodes with the given VF. 3372 // Currently the are vectorized loads,extracts without alternate operands + 3373 // some gathering of extracts. 3374 SmallVector<TreeEntry *> NonVectorized; 3375 for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders, 3376 &NonVectorized]( 3377 const std::unique_ptr<TreeEntry> &TE) { 3378 if (TE->State != TreeEntry::Vectorize) 3379 NonVectorized.push_back(TE.get()); 3380 if (Optional<OrdersType> CurrentOrder = 3381 getReorderingData(*TE.get(), /*TopToBottom=*/false)) { 3382 OrderedEntries.insert(TE.get()); 3383 if (TE->State != TreeEntry::Vectorize) 3384 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3385 } 3386 }); 3387 3388 // Checks if the operands of the users are reordarable and have only single 3389 // use. 3390 auto &&CheckOperands = 3391 [this, &NonVectorized](const auto &Data, 3392 SmallVectorImpl<TreeEntry *> &GatherOps) { 3393 for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) { 3394 if (any_of(Data.second, 3395 [I](const std::pair<unsigned, TreeEntry *> &OpData) { 3396 return OpData.first == I && 3397 OpData.second->State == TreeEntry::Vectorize; 3398 })) 3399 continue; 3400 ArrayRef<Value *> VL = Data.first->getOperand(I); 3401 const TreeEntry *TE = nullptr; 3402 const auto *It = find_if(VL, [this, &TE](Value *V) { 3403 TE = getTreeEntry(V); 3404 return TE; 3405 }); 3406 if (It != VL.end() && TE->isSame(VL)) 3407 return false; 3408 TreeEntry *Gather = nullptr; 3409 if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) { 3410 assert(TE->State != TreeEntry::Vectorize && 3411 "Only non-vectorized nodes are expected."); 3412 if (TE->isSame(VL)) { 3413 Gather = TE; 3414 return true; 3415 } 3416 return false; 3417 }) > 1) 3418 return false; 3419 if (Gather) 3420 GatherOps.push_back(Gather); 3421 } 3422 return true; 3423 }; 3424 // 1. Propagate order to the graph nodes, which use only reordered nodes. 3425 // I.e., if the node has operands, that are reordered, try to make at least 3426 // one operand order in the natural order and reorder others + reorder the 3427 // user node itself. 3428 SmallPtrSet<const TreeEntry *, 4> Visited; 3429 while (!OrderedEntries.empty()) { 3430 // 1. Filter out only reordered nodes. 3431 // 2. If the entry has multiple uses - skip it and jump to the next node. 3432 MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users; 3433 SmallVector<TreeEntry *> Filtered; 3434 for (TreeEntry *TE : OrderedEntries) { 3435 if (!(TE->State == TreeEntry::Vectorize || 3436 (TE->State == TreeEntry::NeedToGather && 3437 GathersToOrders.count(TE))) || 3438 TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() || 3439 !all_of(drop_begin(TE->UserTreeIndices), 3440 [TE](const EdgeInfo &EI) { 3441 return EI.UserTE == TE->UserTreeIndices.front().UserTE; 3442 }) || 3443 !Visited.insert(TE).second) { 3444 Filtered.push_back(TE); 3445 continue; 3446 } 3447 // Build a map between user nodes and their operands order to speedup 3448 // search. The graph currently does not provide this dependency directly. 3449 for (EdgeInfo &EI : TE->UserTreeIndices) { 3450 TreeEntry *UserTE = EI.UserTE; 3451 auto It = Users.find(UserTE); 3452 if (It == Users.end()) 3453 It = Users.insert({UserTE, {}}).first; 3454 It->second.emplace_back(EI.EdgeIdx, TE); 3455 } 3456 } 3457 // Erase filtered entries. 3458 for_each(Filtered, 3459 [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); }); 3460 for (const auto &Data : Users) { 3461 // Check that operands are used only in the User node. 3462 SmallVector<TreeEntry *> GatherOps; 3463 if (!CheckOperands(Data, GatherOps)) { 3464 for_each(Data.second, 3465 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3466 OrderedEntries.remove(Op.second); 3467 }); 3468 continue; 3469 } 3470 // All operands are reordered and used only in this node - propagate the 3471 // most used order to the user node. 3472 MapVector<OrdersType, unsigned, 3473 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3474 OrdersUses; 3475 // Do the analysis for each tree entry only once, otherwise the order of 3476 // the same node my be considered several times, though might be not 3477 // profitable. 3478 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3479 for (const auto &Op : Data.second) { 3480 TreeEntry *OpTE = Op.second; 3481 if (!VisitedOps.insert(OpTE).second) 3482 continue; 3483 if (!OpTE->ReuseShuffleIndices.empty() || 3484 (IgnoreReorder && OpTE == VectorizableTree.front().get())) 3485 continue; 3486 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3487 if (OpTE->State == TreeEntry::NeedToGather) 3488 return GathersToOrders.find(OpTE)->second; 3489 return OpTE->ReorderIndices; 3490 }(); 3491 // Stores actually store the mask, not the order, need to invert. 3492 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3493 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3494 SmallVector<int> Mask; 3495 inversePermutation(Order, Mask); 3496 unsigned E = Order.size(); 3497 OrdersType CurrentOrder(E, E); 3498 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3499 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3500 }); 3501 fixupOrderingIndices(CurrentOrder); 3502 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 3503 } else { 3504 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 3505 } 3506 OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second += 3507 OpTE->UserTreeIndices.size(); 3508 assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0."); 3509 --OrdersUses[{}]; 3510 } 3511 // If no orders - skip current nodes and jump to the next one, if any. 3512 if (OrdersUses.empty()) { 3513 for_each(Data.second, 3514 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3515 OrderedEntries.remove(Op.second); 3516 }); 3517 continue; 3518 } 3519 // Choose the best order. 3520 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3521 unsigned Cnt = OrdersUses.front().second; 3522 for (const auto &Pair : drop_begin(OrdersUses)) { 3523 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3524 BestOrder = Pair.first; 3525 Cnt = Pair.second; 3526 } 3527 } 3528 // Set order of the user node (reordering of operands and user nodes). 3529 if (BestOrder.empty()) { 3530 for_each(Data.second, 3531 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3532 OrderedEntries.remove(Op.second); 3533 }); 3534 continue; 3535 } 3536 // Erase operands from OrderedEntries list and adjust their orders. 3537 VisitedOps.clear(); 3538 SmallVector<int> Mask; 3539 inversePermutation(BestOrder, Mask); 3540 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3541 unsigned E = BestOrder.size(); 3542 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3543 return I < E ? static_cast<int>(I) : UndefMaskElem; 3544 }); 3545 for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) { 3546 TreeEntry *TE = Op.second; 3547 OrderedEntries.remove(TE); 3548 if (!VisitedOps.insert(TE).second) 3549 continue; 3550 if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) { 3551 // Just reorder reuses indices. 3552 reorderReuses(TE->ReuseShuffleIndices, Mask); 3553 continue; 3554 } 3555 // Gathers are processed separately. 3556 if (TE->State != TreeEntry::Vectorize) 3557 continue; 3558 assert((BestOrder.size() == TE->ReorderIndices.size() || 3559 TE->ReorderIndices.empty()) && 3560 "Non-matching sizes of user/operand entries."); 3561 reorderOrder(TE->ReorderIndices, Mask); 3562 } 3563 // For gathers just need to reorder its scalars. 3564 for (TreeEntry *Gather : GatherOps) { 3565 assert(Gather->ReorderIndices.empty() && 3566 "Unexpected reordering of gathers."); 3567 if (!Gather->ReuseShuffleIndices.empty()) { 3568 // Just reorder reuses indices. 3569 reorderReuses(Gather->ReuseShuffleIndices, Mask); 3570 continue; 3571 } 3572 reorderScalars(Gather->Scalars, Mask); 3573 OrderedEntries.remove(Gather); 3574 } 3575 // Reorder operands of the user node and set the ordering for the user 3576 // node itself. 3577 if (Data.first->State != TreeEntry::Vectorize || 3578 !isa<ExtractElementInst, ExtractValueInst, LoadInst>( 3579 Data.first->getMainOp()) || 3580 Data.first->isAltShuffle()) 3581 Data.first->reorderOperands(Mask); 3582 if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) || 3583 Data.first->isAltShuffle()) { 3584 reorderScalars(Data.first->Scalars, Mask); 3585 reorderOrder(Data.first->ReorderIndices, MaskOrder); 3586 if (Data.first->ReuseShuffleIndices.empty() && 3587 !Data.first->ReorderIndices.empty() && 3588 !Data.first->isAltShuffle()) { 3589 // Insert user node to the list to try to sink reordering deeper in 3590 // the graph. 3591 OrderedEntries.insert(Data.first); 3592 } 3593 } else { 3594 reorderOrder(Data.first->ReorderIndices, Mask); 3595 } 3596 } 3597 } 3598 // If the reordering is unnecessary, just remove the reorder. 3599 if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() && 3600 VectorizableTree.front()->ReuseShuffleIndices.empty()) 3601 VectorizableTree.front()->ReorderIndices.clear(); 3602 } 3603 3604 void BoUpSLP::buildExternalUses( 3605 const ExtraValueToDebugLocsMap &ExternallyUsedValues) { 3606 // Collect the values that we need to extract from the tree. 3607 for (auto &TEPtr : VectorizableTree) { 3608 TreeEntry *Entry = TEPtr.get(); 3609 3610 // No need to handle users of gathered values. 3611 if (Entry->State == TreeEntry::NeedToGather) 3612 continue; 3613 3614 // For each lane: 3615 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 3616 Value *Scalar = Entry->Scalars[Lane]; 3617 int FoundLane = Entry->findLaneForValue(Scalar); 3618 3619 // Check if the scalar is externally used as an extra arg. 3620 auto ExtI = ExternallyUsedValues.find(Scalar); 3621 if (ExtI != ExternallyUsedValues.end()) { 3622 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " 3623 << Lane << " from " << *Scalar << ".\n"); 3624 ExternalUses.emplace_back(Scalar, nullptr, FoundLane); 3625 } 3626 for (User *U : Scalar->users()) { 3627 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n"); 3628 3629 Instruction *UserInst = dyn_cast<Instruction>(U); 3630 if (!UserInst) 3631 continue; 3632 3633 if (isDeleted(UserInst)) 3634 continue; 3635 3636 // Skip in-tree scalars that become vectors 3637 if (TreeEntry *UseEntry = getTreeEntry(U)) { 3638 Value *UseScalar = UseEntry->Scalars[0]; 3639 // Some in-tree scalars will remain as scalar in vectorized 3640 // instructions. If that is the case, the one in Lane 0 will 3641 // be used. 3642 if (UseScalar != U || 3643 UseEntry->State == TreeEntry::ScatterVectorize || 3644 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) { 3645 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U 3646 << ".\n"); 3647 assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state"); 3648 continue; 3649 } 3650 } 3651 3652 // Ignore users in the user ignore list. 3653 if (is_contained(UserIgnoreList, UserInst)) 3654 continue; 3655 3656 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " 3657 << Lane << " from " << *Scalar << ".\n"); 3658 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane)); 3659 } 3660 } 3661 } 3662 } 3663 3664 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, 3665 ArrayRef<Value *> UserIgnoreLst) { 3666 deleteTree(); 3667 UserIgnoreList = UserIgnoreLst; 3668 if (!allSameType(Roots)) 3669 return; 3670 buildTree_rec(Roots, 0, EdgeInfo()); 3671 } 3672 3673 namespace { 3674 /// Tracks the state we can represent the loads in the given sequence. 3675 enum class LoadsState { Gather, Vectorize, ScatterVectorize }; 3676 } // anonymous namespace 3677 3678 /// Checks if the given array of loads can be represented as a vectorized, 3679 /// scatter or just simple gather. 3680 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0, 3681 const TargetTransformInfo &TTI, 3682 const DataLayout &DL, ScalarEvolution &SE, 3683 SmallVectorImpl<unsigned> &Order, 3684 SmallVectorImpl<Value *> &PointerOps) { 3685 // Check that a vectorized load would load the same memory as a scalar 3686 // load. For example, we don't want to vectorize loads that are smaller 3687 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 3688 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 3689 // from such a struct, we read/write packed bits disagreeing with the 3690 // unvectorized version. 3691 Type *ScalarTy = VL0->getType(); 3692 3693 if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy)) 3694 return LoadsState::Gather; 3695 3696 // Make sure all loads in the bundle are simple - we can't vectorize 3697 // atomic or volatile loads. 3698 PointerOps.clear(); 3699 PointerOps.resize(VL.size()); 3700 auto *POIter = PointerOps.begin(); 3701 for (Value *V : VL) { 3702 auto *L = cast<LoadInst>(V); 3703 if (!L->isSimple()) 3704 return LoadsState::Gather; 3705 *POIter = L->getPointerOperand(); 3706 ++POIter; 3707 } 3708 3709 Order.clear(); 3710 // Check the order of pointer operands. 3711 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) { 3712 Value *Ptr0; 3713 Value *PtrN; 3714 if (Order.empty()) { 3715 Ptr0 = PointerOps.front(); 3716 PtrN = PointerOps.back(); 3717 } else { 3718 Ptr0 = PointerOps[Order.front()]; 3719 PtrN = PointerOps[Order.back()]; 3720 } 3721 Optional<int> Diff = 3722 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE); 3723 // Check that the sorted loads are consecutive. 3724 if (static_cast<unsigned>(*Diff) == VL.size() - 1) 3725 return LoadsState::Vectorize; 3726 Align CommonAlignment = cast<LoadInst>(VL0)->getAlign(); 3727 for (Value *V : VL) 3728 CommonAlignment = 3729 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 3730 if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()), 3731 CommonAlignment)) 3732 return LoadsState::ScatterVectorize; 3733 } 3734 3735 return LoadsState::Gather; 3736 } 3737 3738 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth, 3739 const EdgeInfo &UserTreeIdx) { 3740 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!"); 3741 3742 SmallVector<int> ReuseShuffleIndicies; 3743 SmallVector<Value *> UniqueValues; 3744 auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues, 3745 &UserTreeIdx, 3746 this](const InstructionsState &S) { 3747 // Check that every instruction appears once in this bundle. 3748 DenseMap<Value *, unsigned> UniquePositions; 3749 for (Value *V : VL) { 3750 if (isConstant(V)) { 3751 ReuseShuffleIndicies.emplace_back( 3752 isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size()); 3753 UniqueValues.emplace_back(V); 3754 continue; 3755 } 3756 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 3757 ReuseShuffleIndicies.emplace_back(Res.first->second); 3758 if (Res.second) 3759 UniqueValues.emplace_back(V); 3760 } 3761 size_t NumUniqueScalarValues = UniqueValues.size(); 3762 if (NumUniqueScalarValues == VL.size()) { 3763 ReuseShuffleIndicies.clear(); 3764 } else { 3765 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n"); 3766 if (NumUniqueScalarValues <= 1 || 3767 (UniquePositions.size() == 1 && all_of(UniqueValues, 3768 [](Value *V) { 3769 return isa<UndefValue>(V) || 3770 !isConstant(V); 3771 })) || 3772 !llvm::isPowerOf2_32(NumUniqueScalarValues)) { 3773 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); 3774 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3775 return false; 3776 } 3777 VL = UniqueValues; 3778 } 3779 return true; 3780 }; 3781 3782 InstructionsState S = getSameOpcode(VL); 3783 if (Depth == RecursionMaxDepth) { 3784 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); 3785 if (TryToFindDuplicates(S)) 3786 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3787 ReuseShuffleIndicies); 3788 return; 3789 } 3790 3791 // Don't handle scalable vectors 3792 if (S.getOpcode() == Instruction::ExtractElement && 3793 isa<ScalableVectorType>( 3794 cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) { 3795 LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n"); 3796 if (TryToFindDuplicates(S)) 3797 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3798 ReuseShuffleIndicies); 3799 return; 3800 } 3801 3802 // Don't handle vectors. 3803 if (S.OpValue->getType()->isVectorTy() && 3804 !isa<InsertElementInst>(S.OpValue)) { 3805 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); 3806 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3807 return; 3808 } 3809 3810 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue)) 3811 if (SI->getValueOperand()->getType()->isVectorTy()) { 3812 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); 3813 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3814 return; 3815 } 3816 3817 // If all of the operands are identical or constant we have a simple solution. 3818 // If we deal with insert/extract instructions, they all must have constant 3819 // indices, otherwise we should gather them, not try to vectorize. 3820 if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() || 3821 (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) && 3822 !all_of(VL, isVectorLikeInstWithConstOps))) { 3823 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n"); 3824 if (TryToFindDuplicates(S)) 3825 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3826 ReuseShuffleIndicies); 3827 return; 3828 } 3829 3830 // We now know that this is a vector of instructions of the same type from 3831 // the same block. 3832 3833 // Don't vectorize ephemeral values. 3834 for (Value *V : VL) { 3835 if (EphValues.count(V)) { 3836 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 3837 << ") is ephemeral.\n"); 3838 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3839 return; 3840 } 3841 } 3842 3843 // Check if this is a duplicate of another entry. 3844 if (TreeEntry *E = getTreeEntry(S.OpValue)) { 3845 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n"); 3846 if (!E->isSame(VL)) { 3847 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); 3848 if (TryToFindDuplicates(S)) 3849 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3850 ReuseShuffleIndicies); 3851 return; 3852 } 3853 // Record the reuse of the tree node. FIXME, currently this is only used to 3854 // properly draw the graph rather than for the actual vectorization. 3855 E->UserTreeIndices.push_back(UserTreeIdx); 3856 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue 3857 << ".\n"); 3858 return; 3859 } 3860 3861 // Check that none of the instructions in the bundle are already in the tree. 3862 for (Value *V : VL) { 3863 auto *I = dyn_cast<Instruction>(V); 3864 if (!I) 3865 continue; 3866 if (getTreeEntry(I)) { 3867 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 3868 << ") is already in tree.\n"); 3869 if (TryToFindDuplicates(S)) 3870 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3871 ReuseShuffleIndicies); 3872 return; 3873 } 3874 } 3875 3876 // The reduction nodes (stored in UserIgnoreList) also should stay scalar. 3877 for (Value *V : VL) { 3878 if (is_contained(UserIgnoreList, V)) { 3879 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n"); 3880 if (TryToFindDuplicates(S)) 3881 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3882 ReuseShuffleIndicies); 3883 return; 3884 } 3885 } 3886 3887 // Check that all of the users of the scalars that we want to vectorize are 3888 // schedulable. 3889 auto *VL0 = cast<Instruction>(S.OpValue); 3890 BasicBlock *BB = VL0->getParent(); 3891 3892 if (!DT->isReachableFromEntry(BB)) { 3893 // Don't go into unreachable blocks. They may contain instructions with 3894 // dependency cycles which confuse the final scheduling. 3895 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n"); 3896 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3897 return; 3898 } 3899 3900 // Check that every instruction appears once in this bundle. 3901 if (!TryToFindDuplicates(S)) 3902 return; 3903 3904 auto &BSRef = BlocksSchedules[BB]; 3905 if (!BSRef) 3906 BSRef = std::make_unique<BlockScheduling>(BB); 3907 3908 BlockScheduling &BS = *BSRef.get(); 3909 3910 Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S); 3911 #ifdef EXPENSIVE_CHECKS 3912 // Make sure we didn't break any internal invariants 3913 BS.verify(); 3914 #endif 3915 if (!Bundle) { 3916 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n"); 3917 assert((!BS.getScheduleData(VL0) || 3918 !BS.getScheduleData(VL0)->isPartOfBundle()) && 3919 "tryScheduleBundle should cancelScheduling on failure"); 3920 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3921 ReuseShuffleIndicies); 3922 return; 3923 } 3924 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); 3925 3926 unsigned ShuffleOrOp = S.isAltShuffle() ? 3927 (unsigned) Instruction::ShuffleVector : S.getOpcode(); 3928 switch (ShuffleOrOp) { 3929 case Instruction::PHI: { 3930 auto *PH = cast<PHINode>(VL0); 3931 3932 // Check for terminator values (e.g. invoke). 3933 for (Value *V : VL) 3934 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 3935 Instruction *Term = dyn_cast<Instruction>( 3936 cast<PHINode>(V)->getIncomingValueForBlock( 3937 PH->getIncomingBlock(I))); 3938 if (Term && Term->isTerminator()) { 3939 LLVM_DEBUG(dbgs() 3940 << "SLP: Need to swizzle PHINodes (terminator use).\n"); 3941 BS.cancelScheduling(VL, VL0); 3942 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3943 ReuseShuffleIndicies); 3944 return; 3945 } 3946 } 3947 3948 TreeEntry *TE = 3949 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies); 3950 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); 3951 3952 // Keeps the reordered operands to avoid code duplication. 3953 SmallVector<ValueList, 2> OperandsVec; 3954 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 3955 if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) { 3956 ValueList Operands(VL.size(), PoisonValue::get(PH->getType())); 3957 TE->setOperand(I, Operands); 3958 OperandsVec.push_back(Operands); 3959 continue; 3960 } 3961 ValueList Operands; 3962 // Prepare the operand vector. 3963 for (Value *V : VL) 3964 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock( 3965 PH->getIncomingBlock(I))); 3966 TE->setOperand(I, Operands); 3967 OperandsVec.push_back(Operands); 3968 } 3969 for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx) 3970 buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx}); 3971 return; 3972 } 3973 case Instruction::ExtractValue: 3974 case Instruction::ExtractElement: { 3975 OrdersType CurrentOrder; 3976 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder); 3977 if (Reuse) { 3978 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n"); 3979 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3980 ReuseShuffleIndicies); 3981 // This is a special case, as it does not gather, but at the same time 3982 // we are not extending buildTree_rec() towards the operands. 3983 ValueList Op0; 3984 Op0.assign(VL.size(), VL0->getOperand(0)); 3985 VectorizableTree.back()->setOperand(0, Op0); 3986 return; 3987 } 3988 if (!CurrentOrder.empty()) { 3989 LLVM_DEBUG({ 3990 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " 3991 "with order"; 3992 for (unsigned Idx : CurrentOrder) 3993 dbgs() << " " << Idx; 3994 dbgs() << "\n"; 3995 }); 3996 fixupOrderingIndices(CurrentOrder); 3997 // Insert new order with initial value 0, if it does not exist, 3998 // otherwise return the iterator to the existing one. 3999 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4000 ReuseShuffleIndicies, CurrentOrder); 4001 // This is a special case, as it does not gather, but at the same time 4002 // we are not extending buildTree_rec() towards the operands. 4003 ValueList Op0; 4004 Op0.assign(VL.size(), VL0->getOperand(0)); 4005 VectorizableTree.back()->setOperand(0, Op0); 4006 return; 4007 } 4008 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n"); 4009 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4010 ReuseShuffleIndicies); 4011 BS.cancelScheduling(VL, VL0); 4012 return; 4013 } 4014 case Instruction::InsertElement: { 4015 assert(ReuseShuffleIndicies.empty() && "All inserts should be unique"); 4016 4017 // Check that we have a buildvector and not a shuffle of 2 or more 4018 // different vectors. 4019 ValueSet SourceVectors; 4020 int MinIdx = std::numeric_limits<int>::max(); 4021 for (Value *V : VL) { 4022 SourceVectors.insert(cast<Instruction>(V)->getOperand(0)); 4023 Optional<int> Idx = *getInsertIndex(V, 0); 4024 if (!Idx || *Idx == UndefMaskElem) 4025 continue; 4026 MinIdx = std::min(MinIdx, *Idx); 4027 } 4028 4029 if (count_if(VL, [&SourceVectors](Value *V) { 4030 return !SourceVectors.contains(V); 4031 }) >= 2) { 4032 // Found 2nd source vector - cancel. 4033 LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with " 4034 "different source vectors.\n"); 4035 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4036 BS.cancelScheduling(VL, VL0); 4037 return; 4038 } 4039 4040 auto OrdCompare = [](const std::pair<int, int> &P1, 4041 const std::pair<int, int> &P2) { 4042 return P1.first > P2.first; 4043 }; 4044 PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>, 4045 decltype(OrdCompare)> 4046 Indices(OrdCompare); 4047 for (int I = 0, E = VL.size(); I < E; ++I) { 4048 Optional<int> Idx = *getInsertIndex(VL[I], 0); 4049 if (!Idx || *Idx == UndefMaskElem) 4050 continue; 4051 Indices.emplace(*Idx, I); 4052 } 4053 OrdersType CurrentOrder(VL.size(), VL.size()); 4054 bool IsIdentity = true; 4055 for (int I = 0, E = VL.size(); I < E; ++I) { 4056 CurrentOrder[Indices.top().second] = I; 4057 IsIdentity &= Indices.top().second == I; 4058 Indices.pop(); 4059 } 4060 if (IsIdentity) 4061 CurrentOrder.clear(); 4062 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4063 None, CurrentOrder); 4064 LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n"); 4065 4066 constexpr int NumOps = 2; 4067 ValueList VectorOperands[NumOps]; 4068 for (int I = 0; I < NumOps; ++I) { 4069 for (Value *V : VL) 4070 VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I)); 4071 4072 TE->setOperand(I, VectorOperands[I]); 4073 } 4074 buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1}); 4075 return; 4076 } 4077 case Instruction::Load: { 4078 // Check that a vectorized load would load the same memory as a scalar 4079 // load. For example, we don't want to vectorize loads that are smaller 4080 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 4081 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 4082 // from such a struct, we read/write packed bits disagreeing with the 4083 // unvectorized version. 4084 SmallVector<Value *> PointerOps; 4085 OrdersType CurrentOrder; 4086 TreeEntry *TE = nullptr; 4087 switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder, 4088 PointerOps)) { 4089 case LoadsState::Vectorize: 4090 if (CurrentOrder.empty()) { 4091 // Original loads are consecutive and does not require reordering. 4092 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4093 ReuseShuffleIndicies); 4094 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n"); 4095 } else { 4096 fixupOrderingIndices(CurrentOrder); 4097 // Need to reorder. 4098 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4099 ReuseShuffleIndicies, CurrentOrder); 4100 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n"); 4101 } 4102 TE->setOperandsInOrder(); 4103 break; 4104 case LoadsState::ScatterVectorize: 4105 // Vectorizing non-consecutive loads with `llvm.masked.gather`. 4106 TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S, 4107 UserTreeIdx, ReuseShuffleIndicies); 4108 TE->setOperandsInOrder(); 4109 buildTree_rec(PointerOps, Depth + 1, {TE, 0}); 4110 LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n"); 4111 break; 4112 case LoadsState::Gather: 4113 BS.cancelScheduling(VL, VL0); 4114 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4115 ReuseShuffleIndicies); 4116 #ifndef NDEBUG 4117 Type *ScalarTy = VL0->getType(); 4118 if (DL->getTypeSizeInBits(ScalarTy) != 4119 DL->getTypeAllocSizeInBits(ScalarTy)) 4120 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n"); 4121 else if (any_of(VL, [](Value *V) { 4122 return !cast<LoadInst>(V)->isSimple(); 4123 })) 4124 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n"); 4125 else 4126 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n"); 4127 #endif // NDEBUG 4128 break; 4129 } 4130 return; 4131 } 4132 case Instruction::ZExt: 4133 case Instruction::SExt: 4134 case Instruction::FPToUI: 4135 case Instruction::FPToSI: 4136 case Instruction::FPExt: 4137 case Instruction::PtrToInt: 4138 case Instruction::IntToPtr: 4139 case Instruction::SIToFP: 4140 case Instruction::UIToFP: 4141 case Instruction::Trunc: 4142 case Instruction::FPTrunc: 4143 case Instruction::BitCast: { 4144 Type *SrcTy = VL0->getOperand(0)->getType(); 4145 for (Value *V : VL) { 4146 Type *Ty = cast<Instruction>(V)->getOperand(0)->getType(); 4147 if (Ty != SrcTy || !isValidElementType(Ty)) { 4148 BS.cancelScheduling(VL, VL0); 4149 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4150 ReuseShuffleIndicies); 4151 LLVM_DEBUG(dbgs() 4152 << "SLP: Gathering casts with different src types.\n"); 4153 return; 4154 } 4155 } 4156 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4157 ReuseShuffleIndicies); 4158 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n"); 4159 4160 TE->setOperandsInOrder(); 4161 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4162 ValueList Operands; 4163 // Prepare the operand vector. 4164 for (Value *V : VL) 4165 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4166 4167 buildTree_rec(Operands, Depth + 1, {TE, i}); 4168 } 4169 return; 4170 } 4171 case Instruction::ICmp: 4172 case Instruction::FCmp: { 4173 // Check that all of the compares have the same predicate. 4174 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 4175 CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0); 4176 Type *ComparedTy = VL0->getOperand(0)->getType(); 4177 for (Value *V : VL) { 4178 CmpInst *Cmp = cast<CmpInst>(V); 4179 if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) || 4180 Cmp->getOperand(0)->getType() != ComparedTy) { 4181 BS.cancelScheduling(VL, VL0); 4182 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4183 ReuseShuffleIndicies); 4184 LLVM_DEBUG(dbgs() 4185 << "SLP: Gathering cmp with different predicate.\n"); 4186 return; 4187 } 4188 } 4189 4190 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4191 ReuseShuffleIndicies); 4192 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n"); 4193 4194 ValueList Left, Right; 4195 if (cast<CmpInst>(VL0)->isCommutative()) { 4196 // Commutative predicate - collect + sort operands of the instructions 4197 // so that each side is more likely to have the same opcode. 4198 assert(P0 == SwapP0 && "Commutative Predicate mismatch"); 4199 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4200 } else { 4201 // Collect operands - commute if it uses the swapped predicate. 4202 for (Value *V : VL) { 4203 auto *Cmp = cast<CmpInst>(V); 4204 Value *LHS = Cmp->getOperand(0); 4205 Value *RHS = Cmp->getOperand(1); 4206 if (Cmp->getPredicate() != P0) 4207 std::swap(LHS, RHS); 4208 Left.push_back(LHS); 4209 Right.push_back(RHS); 4210 } 4211 } 4212 TE->setOperand(0, Left); 4213 TE->setOperand(1, Right); 4214 buildTree_rec(Left, Depth + 1, {TE, 0}); 4215 buildTree_rec(Right, Depth + 1, {TE, 1}); 4216 return; 4217 } 4218 case Instruction::Select: 4219 case Instruction::FNeg: 4220 case Instruction::Add: 4221 case Instruction::FAdd: 4222 case Instruction::Sub: 4223 case Instruction::FSub: 4224 case Instruction::Mul: 4225 case Instruction::FMul: 4226 case Instruction::UDiv: 4227 case Instruction::SDiv: 4228 case Instruction::FDiv: 4229 case Instruction::URem: 4230 case Instruction::SRem: 4231 case Instruction::FRem: 4232 case Instruction::Shl: 4233 case Instruction::LShr: 4234 case Instruction::AShr: 4235 case Instruction::And: 4236 case Instruction::Or: 4237 case Instruction::Xor: { 4238 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4239 ReuseShuffleIndicies); 4240 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n"); 4241 4242 // Sort operands of the instructions so that each side is more likely to 4243 // have the same opcode. 4244 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) { 4245 ValueList Left, Right; 4246 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4247 TE->setOperand(0, Left); 4248 TE->setOperand(1, Right); 4249 buildTree_rec(Left, Depth + 1, {TE, 0}); 4250 buildTree_rec(Right, Depth + 1, {TE, 1}); 4251 return; 4252 } 4253 4254 TE->setOperandsInOrder(); 4255 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4256 ValueList Operands; 4257 // Prepare the operand vector. 4258 for (Value *V : VL) 4259 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4260 4261 buildTree_rec(Operands, Depth + 1, {TE, i}); 4262 } 4263 return; 4264 } 4265 case Instruction::GetElementPtr: { 4266 // We don't combine GEPs with complicated (nested) indexing. 4267 for (Value *V : VL) { 4268 if (cast<Instruction>(V)->getNumOperands() != 2) { 4269 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"); 4270 BS.cancelScheduling(VL, VL0); 4271 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4272 ReuseShuffleIndicies); 4273 return; 4274 } 4275 } 4276 4277 // We can't combine several GEPs into one vector if they operate on 4278 // different types. 4279 Type *Ty0 = VL0->getOperand(0)->getType(); 4280 for (Value *V : VL) { 4281 Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType(); 4282 if (Ty0 != CurTy) { 4283 LLVM_DEBUG(dbgs() 4284 << "SLP: not-vectorizable GEP (different types).\n"); 4285 BS.cancelScheduling(VL, VL0); 4286 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4287 ReuseShuffleIndicies); 4288 return; 4289 } 4290 } 4291 4292 // We don't combine GEPs with non-constant indexes. 4293 Type *Ty1 = VL0->getOperand(1)->getType(); 4294 for (Value *V : VL) { 4295 auto Op = cast<Instruction>(V)->getOperand(1); 4296 if (!isa<ConstantInt>(Op) || 4297 (Op->getType() != Ty1 && 4298 Op->getType()->getScalarSizeInBits() > 4299 DL->getIndexSizeInBits( 4300 V->getType()->getPointerAddressSpace()))) { 4301 LLVM_DEBUG(dbgs() 4302 << "SLP: not-vectorizable GEP (non-constant indexes).\n"); 4303 BS.cancelScheduling(VL, VL0); 4304 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4305 ReuseShuffleIndicies); 4306 return; 4307 } 4308 } 4309 4310 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4311 ReuseShuffleIndicies); 4312 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n"); 4313 SmallVector<ValueList, 2> Operands(2); 4314 // Prepare the operand vector for pointer operands. 4315 for (Value *V : VL) 4316 Operands.front().push_back( 4317 cast<GetElementPtrInst>(V)->getPointerOperand()); 4318 TE->setOperand(0, Operands.front()); 4319 // Need to cast all indices to the same type before vectorization to 4320 // avoid crash. 4321 // Required to be able to find correct matches between different gather 4322 // nodes and reuse the vectorized values rather than trying to gather them 4323 // again. 4324 int IndexIdx = 1; 4325 Type *VL0Ty = VL0->getOperand(IndexIdx)->getType(); 4326 Type *Ty = all_of(VL, 4327 [VL0Ty, IndexIdx](Value *V) { 4328 return VL0Ty == cast<GetElementPtrInst>(V) 4329 ->getOperand(IndexIdx) 4330 ->getType(); 4331 }) 4332 ? VL0Ty 4333 : DL->getIndexType(cast<GetElementPtrInst>(VL0) 4334 ->getPointerOperandType() 4335 ->getScalarType()); 4336 // Prepare the operand vector. 4337 for (Value *V : VL) { 4338 auto *Op = cast<Instruction>(V)->getOperand(IndexIdx); 4339 auto *CI = cast<ConstantInt>(Op); 4340 Operands.back().push_back(ConstantExpr::getIntegerCast( 4341 CI, Ty, CI->getValue().isSignBitSet())); 4342 } 4343 TE->setOperand(IndexIdx, Operands.back()); 4344 4345 for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I) 4346 buildTree_rec(Operands[I], Depth + 1, {TE, I}); 4347 return; 4348 } 4349 case Instruction::Store: { 4350 // Check if the stores are consecutive or if we need to swizzle them. 4351 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType(); 4352 // Avoid types that are padded when being allocated as scalars, while 4353 // being packed together in a vector (such as i1). 4354 if (DL->getTypeSizeInBits(ScalarTy) != 4355 DL->getTypeAllocSizeInBits(ScalarTy)) { 4356 BS.cancelScheduling(VL, VL0); 4357 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4358 ReuseShuffleIndicies); 4359 LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n"); 4360 return; 4361 } 4362 // Make sure all stores in the bundle are simple - we can't vectorize 4363 // atomic or volatile stores. 4364 SmallVector<Value *, 4> PointerOps(VL.size()); 4365 ValueList Operands(VL.size()); 4366 auto POIter = PointerOps.begin(); 4367 auto OIter = Operands.begin(); 4368 for (Value *V : VL) { 4369 auto *SI = cast<StoreInst>(V); 4370 if (!SI->isSimple()) { 4371 BS.cancelScheduling(VL, VL0); 4372 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4373 ReuseShuffleIndicies); 4374 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n"); 4375 return; 4376 } 4377 *POIter = SI->getPointerOperand(); 4378 *OIter = SI->getValueOperand(); 4379 ++POIter; 4380 ++OIter; 4381 } 4382 4383 OrdersType CurrentOrder; 4384 // Check the order of pointer operands. 4385 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) { 4386 Value *Ptr0; 4387 Value *PtrN; 4388 if (CurrentOrder.empty()) { 4389 Ptr0 = PointerOps.front(); 4390 PtrN = PointerOps.back(); 4391 } else { 4392 Ptr0 = PointerOps[CurrentOrder.front()]; 4393 PtrN = PointerOps[CurrentOrder.back()]; 4394 } 4395 Optional<int> Dist = 4396 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE); 4397 // Check that the sorted pointer operands are consecutive. 4398 if (static_cast<unsigned>(*Dist) == VL.size() - 1) { 4399 if (CurrentOrder.empty()) { 4400 // Original stores are consecutive and does not require reordering. 4401 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, 4402 UserTreeIdx, ReuseShuffleIndicies); 4403 TE->setOperandsInOrder(); 4404 buildTree_rec(Operands, Depth + 1, {TE, 0}); 4405 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n"); 4406 } else { 4407 fixupOrderingIndices(CurrentOrder); 4408 TreeEntry *TE = 4409 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4410 ReuseShuffleIndicies, CurrentOrder); 4411 TE->setOperandsInOrder(); 4412 buildTree_rec(Operands, Depth + 1, {TE, 0}); 4413 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n"); 4414 } 4415 return; 4416 } 4417 } 4418 4419 BS.cancelScheduling(VL, VL0); 4420 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4421 ReuseShuffleIndicies); 4422 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n"); 4423 return; 4424 } 4425 case Instruction::Call: { 4426 // Check if the calls are all to the same vectorizable intrinsic or 4427 // library function. 4428 CallInst *CI = cast<CallInst>(VL0); 4429 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4430 4431 VFShape Shape = VFShape::get( 4432 *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())), 4433 false /*HasGlobalPred*/); 4434 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 4435 4436 if (!VecFunc && !isTriviallyVectorizable(ID)) { 4437 BS.cancelScheduling(VL, VL0); 4438 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4439 ReuseShuffleIndicies); 4440 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n"); 4441 return; 4442 } 4443 Function *F = CI->getCalledFunction(); 4444 unsigned NumArgs = CI->arg_size(); 4445 SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr); 4446 for (unsigned j = 0; j != NumArgs; ++j) 4447 if (hasVectorInstrinsicScalarOpd(ID, j)) 4448 ScalarArgs[j] = CI->getArgOperand(j); 4449 for (Value *V : VL) { 4450 CallInst *CI2 = dyn_cast<CallInst>(V); 4451 if (!CI2 || CI2->getCalledFunction() != F || 4452 getVectorIntrinsicIDForCall(CI2, TLI) != ID || 4453 (VecFunc && 4454 VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) || 4455 !CI->hasIdenticalOperandBundleSchema(*CI2)) { 4456 BS.cancelScheduling(VL, VL0); 4457 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4458 ReuseShuffleIndicies); 4459 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V 4460 << "\n"); 4461 return; 4462 } 4463 // Some intrinsics have scalar arguments and should be same in order for 4464 // them to be vectorized. 4465 for (unsigned j = 0; j != NumArgs; ++j) { 4466 if (hasVectorInstrinsicScalarOpd(ID, j)) { 4467 Value *A1J = CI2->getArgOperand(j); 4468 if (ScalarArgs[j] != A1J) { 4469 BS.cancelScheduling(VL, VL0); 4470 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4471 ReuseShuffleIndicies); 4472 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI 4473 << " argument " << ScalarArgs[j] << "!=" << A1J 4474 << "\n"); 4475 return; 4476 } 4477 } 4478 } 4479 // Verify that the bundle operands are identical between the two calls. 4480 if (CI->hasOperandBundles() && 4481 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(), 4482 CI->op_begin() + CI->getBundleOperandsEndIndex(), 4483 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) { 4484 BS.cancelScheduling(VL, VL0); 4485 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4486 ReuseShuffleIndicies); 4487 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" 4488 << *CI << "!=" << *V << '\n'); 4489 return; 4490 } 4491 } 4492 4493 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4494 ReuseShuffleIndicies); 4495 TE->setOperandsInOrder(); 4496 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 4497 // For scalar operands no need to to create an entry since no need to 4498 // vectorize it. 4499 if (hasVectorInstrinsicScalarOpd(ID, i)) 4500 continue; 4501 ValueList Operands; 4502 // Prepare the operand vector. 4503 for (Value *V : VL) { 4504 auto *CI2 = cast<CallInst>(V); 4505 Operands.push_back(CI2->getArgOperand(i)); 4506 } 4507 buildTree_rec(Operands, Depth + 1, {TE, i}); 4508 } 4509 return; 4510 } 4511 case Instruction::ShuffleVector: { 4512 // If this is not an alternate sequence of opcode like add-sub 4513 // then do not vectorize this instruction. 4514 if (!S.isAltShuffle()) { 4515 BS.cancelScheduling(VL, VL0); 4516 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4517 ReuseShuffleIndicies); 4518 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n"); 4519 return; 4520 } 4521 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4522 ReuseShuffleIndicies); 4523 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n"); 4524 4525 // Reorder operands if reordering would enable vectorization. 4526 auto *CI = dyn_cast<CmpInst>(VL0); 4527 if (isa<BinaryOperator>(VL0) || CI) { 4528 ValueList Left, Right; 4529 if (!CI || all_of(VL, [](Value *V) { 4530 return cast<CmpInst>(V)->isCommutative(); 4531 })) { 4532 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4533 } else { 4534 CmpInst::Predicate P0 = CI->getPredicate(); 4535 CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate(); 4536 assert(P0 != AltP0 && 4537 "Expected different main/alternate predicates."); 4538 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 4539 Value *BaseOp0 = VL0->getOperand(0); 4540 Value *BaseOp1 = VL0->getOperand(1); 4541 // Collect operands - commute if it uses the swapped predicate or 4542 // alternate operation. 4543 for (Value *V : VL) { 4544 auto *Cmp = cast<CmpInst>(V); 4545 Value *LHS = Cmp->getOperand(0); 4546 Value *RHS = Cmp->getOperand(1); 4547 CmpInst::Predicate CurrentPred = Cmp->getPredicate(); 4548 if (P0 == AltP0Swapped) { 4549 if ((P0 == CurrentPred && 4550 !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) || 4551 (AltP0 == CurrentPred && 4552 areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))) 4553 std::swap(LHS, RHS); 4554 } else if (P0 != CurrentPred && AltP0 != CurrentPred) { 4555 std::swap(LHS, RHS); 4556 } 4557 Left.push_back(LHS); 4558 Right.push_back(RHS); 4559 } 4560 } 4561 TE->setOperand(0, Left); 4562 TE->setOperand(1, Right); 4563 buildTree_rec(Left, Depth + 1, {TE, 0}); 4564 buildTree_rec(Right, Depth + 1, {TE, 1}); 4565 return; 4566 } 4567 4568 TE->setOperandsInOrder(); 4569 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4570 ValueList Operands; 4571 // Prepare the operand vector. 4572 for (Value *V : VL) 4573 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4574 4575 buildTree_rec(Operands, Depth + 1, {TE, i}); 4576 } 4577 return; 4578 } 4579 default: 4580 BS.cancelScheduling(VL, VL0); 4581 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4582 ReuseShuffleIndicies); 4583 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); 4584 return; 4585 } 4586 } 4587 4588 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const { 4589 unsigned N = 1; 4590 Type *EltTy = T; 4591 4592 while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) || 4593 isa<VectorType>(EltTy)) { 4594 if (auto *ST = dyn_cast<StructType>(EltTy)) { 4595 // Check that struct is homogeneous. 4596 for (const auto *Ty : ST->elements()) 4597 if (Ty != *ST->element_begin()) 4598 return 0; 4599 N *= ST->getNumElements(); 4600 EltTy = *ST->element_begin(); 4601 } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) { 4602 N *= AT->getNumElements(); 4603 EltTy = AT->getElementType(); 4604 } else { 4605 auto *VT = cast<FixedVectorType>(EltTy); 4606 N *= VT->getNumElements(); 4607 EltTy = VT->getElementType(); 4608 } 4609 } 4610 4611 if (!isValidElementType(EltTy)) 4612 return 0; 4613 uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N)); 4614 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T)) 4615 return 0; 4616 return N; 4617 } 4618 4619 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 4620 SmallVectorImpl<unsigned> &CurrentOrder) const { 4621 const auto *It = find_if(VL, [](Value *V) { 4622 return isa<ExtractElementInst, ExtractValueInst>(V); 4623 }); 4624 assert(It != VL.end() && "Expected at least one extract instruction."); 4625 auto *E0 = cast<Instruction>(*It); 4626 assert(all_of(VL, 4627 [](Value *V) { 4628 return isa<UndefValue, ExtractElementInst, ExtractValueInst>( 4629 V); 4630 }) && 4631 "Invalid opcode"); 4632 // Check if all of the extracts come from the same vector and from the 4633 // correct offset. 4634 Value *Vec = E0->getOperand(0); 4635 4636 CurrentOrder.clear(); 4637 4638 // We have to extract from a vector/aggregate with the same number of elements. 4639 unsigned NElts; 4640 if (E0->getOpcode() == Instruction::ExtractValue) { 4641 const DataLayout &DL = E0->getModule()->getDataLayout(); 4642 NElts = canMapToVector(Vec->getType(), DL); 4643 if (!NElts) 4644 return false; 4645 // Check if load can be rewritten as load of vector. 4646 LoadInst *LI = dyn_cast<LoadInst>(Vec); 4647 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size())) 4648 return false; 4649 } else { 4650 NElts = cast<FixedVectorType>(Vec->getType())->getNumElements(); 4651 } 4652 4653 if (NElts != VL.size()) 4654 return false; 4655 4656 // Check that all of the indices extract from the correct offset. 4657 bool ShouldKeepOrder = true; 4658 unsigned E = VL.size(); 4659 // Assign to all items the initial value E + 1 so we can check if the extract 4660 // instruction index was used already. 4661 // Also, later we can check that all the indices are used and we have a 4662 // consecutive access in the extract instructions, by checking that no 4663 // element of CurrentOrder still has value E + 1. 4664 CurrentOrder.assign(E, E); 4665 unsigned I = 0; 4666 for (; I < E; ++I) { 4667 auto *Inst = dyn_cast<Instruction>(VL[I]); 4668 if (!Inst) 4669 continue; 4670 if (Inst->getOperand(0) != Vec) 4671 break; 4672 if (auto *EE = dyn_cast<ExtractElementInst>(Inst)) 4673 if (isa<UndefValue>(EE->getIndexOperand())) 4674 continue; 4675 Optional<unsigned> Idx = getExtractIndex(Inst); 4676 if (!Idx) 4677 break; 4678 const unsigned ExtIdx = *Idx; 4679 if (ExtIdx != I) { 4680 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E) 4681 break; 4682 ShouldKeepOrder = false; 4683 CurrentOrder[ExtIdx] = I; 4684 } else { 4685 if (CurrentOrder[I] != E) 4686 break; 4687 CurrentOrder[I] = I; 4688 } 4689 } 4690 if (I < E) { 4691 CurrentOrder.clear(); 4692 return false; 4693 } 4694 if (ShouldKeepOrder) 4695 CurrentOrder.clear(); 4696 4697 return ShouldKeepOrder; 4698 } 4699 4700 bool BoUpSLP::areAllUsersVectorized(Instruction *I, 4701 ArrayRef<Value *> VectorizedVals) const { 4702 return (I->hasOneUse() && is_contained(VectorizedVals, I)) || 4703 all_of(I->users(), [this](User *U) { 4704 return ScalarToTreeEntry.count(U) > 0 || 4705 isVectorLikeInstWithConstOps(U) || 4706 (isa<ExtractElementInst>(U) && MustGather.contains(U)); 4707 }); 4708 } 4709 4710 static std::pair<InstructionCost, InstructionCost> 4711 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy, 4712 TargetTransformInfo *TTI, TargetLibraryInfo *TLI) { 4713 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4714 4715 // Calculate the cost of the scalar and vector calls. 4716 SmallVector<Type *, 4> VecTys; 4717 for (Use &Arg : CI->args()) 4718 VecTys.push_back( 4719 FixedVectorType::get(Arg->getType(), VecTy->getNumElements())); 4720 FastMathFlags FMF; 4721 if (auto *FPCI = dyn_cast<FPMathOperator>(CI)) 4722 FMF = FPCI->getFastMathFlags(); 4723 SmallVector<const Value *> Arguments(CI->args()); 4724 IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF, 4725 dyn_cast<IntrinsicInst>(CI)); 4726 auto IntrinsicCost = 4727 TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput); 4728 4729 auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 4730 VecTy->getNumElements())), 4731 false /*HasGlobalPred*/); 4732 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 4733 auto LibCost = IntrinsicCost; 4734 if (!CI->isNoBuiltin() && VecFunc) { 4735 // Calculate the cost of the vector library call. 4736 // If the corresponding vector call is cheaper, return its cost. 4737 LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys, 4738 TTI::TCK_RecipThroughput); 4739 } 4740 return {IntrinsicCost, LibCost}; 4741 } 4742 4743 /// Compute the cost of creating a vector of type \p VecTy containing the 4744 /// extracted values from \p VL. 4745 static InstructionCost 4746 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy, 4747 TargetTransformInfo::ShuffleKind ShuffleKind, 4748 ArrayRef<int> Mask, TargetTransformInfo &TTI) { 4749 unsigned NumOfParts = TTI.getNumberOfParts(VecTy); 4750 4751 if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts || 4752 VecTy->getNumElements() < NumOfParts) 4753 return TTI.getShuffleCost(ShuffleKind, VecTy, Mask); 4754 4755 bool AllConsecutive = true; 4756 unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts; 4757 unsigned Idx = -1; 4758 InstructionCost Cost = 0; 4759 4760 // Process extracts in blocks of EltsPerVector to check if the source vector 4761 // operand can be re-used directly. If not, add the cost of creating a shuffle 4762 // to extract the values into a vector register. 4763 for (auto *V : VL) { 4764 ++Idx; 4765 4766 // Need to exclude undefs from analysis. 4767 if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem) 4768 continue; 4769 4770 // Reached the start of a new vector registers. 4771 if (Idx % EltsPerVector == 0) { 4772 AllConsecutive = true; 4773 continue; 4774 } 4775 4776 // Check all extracts for a vector register on the target directly 4777 // extract values in order. 4778 unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V)); 4779 if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) { 4780 unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1])); 4781 AllConsecutive &= PrevIdx + 1 == CurrentIdx && 4782 CurrentIdx % EltsPerVector == Idx % EltsPerVector; 4783 } 4784 4785 if (AllConsecutive) 4786 continue; 4787 4788 // Skip all indices, except for the last index per vector block. 4789 if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size()) 4790 continue; 4791 4792 // If we have a series of extracts which are not consecutive and hence 4793 // cannot re-use the source vector register directly, compute the shuffle 4794 // cost to extract the a vector with EltsPerVector elements. 4795 Cost += TTI.getShuffleCost( 4796 TargetTransformInfo::SK_PermuteSingleSrc, 4797 FixedVectorType::get(VecTy->getElementType(), EltsPerVector)); 4798 } 4799 return Cost; 4800 } 4801 4802 /// Build shuffle mask for shuffle graph entries and lists of main and alternate 4803 /// operations operands. 4804 static void 4805 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices, 4806 ArrayRef<int> ReusesIndices, 4807 const function_ref<bool(Instruction *)> IsAltOp, 4808 SmallVectorImpl<int> &Mask, 4809 SmallVectorImpl<Value *> *OpScalars = nullptr, 4810 SmallVectorImpl<Value *> *AltScalars = nullptr) { 4811 unsigned Sz = VL.size(); 4812 Mask.assign(Sz, UndefMaskElem); 4813 SmallVector<int> OrderMask; 4814 if (!ReorderIndices.empty()) 4815 inversePermutation(ReorderIndices, OrderMask); 4816 for (unsigned I = 0; I < Sz; ++I) { 4817 unsigned Idx = I; 4818 if (!ReorderIndices.empty()) 4819 Idx = OrderMask[I]; 4820 auto *OpInst = cast<Instruction>(VL[Idx]); 4821 if (IsAltOp(OpInst)) { 4822 Mask[I] = Sz + Idx; 4823 if (AltScalars) 4824 AltScalars->push_back(OpInst); 4825 } else { 4826 Mask[I] = Idx; 4827 if (OpScalars) 4828 OpScalars->push_back(OpInst); 4829 } 4830 } 4831 if (!ReusesIndices.empty()) { 4832 SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem); 4833 transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) { 4834 return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem; 4835 }); 4836 Mask.swap(NewMask); 4837 } 4838 } 4839 4840 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E, 4841 ArrayRef<Value *> VectorizedVals) { 4842 ArrayRef<Value*> VL = E->Scalars; 4843 4844 Type *ScalarTy = VL[0]->getType(); 4845 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 4846 ScalarTy = SI->getValueOperand()->getType(); 4847 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0])) 4848 ScalarTy = CI->getOperand(0)->getType(); 4849 else if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 4850 ScalarTy = IE->getOperand(1)->getType(); 4851 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 4852 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 4853 4854 // If we have computed a smaller type for the expression, update VecTy so 4855 // that the costs will be accurate. 4856 if (MinBWs.count(VL[0])) 4857 VecTy = FixedVectorType::get( 4858 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size()); 4859 unsigned EntryVF = E->getVectorFactor(); 4860 auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF); 4861 4862 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 4863 // FIXME: it tries to fix a problem with MSVC buildbots. 4864 TargetTransformInfo &TTIRef = *TTI; 4865 auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy, 4866 VectorizedVals, E](InstructionCost &Cost) { 4867 DenseMap<Value *, int> ExtractVectorsTys; 4868 SmallPtrSet<Value *, 4> CheckedExtracts; 4869 for (auto *V : VL) { 4870 if (isa<UndefValue>(V)) 4871 continue; 4872 // If all users of instruction are going to be vectorized and this 4873 // instruction itself is not going to be vectorized, consider this 4874 // instruction as dead and remove its cost from the final cost of the 4875 // vectorized tree. 4876 // Also, avoid adjusting the cost for extractelements with multiple uses 4877 // in different graph entries. 4878 const TreeEntry *VE = getTreeEntry(V); 4879 if (!CheckedExtracts.insert(V).second || 4880 !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) || 4881 (VE && VE != E)) 4882 continue; 4883 auto *EE = cast<ExtractElementInst>(V); 4884 Optional<unsigned> EEIdx = getExtractIndex(EE); 4885 if (!EEIdx) 4886 continue; 4887 unsigned Idx = *EEIdx; 4888 if (TTIRef.getNumberOfParts(VecTy) != 4889 TTIRef.getNumberOfParts(EE->getVectorOperandType())) { 4890 auto It = 4891 ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first; 4892 It->getSecond() = std::min<int>(It->second, Idx); 4893 } 4894 // Take credit for instruction that will become dead. 4895 if (EE->hasOneUse()) { 4896 Instruction *Ext = EE->user_back(); 4897 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 4898 all_of(Ext->users(), 4899 [](User *U) { return isa<GetElementPtrInst>(U); })) { 4900 // Use getExtractWithExtendCost() to calculate the cost of 4901 // extractelement/ext pair. 4902 Cost -= 4903 TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(), 4904 EE->getVectorOperandType(), Idx); 4905 // Add back the cost of s|zext which is subtracted separately. 4906 Cost += TTIRef.getCastInstrCost( 4907 Ext->getOpcode(), Ext->getType(), EE->getType(), 4908 TTI::getCastContextHint(Ext), CostKind, Ext); 4909 continue; 4910 } 4911 } 4912 Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement, 4913 EE->getVectorOperandType(), Idx); 4914 } 4915 // Add a cost for subvector extracts/inserts if required. 4916 for (const auto &Data : ExtractVectorsTys) { 4917 auto *EEVTy = cast<FixedVectorType>(Data.first->getType()); 4918 unsigned NumElts = VecTy->getNumElements(); 4919 if (Data.second % NumElts == 0) 4920 continue; 4921 if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) { 4922 unsigned Idx = (Data.second / NumElts) * NumElts; 4923 unsigned EENumElts = EEVTy->getNumElements(); 4924 if (Idx + NumElts <= EENumElts) { 4925 Cost += 4926 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 4927 EEVTy, None, Idx, VecTy); 4928 } else { 4929 // Need to round up the subvector type vectorization factor to avoid a 4930 // crash in cost model functions. Make SubVT so that Idx + VF of SubVT 4931 // <= EENumElts. 4932 auto *SubVT = 4933 FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx); 4934 Cost += 4935 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 4936 EEVTy, None, Idx, SubVT); 4937 } 4938 } else { 4939 Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector, 4940 VecTy, None, 0, EEVTy); 4941 } 4942 } 4943 }; 4944 if (E->State == TreeEntry::NeedToGather) { 4945 if (allConstant(VL)) 4946 return 0; 4947 if (isa<InsertElementInst>(VL[0])) 4948 return InstructionCost::getInvalid(); 4949 SmallVector<int> Mask; 4950 SmallVector<const TreeEntry *> Entries; 4951 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 4952 isGatherShuffledEntry(E, Mask, Entries); 4953 if (Shuffle.hasValue()) { 4954 InstructionCost GatherCost = 0; 4955 if (ShuffleVectorInst::isIdentityMask(Mask)) { 4956 // Perfect match in the graph, will reuse the previously vectorized 4957 // node. Cost is 0. 4958 LLVM_DEBUG( 4959 dbgs() 4960 << "SLP: perfect diamond match for gather bundle that starts with " 4961 << *VL.front() << ".\n"); 4962 if (NeedToShuffleReuses) 4963 GatherCost = 4964 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 4965 FinalVecTy, E->ReuseShuffleIndices); 4966 } else { 4967 LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size() 4968 << " entries for bundle that starts with " 4969 << *VL.front() << ".\n"); 4970 // Detected that instead of gather we can emit a shuffle of single/two 4971 // previously vectorized nodes. Add the cost of the permutation rather 4972 // than gather. 4973 ::addMask(Mask, E->ReuseShuffleIndices); 4974 GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask); 4975 } 4976 return GatherCost; 4977 } 4978 if ((E->getOpcode() == Instruction::ExtractElement || 4979 all_of(E->Scalars, 4980 [](Value *V) { 4981 return isa<ExtractElementInst, UndefValue>(V); 4982 })) && 4983 allSameType(VL)) { 4984 // Check that gather of extractelements can be represented as just a 4985 // shuffle of a single/two vectors the scalars are extracted from. 4986 SmallVector<int> Mask; 4987 Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = 4988 isFixedVectorShuffle(VL, Mask); 4989 if (ShuffleKind.hasValue()) { 4990 // Found the bunch of extractelement instructions that must be gathered 4991 // into a vector and can be represented as a permutation elements in a 4992 // single input vector or of 2 input vectors. 4993 InstructionCost Cost = 4994 computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI); 4995 AdjustExtractsCost(Cost); 4996 if (NeedToShuffleReuses) 4997 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 4998 FinalVecTy, E->ReuseShuffleIndices); 4999 return Cost; 5000 } 5001 } 5002 if (isSplat(VL)) { 5003 // Found the broadcasting of the single scalar, calculate the cost as the 5004 // broadcast. 5005 assert(VecTy == FinalVecTy && 5006 "No reused scalars expected for broadcast."); 5007 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy); 5008 } 5009 InstructionCost ReuseShuffleCost = 0; 5010 if (NeedToShuffleReuses) 5011 ReuseShuffleCost = TTI->getShuffleCost( 5012 TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices); 5013 // Improve gather cost for gather of loads, if we can group some of the 5014 // loads into vector loads. 5015 if (VL.size() > 2 && E->getOpcode() == Instruction::Load && 5016 !E->isAltShuffle()) { 5017 BoUpSLP::ValueSet VectorizedLoads; 5018 unsigned StartIdx = 0; 5019 unsigned VF = VL.size() / 2; 5020 unsigned VectorizedCnt = 0; 5021 unsigned ScatterVectorizeCnt = 0; 5022 const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType()); 5023 for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) { 5024 for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End; 5025 Cnt += VF) { 5026 ArrayRef<Value *> Slice = VL.slice(Cnt, VF); 5027 if (!VectorizedLoads.count(Slice.front()) && 5028 !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) { 5029 SmallVector<Value *> PointerOps; 5030 OrdersType CurrentOrder; 5031 LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL, 5032 *SE, CurrentOrder, PointerOps); 5033 switch (LS) { 5034 case LoadsState::Vectorize: 5035 case LoadsState::ScatterVectorize: 5036 // Mark the vectorized loads so that we don't vectorize them 5037 // again. 5038 if (LS == LoadsState::Vectorize) 5039 ++VectorizedCnt; 5040 else 5041 ++ScatterVectorizeCnt; 5042 VectorizedLoads.insert(Slice.begin(), Slice.end()); 5043 // If we vectorized initial block, no need to try to vectorize it 5044 // again. 5045 if (Cnt == StartIdx) 5046 StartIdx += VF; 5047 break; 5048 case LoadsState::Gather: 5049 break; 5050 } 5051 } 5052 } 5053 // Check if the whole array was vectorized already - exit. 5054 if (StartIdx >= VL.size()) 5055 break; 5056 // Found vectorizable parts - exit. 5057 if (!VectorizedLoads.empty()) 5058 break; 5059 } 5060 if (!VectorizedLoads.empty()) { 5061 InstructionCost GatherCost = 0; 5062 unsigned NumParts = TTI->getNumberOfParts(VecTy); 5063 bool NeedInsertSubvectorAnalysis = 5064 !NumParts || (VL.size() / VF) > NumParts; 5065 // Get the cost for gathered loads. 5066 for (unsigned I = 0, End = VL.size(); I < End; I += VF) { 5067 if (VectorizedLoads.contains(VL[I])) 5068 continue; 5069 GatherCost += getGatherCost(VL.slice(I, VF)); 5070 } 5071 // The cost for vectorized loads. 5072 InstructionCost ScalarsCost = 0; 5073 for (Value *V : VectorizedLoads) { 5074 auto *LI = cast<LoadInst>(V); 5075 ScalarsCost += TTI->getMemoryOpCost( 5076 Instruction::Load, LI->getType(), LI->getAlign(), 5077 LI->getPointerAddressSpace(), CostKind, LI); 5078 } 5079 auto *LI = cast<LoadInst>(E->getMainOp()); 5080 auto *LoadTy = FixedVectorType::get(LI->getType(), VF); 5081 Align Alignment = LI->getAlign(); 5082 GatherCost += 5083 VectorizedCnt * 5084 TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment, 5085 LI->getPointerAddressSpace(), CostKind, LI); 5086 GatherCost += ScatterVectorizeCnt * 5087 TTI->getGatherScatterOpCost( 5088 Instruction::Load, LoadTy, LI->getPointerOperand(), 5089 /*VariableMask=*/false, Alignment, CostKind, LI); 5090 if (NeedInsertSubvectorAnalysis) { 5091 // Add the cost for the subvectors insert. 5092 for (int I = VF, E = VL.size(); I < E; I += VF) 5093 GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy, 5094 None, I, LoadTy); 5095 } 5096 return ReuseShuffleCost + GatherCost - ScalarsCost; 5097 } 5098 } 5099 return ReuseShuffleCost + getGatherCost(VL); 5100 } 5101 InstructionCost CommonCost = 0; 5102 SmallVector<int> Mask; 5103 if (!E->ReorderIndices.empty()) { 5104 SmallVector<int> NewMask; 5105 if (E->getOpcode() == Instruction::Store) { 5106 // For stores the order is actually a mask. 5107 NewMask.resize(E->ReorderIndices.size()); 5108 copy(E->ReorderIndices, NewMask.begin()); 5109 } else { 5110 inversePermutation(E->ReorderIndices, NewMask); 5111 } 5112 ::addMask(Mask, NewMask); 5113 } 5114 if (NeedToShuffleReuses) 5115 ::addMask(Mask, E->ReuseShuffleIndices); 5116 if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask)) 5117 CommonCost = 5118 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask); 5119 assert((E->State == TreeEntry::Vectorize || 5120 E->State == TreeEntry::ScatterVectorize) && 5121 "Unhandled state"); 5122 assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL"); 5123 Instruction *VL0 = E->getMainOp(); 5124 unsigned ShuffleOrOp = 5125 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 5126 switch (ShuffleOrOp) { 5127 case Instruction::PHI: 5128 return 0; 5129 5130 case Instruction::ExtractValue: 5131 case Instruction::ExtractElement: { 5132 // The common cost of removal ExtractElement/ExtractValue instructions + 5133 // the cost of shuffles, if required to resuffle the original vector. 5134 if (NeedToShuffleReuses) { 5135 unsigned Idx = 0; 5136 for (unsigned I : E->ReuseShuffleIndices) { 5137 if (ShuffleOrOp == Instruction::ExtractElement) { 5138 auto *EE = cast<ExtractElementInst>(VL[I]); 5139 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 5140 EE->getVectorOperandType(), 5141 *getExtractIndex(EE)); 5142 } else { 5143 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 5144 VecTy, Idx); 5145 ++Idx; 5146 } 5147 } 5148 Idx = EntryVF; 5149 for (Value *V : VL) { 5150 if (ShuffleOrOp == Instruction::ExtractElement) { 5151 auto *EE = cast<ExtractElementInst>(V); 5152 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 5153 EE->getVectorOperandType(), 5154 *getExtractIndex(EE)); 5155 } else { 5156 --Idx; 5157 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 5158 VecTy, Idx); 5159 } 5160 } 5161 } 5162 if (ShuffleOrOp == Instruction::ExtractValue) { 5163 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 5164 auto *EI = cast<Instruction>(VL[I]); 5165 // Take credit for instruction that will become dead. 5166 if (EI->hasOneUse()) { 5167 Instruction *Ext = EI->user_back(); 5168 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 5169 all_of(Ext->users(), 5170 [](User *U) { return isa<GetElementPtrInst>(U); })) { 5171 // Use getExtractWithExtendCost() to calculate the cost of 5172 // extractelement/ext pair. 5173 CommonCost -= TTI->getExtractWithExtendCost( 5174 Ext->getOpcode(), Ext->getType(), VecTy, I); 5175 // Add back the cost of s|zext which is subtracted separately. 5176 CommonCost += TTI->getCastInstrCost( 5177 Ext->getOpcode(), Ext->getType(), EI->getType(), 5178 TTI::getCastContextHint(Ext), CostKind, Ext); 5179 continue; 5180 } 5181 } 5182 CommonCost -= 5183 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I); 5184 } 5185 } else { 5186 AdjustExtractsCost(CommonCost); 5187 } 5188 return CommonCost; 5189 } 5190 case Instruction::InsertElement: { 5191 assert(E->ReuseShuffleIndices.empty() && 5192 "Unique insertelements only are expected."); 5193 auto *SrcVecTy = cast<FixedVectorType>(VL0->getType()); 5194 5195 unsigned const NumElts = SrcVecTy->getNumElements(); 5196 unsigned const NumScalars = VL.size(); 5197 APInt DemandedElts = APInt::getZero(NumElts); 5198 // TODO: Add support for Instruction::InsertValue. 5199 SmallVector<int> Mask; 5200 if (!E->ReorderIndices.empty()) { 5201 inversePermutation(E->ReorderIndices, Mask); 5202 Mask.append(NumElts - NumScalars, UndefMaskElem); 5203 } else { 5204 Mask.assign(NumElts, UndefMaskElem); 5205 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 5206 } 5207 unsigned Offset = *getInsertIndex(VL0, 0); 5208 bool IsIdentity = true; 5209 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 5210 Mask.swap(PrevMask); 5211 for (unsigned I = 0; I < NumScalars; ++I) { 5212 Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0); 5213 if (!InsertIdx || *InsertIdx == UndefMaskElem) 5214 continue; 5215 DemandedElts.setBit(*InsertIdx); 5216 IsIdentity &= *InsertIdx - Offset == I; 5217 Mask[*InsertIdx - Offset] = I; 5218 } 5219 assert(Offset < NumElts && "Failed to find vector index offset"); 5220 5221 InstructionCost Cost = 0; 5222 Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts, 5223 /*Insert*/ true, /*Extract*/ false); 5224 5225 if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) { 5226 // FIXME: Replace with SK_InsertSubvector once it is properly supported. 5227 unsigned Sz = PowerOf2Ceil(Offset + NumScalars); 5228 Cost += TTI->getShuffleCost( 5229 TargetTransformInfo::SK_PermuteSingleSrc, 5230 FixedVectorType::get(SrcVecTy->getElementType(), Sz)); 5231 } else if (!IsIdentity) { 5232 auto *FirstInsert = 5233 cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 5234 return !is_contained(E->Scalars, 5235 cast<Instruction>(V)->getOperand(0)); 5236 })); 5237 if (isUndefVector(FirstInsert->getOperand(0))) { 5238 Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask); 5239 } else { 5240 SmallVector<int> InsertMask(NumElts); 5241 std::iota(InsertMask.begin(), InsertMask.end(), 0); 5242 for (unsigned I = 0; I < NumElts; I++) { 5243 if (Mask[I] != UndefMaskElem) 5244 InsertMask[Offset + I] = NumElts + I; 5245 } 5246 Cost += 5247 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask); 5248 } 5249 } 5250 5251 return Cost; 5252 } 5253 case Instruction::ZExt: 5254 case Instruction::SExt: 5255 case Instruction::FPToUI: 5256 case Instruction::FPToSI: 5257 case Instruction::FPExt: 5258 case Instruction::PtrToInt: 5259 case Instruction::IntToPtr: 5260 case Instruction::SIToFP: 5261 case Instruction::UIToFP: 5262 case Instruction::Trunc: 5263 case Instruction::FPTrunc: 5264 case Instruction::BitCast: { 5265 Type *SrcTy = VL0->getOperand(0)->getType(); 5266 InstructionCost ScalarEltCost = 5267 TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy, 5268 TTI::getCastContextHint(VL0), CostKind, VL0); 5269 if (NeedToShuffleReuses) { 5270 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5271 } 5272 5273 // Calculate the cost of this instruction. 5274 InstructionCost ScalarCost = VL.size() * ScalarEltCost; 5275 5276 auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size()); 5277 InstructionCost VecCost = 0; 5278 // Check if the values are candidates to demote. 5279 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) { 5280 VecCost = CommonCost + TTI->getCastInstrCost( 5281 E->getOpcode(), VecTy, SrcVecTy, 5282 TTI::getCastContextHint(VL0), CostKind, VL0); 5283 } 5284 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5285 return VecCost - ScalarCost; 5286 } 5287 case Instruction::FCmp: 5288 case Instruction::ICmp: 5289 case Instruction::Select: { 5290 // Calculate the cost of this instruction. 5291 InstructionCost ScalarEltCost = 5292 TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 5293 CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0); 5294 if (NeedToShuffleReuses) { 5295 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5296 } 5297 auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size()); 5298 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5299 5300 // Check if all entries in VL are either compares or selects with compares 5301 // as condition that have the same predicates. 5302 CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE; 5303 bool First = true; 5304 for (auto *V : VL) { 5305 CmpInst::Predicate CurrentPred; 5306 auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value()); 5307 if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) && 5308 !match(V, MatchCmp)) || 5309 (!First && VecPred != CurrentPred)) { 5310 VecPred = CmpInst::BAD_ICMP_PREDICATE; 5311 break; 5312 } 5313 First = false; 5314 VecPred = CurrentPred; 5315 } 5316 5317 InstructionCost VecCost = TTI->getCmpSelInstrCost( 5318 E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0); 5319 // Check if it is possible and profitable to use min/max for selects in 5320 // VL. 5321 // 5322 auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL); 5323 if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) { 5324 IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy, 5325 {VecTy, VecTy}); 5326 InstructionCost IntrinsicCost = 5327 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 5328 // If the selects are the only uses of the compares, they will be dead 5329 // and we can adjust the cost by removing their cost. 5330 if (IntrinsicAndUse.second) 5331 IntrinsicCost -= 5332 TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy, 5333 CmpInst::BAD_ICMP_PREDICATE, CostKind); 5334 VecCost = std::min(VecCost, IntrinsicCost); 5335 } 5336 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5337 return CommonCost + VecCost - ScalarCost; 5338 } 5339 case Instruction::FNeg: 5340 case Instruction::Add: 5341 case Instruction::FAdd: 5342 case Instruction::Sub: 5343 case Instruction::FSub: 5344 case Instruction::Mul: 5345 case Instruction::FMul: 5346 case Instruction::UDiv: 5347 case Instruction::SDiv: 5348 case Instruction::FDiv: 5349 case Instruction::URem: 5350 case Instruction::SRem: 5351 case Instruction::FRem: 5352 case Instruction::Shl: 5353 case Instruction::LShr: 5354 case Instruction::AShr: 5355 case Instruction::And: 5356 case Instruction::Or: 5357 case Instruction::Xor: { 5358 // Certain instructions can be cheaper to vectorize if they have a 5359 // constant second vector operand. 5360 TargetTransformInfo::OperandValueKind Op1VK = 5361 TargetTransformInfo::OK_AnyValue; 5362 TargetTransformInfo::OperandValueKind Op2VK = 5363 TargetTransformInfo::OK_UniformConstantValue; 5364 TargetTransformInfo::OperandValueProperties Op1VP = 5365 TargetTransformInfo::OP_None; 5366 TargetTransformInfo::OperandValueProperties Op2VP = 5367 TargetTransformInfo::OP_PowerOf2; 5368 5369 // If all operands are exactly the same ConstantInt then set the 5370 // operand kind to OK_UniformConstantValue. 5371 // If instead not all operands are constants, then set the operand kind 5372 // to OK_AnyValue. If all operands are constants but not the same, 5373 // then set the operand kind to OK_NonUniformConstantValue. 5374 ConstantInt *CInt0 = nullptr; 5375 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 5376 const Instruction *I = cast<Instruction>(VL[i]); 5377 unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0; 5378 ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx)); 5379 if (!CInt) { 5380 Op2VK = TargetTransformInfo::OK_AnyValue; 5381 Op2VP = TargetTransformInfo::OP_None; 5382 break; 5383 } 5384 if (Op2VP == TargetTransformInfo::OP_PowerOf2 && 5385 !CInt->getValue().isPowerOf2()) 5386 Op2VP = TargetTransformInfo::OP_None; 5387 if (i == 0) { 5388 CInt0 = CInt; 5389 continue; 5390 } 5391 if (CInt0 != CInt) 5392 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 5393 } 5394 5395 SmallVector<const Value *, 4> Operands(VL0->operand_values()); 5396 InstructionCost ScalarEltCost = 5397 TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK, 5398 Op2VK, Op1VP, Op2VP, Operands, VL0); 5399 if (NeedToShuffleReuses) { 5400 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5401 } 5402 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5403 InstructionCost VecCost = 5404 TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK, 5405 Op2VK, Op1VP, Op2VP, Operands, VL0); 5406 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5407 return CommonCost + VecCost - ScalarCost; 5408 } 5409 case Instruction::GetElementPtr: { 5410 TargetTransformInfo::OperandValueKind Op1VK = 5411 TargetTransformInfo::OK_AnyValue; 5412 TargetTransformInfo::OperandValueKind Op2VK = 5413 TargetTransformInfo::OK_UniformConstantValue; 5414 5415 InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost( 5416 Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK); 5417 if (NeedToShuffleReuses) { 5418 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5419 } 5420 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5421 InstructionCost VecCost = TTI->getArithmeticInstrCost( 5422 Instruction::Add, VecTy, CostKind, Op1VK, Op2VK); 5423 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5424 return CommonCost + VecCost - ScalarCost; 5425 } 5426 case Instruction::Load: { 5427 // Cost of wide load - cost of scalar loads. 5428 Align Alignment = cast<LoadInst>(VL0)->getAlign(); 5429 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 5430 Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0); 5431 if (NeedToShuffleReuses) { 5432 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5433 } 5434 InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost; 5435 InstructionCost VecLdCost; 5436 if (E->State == TreeEntry::Vectorize) { 5437 VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0, 5438 CostKind, VL0); 5439 } else { 5440 assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState"); 5441 Align CommonAlignment = Alignment; 5442 for (Value *V : VL) 5443 CommonAlignment = 5444 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 5445 VecLdCost = TTI->getGatherScatterOpCost( 5446 Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(), 5447 /*VariableMask=*/false, CommonAlignment, CostKind, VL0); 5448 } 5449 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost)); 5450 return CommonCost + VecLdCost - ScalarLdCost; 5451 } 5452 case Instruction::Store: { 5453 // We know that we can merge the stores. Calculate the cost. 5454 bool IsReorder = !E->ReorderIndices.empty(); 5455 auto *SI = 5456 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0); 5457 Align Alignment = SI->getAlign(); 5458 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 5459 Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0); 5460 InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost; 5461 InstructionCost VecStCost = TTI->getMemoryOpCost( 5462 Instruction::Store, VecTy, Alignment, 0, CostKind, VL0); 5463 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost)); 5464 return CommonCost + VecStCost - ScalarStCost; 5465 } 5466 case Instruction::Call: { 5467 CallInst *CI = cast<CallInst>(VL0); 5468 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 5469 5470 // Calculate the cost of the scalar and vector calls. 5471 IntrinsicCostAttributes CostAttrs(ID, *CI, 1); 5472 InstructionCost ScalarEltCost = 5473 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 5474 if (NeedToShuffleReuses) { 5475 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5476 } 5477 InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost; 5478 5479 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 5480 InstructionCost VecCallCost = 5481 std::min(VecCallCosts.first, VecCallCosts.second); 5482 5483 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost 5484 << " (" << VecCallCost << "-" << ScalarCallCost << ")" 5485 << " for " << *CI << "\n"); 5486 5487 return CommonCost + VecCallCost - ScalarCallCost; 5488 } 5489 case Instruction::ShuffleVector: { 5490 assert(E->isAltShuffle() && 5491 ((Instruction::isBinaryOp(E->getOpcode()) && 5492 Instruction::isBinaryOp(E->getAltOpcode())) || 5493 (Instruction::isCast(E->getOpcode()) && 5494 Instruction::isCast(E->getAltOpcode())) || 5495 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 5496 "Invalid Shuffle Vector Operand"); 5497 InstructionCost ScalarCost = 0; 5498 if (NeedToShuffleReuses) { 5499 for (unsigned Idx : E->ReuseShuffleIndices) { 5500 Instruction *I = cast<Instruction>(VL[Idx]); 5501 CommonCost -= TTI->getInstructionCost(I, CostKind); 5502 } 5503 for (Value *V : VL) { 5504 Instruction *I = cast<Instruction>(V); 5505 CommonCost += TTI->getInstructionCost(I, CostKind); 5506 } 5507 } 5508 for (Value *V : VL) { 5509 Instruction *I = cast<Instruction>(V); 5510 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 5511 ScalarCost += TTI->getInstructionCost(I, CostKind); 5512 } 5513 // VecCost is equal to sum of the cost of creating 2 vectors 5514 // and the cost of creating shuffle. 5515 InstructionCost VecCost = 0; 5516 // Try to find the previous shuffle node with the same operands and same 5517 // main/alternate ops. 5518 auto &&TryFindNodeWithEqualOperands = [this, E]() { 5519 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 5520 if (TE.get() == E) 5521 break; 5522 if (TE->isAltShuffle() && 5523 ((TE->getOpcode() == E->getOpcode() && 5524 TE->getAltOpcode() == E->getAltOpcode()) || 5525 (TE->getOpcode() == E->getAltOpcode() && 5526 TE->getAltOpcode() == E->getOpcode())) && 5527 TE->hasEqualOperands(*E)) 5528 return true; 5529 } 5530 return false; 5531 }; 5532 if (TryFindNodeWithEqualOperands()) { 5533 LLVM_DEBUG({ 5534 dbgs() << "SLP: diamond match for alternate node found.\n"; 5535 E->dump(); 5536 }); 5537 // No need to add new vector costs here since we're going to reuse 5538 // same main/alternate vector ops, just do different shuffling. 5539 } else if (Instruction::isBinaryOp(E->getOpcode())) { 5540 VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind); 5541 VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy, 5542 CostKind); 5543 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 5544 VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, 5545 Builder.getInt1Ty(), 5546 CI0->getPredicate(), CostKind, VL0); 5547 VecCost += TTI->getCmpSelInstrCost( 5548 E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 5549 cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind, 5550 E->getAltOp()); 5551 } else { 5552 Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType(); 5553 Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType(); 5554 auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size()); 5555 auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size()); 5556 VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty, 5557 TTI::CastContextHint::None, CostKind); 5558 VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty, 5559 TTI::CastContextHint::None, CostKind); 5560 } 5561 5562 SmallVector<int> Mask; 5563 buildSuffleEntryMask( 5564 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 5565 [E](Instruction *I) { 5566 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 5567 if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) { 5568 auto *AltCI0 = cast<CmpInst>(E->getAltOp()); 5569 auto *CI = cast<CmpInst>(I); 5570 CmpInst::Predicate P0 = CI0->getPredicate(); 5571 CmpInst::Predicate AltP0 = AltCI0->getPredicate(); 5572 assert(P0 != AltP0 && 5573 "Expected different main/alternate predicates."); 5574 CmpInst::Predicate AltP0Swapped = 5575 CmpInst::getSwappedPredicate(AltP0); 5576 CmpInst::Predicate CurrentPred = CI->getPredicate(); 5577 if (P0 == AltP0Swapped) 5578 return (P0 == CurrentPred && 5579 !areCompatibleCmpOps( 5580 CI0->getOperand(0), CI0->getOperand(1), 5581 CI->getOperand(0), CI->getOperand(1))) || 5582 (AltP0 == CurrentPred && 5583 !areCompatibleCmpOps( 5584 CI0->getOperand(0), CI0->getOperand(1), 5585 CI->getOperand(1), CI->getOperand(0))); 5586 return AltP0 == CurrentPred || AltP0Swapped == CurrentPred; 5587 } 5588 return I->getOpcode() == E->getAltOpcode(); 5589 }, 5590 Mask); 5591 CommonCost = 5592 TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask); 5593 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5594 return CommonCost + VecCost - ScalarCost; 5595 } 5596 default: 5597 llvm_unreachable("Unknown instruction"); 5598 } 5599 } 5600 5601 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const { 5602 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height " 5603 << VectorizableTree.size() << " is fully vectorizable .\n"); 5604 5605 auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) { 5606 SmallVector<int> Mask; 5607 return TE->State == TreeEntry::NeedToGather && 5608 !any_of(TE->Scalars, 5609 [this](Value *V) { return EphValues.contains(V); }) && 5610 (allConstant(TE->Scalars) || isSplat(TE->Scalars) || 5611 TE->Scalars.size() < Limit || 5612 ((TE->getOpcode() == Instruction::ExtractElement || 5613 all_of(TE->Scalars, 5614 [](Value *V) { 5615 return isa<ExtractElementInst, UndefValue>(V); 5616 })) && 5617 isFixedVectorShuffle(TE->Scalars, Mask)) || 5618 (TE->State == TreeEntry::NeedToGather && 5619 TE->getOpcode() == Instruction::Load && !TE->isAltShuffle())); 5620 }; 5621 5622 // We only handle trees of heights 1 and 2. 5623 if (VectorizableTree.size() == 1 && 5624 (VectorizableTree[0]->State == TreeEntry::Vectorize || 5625 (ForReduction && 5626 AreVectorizableGathers(VectorizableTree[0].get(), 5627 VectorizableTree[0]->Scalars.size()) && 5628 VectorizableTree[0]->getVectorFactor() > 2))) 5629 return true; 5630 5631 if (VectorizableTree.size() != 2) 5632 return false; 5633 5634 // Handle splat and all-constants stores. Also try to vectorize tiny trees 5635 // with the second gather nodes if they have less scalar operands rather than 5636 // the initial tree element (may be profitable to shuffle the second gather) 5637 // or they are extractelements, which form shuffle. 5638 SmallVector<int> Mask; 5639 if (VectorizableTree[0]->State == TreeEntry::Vectorize && 5640 AreVectorizableGathers(VectorizableTree[1].get(), 5641 VectorizableTree[0]->Scalars.size())) 5642 return true; 5643 5644 // Gathering cost would be too much for tiny trees. 5645 if (VectorizableTree[0]->State == TreeEntry::NeedToGather || 5646 (VectorizableTree[1]->State == TreeEntry::NeedToGather && 5647 VectorizableTree[0]->State != TreeEntry::ScatterVectorize)) 5648 return false; 5649 5650 return true; 5651 } 5652 5653 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts, 5654 TargetTransformInfo *TTI, 5655 bool MustMatchOrInst) { 5656 // Look past the root to find a source value. Arbitrarily follow the 5657 // path through operand 0 of any 'or'. Also, peek through optional 5658 // shift-left-by-multiple-of-8-bits. 5659 Value *ZextLoad = Root; 5660 const APInt *ShAmtC; 5661 bool FoundOr = false; 5662 while (!isa<ConstantExpr>(ZextLoad) && 5663 (match(ZextLoad, m_Or(m_Value(), m_Value())) || 5664 (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) && 5665 ShAmtC->urem(8) == 0))) { 5666 auto *BinOp = cast<BinaryOperator>(ZextLoad); 5667 ZextLoad = BinOp->getOperand(0); 5668 if (BinOp->getOpcode() == Instruction::Or) 5669 FoundOr = true; 5670 } 5671 // Check if the input is an extended load of the required or/shift expression. 5672 Value *Load; 5673 if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root || 5674 !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load)) 5675 return false; 5676 5677 // Require that the total load bit width is a legal integer type. 5678 // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target. 5679 // But <16 x i8> --> i128 is not, so the backend probably can't reduce it. 5680 Type *SrcTy = Load->getType(); 5681 unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts; 5682 if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth))) 5683 return false; 5684 5685 // Everything matched - assume that we can fold the whole sequence using 5686 // load combining. 5687 LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at " 5688 << *(cast<Instruction>(Root)) << "\n"); 5689 5690 return true; 5691 } 5692 5693 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const { 5694 if (RdxKind != RecurKind::Or) 5695 return false; 5696 5697 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 5698 Value *FirstReduced = VectorizableTree[0]->Scalars[0]; 5699 return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI, 5700 /* MatchOr */ false); 5701 } 5702 5703 bool BoUpSLP::isLoadCombineCandidate() const { 5704 // Peek through a final sequence of stores and check if all operations are 5705 // likely to be load-combined. 5706 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 5707 for (Value *Scalar : VectorizableTree[0]->Scalars) { 5708 Value *X; 5709 if (!match(Scalar, m_Store(m_Value(X), m_Value())) || 5710 !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true)) 5711 return false; 5712 } 5713 return true; 5714 } 5715 5716 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const { 5717 // No need to vectorize inserts of gathered values. 5718 if (VectorizableTree.size() == 2 && 5719 isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) && 5720 VectorizableTree[1]->State == TreeEntry::NeedToGather) 5721 return true; 5722 5723 // We can vectorize the tree if its size is greater than or equal to the 5724 // minimum size specified by the MinTreeSize command line option. 5725 if (VectorizableTree.size() >= MinTreeSize) 5726 return false; 5727 5728 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we 5729 // can vectorize it if we can prove it fully vectorizable. 5730 if (isFullyVectorizableTinyTree(ForReduction)) 5731 return false; 5732 5733 assert(VectorizableTree.empty() 5734 ? ExternalUses.empty() 5735 : true && "We shouldn't have any external users"); 5736 5737 // Otherwise, we can't vectorize the tree. It is both tiny and not fully 5738 // vectorizable. 5739 return true; 5740 } 5741 5742 InstructionCost BoUpSLP::getSpillCost() const { 5743 // Walk from the bottom of the tree to the top, tracking which values are 5744 // live. When we see a call instruction that is not part of our tree, 5745 // query TTI to see if there is a cost to keeping values live over it 5746 // (for example, if spills and fills are required). 5747 unsigned BundleWidth = VectorizableTree.front()->Scalars.size(); 5748 InstructionCost Cost = 0; 5749 5750 SmallPtrSet<Instruction*, 4> LiveValues; 5751 Instruction *PrevInst = nullptr; 5752 5753 // The entries in VectorizableTree are not necessarily ordered by their 5754 // position in basic blocks. Collect them and order them by dominance so later 5755 // instructions are guaranteed to be visited first. For instructions in 5756 // different basic blocks, we only scan to the beginning of the block, so 5757 // their order does not matter, as long as all instructions in a basic block 5758 // are grouped together. Using dominance ensures a deterministic order. 5759 SmallVector<Instruction *, 16> OrderedScalars; 5760 for (const auto &TEPtr : VectorizableTree) { 5761 Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]); 5762 if (!Inst) 5763 continue; 5764 OrderedScalars.push_back(Inst); 5765 } 5766 llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) { 5767 auto *NodeA = DT->getNode(A->getParent()); 5768 auto *NodeB = DT->getNode(B->getParent()); 5769 assert(NodeA && "Should only process reachable instructions"); 5770 assert(NodeB && "Should only process reachable instructions"); 5771 assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && 5772 "Different nodes should have different DFS numbers"); 5773 if (NodeA != NodeB) 5774 return NodeA->getDFSNumIn() < NodeB->getDFSNumIn(); 5775 return B->comesBefore(A); 5776 }); 5777 5778 for (Instruction *Inst : OrderedScalars) { 5779 if (!PrevInst) { 5780 PrevInst = Inst; 5781 continue; 5782 } 5783 5784 // Update LiveValues. 5785 LiveValues.erase(PrevInst); 5786 for (auto &J : PrevInst->operands()) { 5787 if (isa<Instruction>(&*J) && getTreeEntry(&*J)) 5788 LiveValues.insert(cast<Instruction>(&*J)); 5789 } 5790 5791 LLVM_DEBUG({ 5792 dbgs() << "SLP: #LV: " << LiveValues.size(); 5793 for (auto *X : LiveValues) 5794 dbgs() << " " << X->getName(); 5795 dbgs() << ", Looking at "; 5796 Inst->dump(); 5797 }); 5798 5799 // Now find the sequence of instructions between PrevInst and Inst. 5800 unsigned NumCalls = 0; 5801 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(), 5802 PrevInstIt = 5803 PrevInst->getIterator().getReverse(); 5804 while (InstIt != PrevInstIt) { 5805 if (PrevInstIt == PrevInst->getParent()->rend()) { 5806 PrevInstIt = Inst->getParent()->rbegin(); 5807 continue; 5808 } 5809 5810 // Debug information does not impact spill cost. 5811 if ((isa<CallInst>(&*PrevInstIt) && 5812 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) && 5813 &*PrevInstIt != PrevInst) 5814 NumCalls++; 5815 5816 ++PrevInstIt; 5817 } 5818 5819 if (NumCalls) { 5820 SmallVector<Type*, 4> V; 5821 for (auto *II : LiveValues) { 5822 auto *ScalarTy = II->getType(); 5823 if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy)) 5824 ScalarTy = VectorTy->getElementType(); 5825 V.push_back(FixedVectorType::get(ScalarTy, BundleWidth)); 5826 } 5827 Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V); 5828 } 5829 5830 PrevInst = Inst; 5831 } 5832 5833 return Cost; 5834 } 5835 5836 /// Check if two insertelement instructions are from the same buildvector. 5837 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU, 5838 InsertElementInst *V) { 5839 // Instructions must be from the same basic blocks. 5840 if (VU->getParent() != V->getParent()) 5841 return false; 5842 // Checks if 2 insertelements are from the same buildvector. 5843 if (VU->getType() != V->getType()) 5844 return false; 5845 // Multiple used inserts are separate nodes. 5846 if (!VU->hasOneUse() && !V->hasOneUse()) 5847 return false; 5848 auto *IE1 = VU; 5849 auto *IE2 = V; 5850 // Go through the vector operand of insertelement instructions trying to find 5851 // either VU as the original vector for IE2 or V as the original vector for 5852 // IE1. 5853 do { 5854 if (IE2 == VU || IE1 == V) 5855 return true; 5856 if (IE1) { 5857 if (IE1 != VU && !IE1->hasOneUse()) 5858 IE1 = nullptr; 5859 else 5860 IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0)); 5861 } 5862 if (IE2) { 5863 if (IE2 != V && !IE2->hasOneUse()) 5864 IE2 = nullptr; 5865 else 5866 IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0)); 5867 } 5868 } while (IE1 || IE2); 5869 return false; 5870 } 5871 5872 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) { 5873 InstructionCost Cost = 0; 5874 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size " 5875 << VectorizableTree.size() << ".\n"); 5876 5877 unsigned BundleWidth = VectorizableTree[0]->Scalars.size(); 5878 5879 for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) { 5880 TreeEntry &TE = *VectorizableTree[I].get(); 5881 5882 InstructionCost C = getEntryCost(&TE, VectorizedVals); 5883 Cost += C; 5884 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 5885 << " for bundle that starts with " << *TE.Scalars[0] 5886 << ".\n" 5887 << "SLP: Current total cost = " << Cost << "\n"); 5888 } 5889 5890 SmallPtrSet<Value *, 16> ExtractCostCalculated; 5891 InstructionCost ExtractCost = 0; 5892 SmallVector<unsigned> VF; 5893 SmallVector<SmallVector<int>> ShuffleMask; 5894 SmallVector<Value *> FirstUsers; 5895 SmallVector<APInt> DemandedElts; 5896 for (ExternalUser &EU : ExternalUses) { 5897 // We only add extract cost once for the same scalar. 5898 if (!isa_and_nonnull<InsertElementInst>(EU.User) && 5899 !ExtractCostCalculated.insert(EU.Scalar).second) 5900 continue; 5901 5902 // Uses by ephemeral values are free (because the ephemeral value will be 5903 // removed prior to code generation, and so the extraction will be 5904 // removed as well). 5905 if (EphValues.count(EU.User)) 5906 continue; 5907 5908 // No extract cost for vector "scalar" 5909 if (isa<FixedVectorType>(EU.Scalar->getType())) 5910 continue; 5911 5912 // Already counted the cost for external uses when tried to adjust the cost 5913 // for extractelements, no need to add it again. 5914 if (isa<ExtractElementInst>(EU.Scalar)) 5915 continue; 5916 5917 // If found user is an insertelement, do not calculate extract cost but try 5918 // to detect it as a final shuffled/identity match. 5919 if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) { 5920 if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) { 5921 Optional<int> InsertIdx = getInsertIndex(VU, 0); 5922 if (!InsertIdx || *InsertIdx == UndefMaskElem) 5923 continue; 5924 auto *It = find_if(FirstUsers, [VU](Value *V) { 5925 return areTwoInsertFromSameBuildVector(VU, 5926 cast<InsertElementInst>(V)); 5927 }); 5928 int VecId = -1; 5929 if (It == FirstUsers.end()) { 5930 VF.push_back(FTy->getNumElements()); 5931 ShuffleMask.emplace_back(VF.back(), UndefMaskElem); 5932 // Find the insertvector, vectorized in tree, if any. 5933 Value *Base = VU; 5934 while (isa<InsertElementInst>(Base)) { 5935 // Build the mask for the vectorized insertelement instructions. 5936 if (const TreeEntry *E = getTreeEntry(Base)) { 5937 VU = cast<InsertElementInst>(Base); 5938 do { 5939 int Idx = E->findLaneForValue(Base); 5940 ShuffleMask.back()[Idx] = Idx; 5941 Base = cast<InsertElementInst>(Base)->getOperand(0); 5942 } while (E == getTreeEntry(Base)); 5943 break; 5944 } 5945 Base = cast<InsertElementInst>(Base)->getOperand(0); 5946 } 5947 FirstUsers.push_back(VU); 5948 DemandedElts.push_back(APInt::getZero(VF.back())); 5949 VecId = FirstUsers.size() - 1; 5950 } else { 5951 VecId = std::distance(FirstUsers.begin(), It); 5952 } 5953 int Idx = *InsertIdx; 5954 ShuffleMask[VecId][Idx] = EU.Lane; 5955 DemandedElts[VecId].setBit(Idx); 5956 continue; 5957 } 5958 } 5959 5960 // If we plan to rewrite the tree in a smaller type, we will need to sign 5961 // extend the extracted value back to the original type. Here, we account 5962 // for the extract and the added cost of the sign extend if needed. 5963 auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth); 5964 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 5965 if (MinBWs.count(ScalarRoot)) { 5966 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 5967 auto Extend = 5968 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt; 5969 VecTy = FixedVectorType::get(MinTy, BundleWidth); 5970 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(), 5971 VecTy, EU.Lane); 5972 } else { 5973 ExtractCost += 5974 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane); 5975 } 5976 } 5977 5978 InstructionCost SpillCost = getSpillCost(); 5979 Cost += SpillCost + ExtractCost; 5980 if (FirstUsers.size() == 1) { 5981 int Limit = ShuffleMask.front().size() * 2; 5982 if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) && 5983 !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) { 5984 InstructionCost C = TTI->getShuffleCost( 5985 TTI::SK_PermuteSingleSrc, 5986 cast<FixedVectorType>(FirstUsers.front()->getType()), 5987 ShuffleMask.front()); 5988 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 5989 << " for final shuffle of insertelement external users " 5990 << *VectorizableTree.front()->Scalars.front() << ".\n" 5991 << "SLP: Current total cost = " << Cost << "\n"); 5992 Cost += C; 5993 } 5994 InstructionCost InsertCost = TTI->getScalarizationOverhead( 5995 cast<FixedVectorType>(FirstUsers.front()->getType()), 5996 DemandedElts.front(), /*Insert*/ true, /*Extract*/ false); 5997 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 5998 << " for insertelements gather.\n" 5999 << "SLP: Current total cost = " << Cost << "\n"); 6000 Cost -= InsertCost; 6001 } else if (FirstUsers.size() >= 2) { 6002 unsigned MaxVF = *std::max_element(VF.begin(), VF.end()); 6003 // Combined masks of the first 2 vectors. 6004 SmallVector<int> CombinedMask(MaxVF, UndefMaskElem); 6005 copy(ShuffleMask.front(), CombinedMask.begin()); 6006 APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF); 6007 auto *VecTy = FixedVectorType::get( 6008 cast<VectorType>(FirstUsers.front()->getType())->getElementType(), 6009 MaxVF); 6010 for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) { 6011 if (ShuffleMask[1][I] != UndefMaskElem) { 6012 CombinedMask[I] = ShuffleMask[1][I] + MaxVF; 6013 CombinedDemandedElts.setBit(I); 6014 } 6015 } 6016 InstructionCost C = 6017 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask); 6018 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6019 << " for final shuffle of vector node and external " 6020 "insertelement users " 6021 << *VectorizableTree.front()->Scalars.front() << ".\n" 6022 << "SLP: Current total cost = " << Cost << "\n"); 6023 Cost += C; 6024 InstructionCost InsertCost = TTI->getScalarizationOverhead( 6025 VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false); 6026 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 6027 << " for insertelements gather.\n" 6028 << "SLP: Current total cost = " << Cost << "\n"); 6029 Cost -= InsertCost; 6030 for (int I = 2, E = FirstUsers.size(); I < E; ++I) { 6031 // Other elements - permutation of 2 vectors (the initial one and the 6032 // next Ith incoming vector). 6033 unsigned VF = ShuffleMask[I].size(); 6034 for (unsigned Idx = 0; Idx < VF; ++Idx) { 6035 int Mask = ShuffleMask[I][Idx]; 6036 if (Mask != UndefMaskElem) 6037 CombinedMask[Idx] = MaxVF + Mask; 6038 else if (CombinedMask[Idx] != UndefMaskElem) 6039 CombinedMask[Idx] = Idx; 6040 } 6041 for (unsigned Idx = VF; Idx < MaxVF; ++Idx) 6042 if (CombinedMask[Idx] != UndefMaskElem) 6043 CombinedMask[Idx] = Idx; 6044 InstructionCost C = 6045 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask); 6046 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6047 << " for final shuffle of vector node and external " 6048 "insertelement users " 6049 << *VectorizableTree.front()->Scalars.front() << ".\n" 6050 << "SLP: Current total cost = " << Cost << "\n"); 6051 Cost += C; 6052 InstructionCost InsertCost = TTI->getScalarizationOverhead( 6053 cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I], 6054 /*Insert*/ true, /*Extract*/ false); 6055 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 6056 << " for insertelements gather.\n" 6057 << "SLP: Current total cost = " << Cost << "\n"); 6058 Cost -= InsertCost; 6059 } 6060 } 6061 6062 #ifndef NDEBUG 6063 SmallString<256> Str; 6064 { 6065 raw_svector_ostream OS(Str); 6066 OS << "SLP: Spill Cost = " << SpillCost << ".\n" 6067 << "SLP: Extract Cost = " << ExtractCost << ".\n" 6068 << "SLP: Total Cost = " << Cost << ".\n"; 6069 } 6070 LLVM_DEBUG(dbgs() << Str); 6071 if (ViewSLPTree) 6072 ViewGraph(this, "SLP" + F->getName(), false, Str); 6073 #endif 6074 6075 return Cost; 6076 } 6077 6078 Optional<TargetTransformInfo::ShuffleKind> 6079 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 6080 SmallVectorImpl<const TreeEntry *> &Entries) { 6081 // TODO: currently checking only for Scalars in the tree entry, need to count 6082 // reused elements too for better cost estimation. 6083 Mask.assign(TE->Scalars.size(), UndefMaskElem); 6084 Entries.clear(); 6085 // Build a lists of values to tree entries. 6086 DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs; 6087 for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) { 6088 if (EntryPtr.get() == TE) 6089 break; 6090 if (EntryPtr->State != TreeEntry::NeedToGather) 6091 continue; 6092 for (Value *V : EntryPtr->Scalars) 6093 ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get()); 6094 } 6095 // Find all tree entries used by the gathered values. If no common entries 6096 // found - not a shuffle. 6097 // Here we build a set of tree nodes for each gathered value and trying to 6098 // find the intersection between these sets. If we have at least one common 6099 // tree node for each gathered value - we have just a permutation of the 6100 // single vector. If we have 2 different sets, we're in situation where we 6101 // have a permutation of 2 input vectors. 6102 SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs; 6103 DenseMap<Value *, int> UsedValuesEntry; 6104 for (Value *V : TE->Scalars) { 6105 if (isa<UndefValue>(V)) 6106 continue; 6107 // Build a list of tree entries where V is used. 6108 SmallPtrSet<const TreeEntry *, 4> VToTEs; 6109 auto It = ValueToTEs.find(V); 6110 if (It != ValueToTEs.end()) 6111 VToTEs = It->second; 6112 if (const TreeEntry *VTE = getTreeEntry(V)) 6113 VToTEs.insert(VTE); 6114 if (VToTEs.empty()) 6115 return None; 6116 if (UsedTEs.empty()) { 6117 // The first iteration, just insert the list of nodes to vector. 6118 UsedTEs.push_back(VToTEs); 6119 } else { 6120 // Need to check if there are any previously used tree nodes which use V. 6121 // If there are no such nodes, consider that we have another one input 6122 // vector. 6123 SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs); 6124 unsigned Idx = 0; 6125 for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) { 6126 // Do we have a non-empty intersection of previously listed tree entries 6127 // and tree entries using current V? 6128 set_intersect(VToTEs, Set); 6129 if (!VToTEs.empty()) { 6130 // Yes, write the new subset and continue analysis for the next 6131 // scalar. 6132 Set.swap(VToTEs); 6133 break; 6134 } 6135 VToTEs = SavedVToTEs; 6136 ++Idx; 6137 } 6138 // No non-empty intersection found - need to add a second set of possible 6139 // source vectors. 6140 if (Idx == UsedTEs.size()) { 6141 // If the number of input vectors is greater than 2 - not a permutation, 6142 // fallback to the regular gather. 6143 if (UsedTEs.size() == 2) 6144 return None; 6145 UsedTEs.push_back(SavedVToTEs); 6146 Idx = UsedTEs.size() - 1; 6147 } 6148 UsedValuesEntry.try_emplace(V, Idx); 6149 } 6150 } 6151 6152 unsigned VF = 0; 6153 if (UsedTEs.size() == 1) { 6154 // Try to find the perfect match in another gather node at first. 6155 auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) { 6156 return EntryPtr->isSame(TE->Scalars); 6157 }); 6158 if (It != UsedTEs.front().end()) { 6159 Entries.push_back(*It); 6160 std::iota(Mask.begin(), Mask.end(), 0); 6161 return TargetTransformInfo::SK_PermuteSingleSrc; 6162 } 6163 // No perfect match, just shuffle, so choose the first tree node. 6164 Entries.push_back(*UsedTEs.front().begin()); 6165 } else { 6166 // Try to find nodes with the same vector factor. 6167 assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries."); 6168 DenseMap<int, const TreeEntry *> VFToTE; 6169 for (const TreeEntry *TE : UsedTEs.front()) 6170 VFToTE.try_emplace(TE->getVectorFactor(), TE); 6171 for (const TreeEntry *TE : UsedTEs.back()) { 6172 auto It = VFToTE.find(TE->getVectorFactor()); 6173 if (It != VFToTE.end()) { 6174 VF = It->first; 6175 Entries.push_back(It->second); 6176 Entries.push_back(TE); 6177 break; 6178 } 6179 } 6180 // No 2 source vectors with the same vector factor - give up and do regular 6181 // gather. 6182 if (Entries.empty()) 6183 return None; 6184 } 6185 6186 // Build a shuffle mask for better cost estimation and vector emission. 6187 for (int I = 0, E = TE->Scalars.size(); I < E; ++I) { 6188 Value *V = TE->Scalars[I]; 6189 if (isa<UndefValue>(V)) 6190 continue; 6191 unsigned Idx = UsedValuesEntry.lookup(V); 6192 const TreeEntry *VTE = Entries[Idx]; 6193 int FoundLane = VTE->findLaneForValue(V); 6194 Mask[I] = Idx * VF + FoundLane; 6195 // Extra check required by isSingleSourceMaskImpl function (called by 6196 // ShuffleVectorInst::isSingleSourceMask). 6197 if (Mask[I] >= 2 * E) 6198 return None; 6199 } 6200 switch (Entries.size()) { 6201 case 1: 6202 return TargetTransformInfo::SK_PermuteSingleSrc; 6203 case 2: 6204 return TargetTransformInfo::SK_PermuteTwoSrc; 6205 default: 6206 break; 6207 } 6208 return None; 6209 } 6210 6211 InstructionCost 6212 BoUpSLP::getGatherCost(FixedVectorType *Ty, 6213 const DenseSet<unsigned> &ShuffledIndices, 6214 bool NeedToShuffle) const { 6215 unsigned NumElts = Ty->getNumElements(); 6216 APInt DemandedElts = APInt::getZero(NumElts); 6217 for (unsigned I = 0; I < NumElts; ++I) 6218 if (!ShuffledIndices.count(I)) 6219 DemandedElts.setBit(I); 6220 InstructionCost Cost = 6221 TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true, 6222 /*Extract*/ false); 6223 if (NeedToShuffle) 6224 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty); 6225 return Cost; 6226 } 6227 6228 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const { 6229 // Find the type of the operands in VL. 6230 Type *ScalarTy = VL[0]->getType(); 6231 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 6232 ScalarTy = SI->getValueOperand()->getType(); 6233 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 6234 bool DuplicateNonConst = false; 6235 // Find the cost of inserting/extracting values from the vector. 6236 // Check if the same elements are inserted several times and count them as 6237 // shuffle candidates. 6238 DenseSet<unsigned> ShuffledElements; 6239 DenseSet<Value *> UniqueElements; 6240 // Iterate in reverse order to consider insert elements with the high cost. 6241 for (unsigned I = VL.size(); I > 0; --I) { 6242 unsigned Idx = I - 1; 6243 // No need to shuffle duplicates for constants. 6244 if (isConstant(VL[Idx])) { 6245 ShuffledElements.insert(Idx); 6246 continue; 6247 } 6248 if (!UniqueElements.insert(VL[Idx]).second) { 6249 DuplicateNonConst = true; 6250 ShuffledElements.insert(Idx); 6251 } 6252 } 6253 return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst); 6254 } 6255 6256 // Perform operand reordering on the instructions in VL and return the reordered 6257 // operands in Left and Right. 6258 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 6259 SmallVectorImpl<Value *> &Left, 6260 SmallVectorImpl<Value *> &Right, 6261 const DataLayout &DL, 6262 ScalarEvolution &SE, 6263 const BoUpSLP &R) { 6264 if (VL.empty()) 6265 return; 6266 VLOperands Ops(VL, DL, SE, R); 6267 // Reorder the operands in place. 6268 Ops.reorder(); 6269 Left = Ops.getVL(0); 6270 Right = Ops.getVL(1); 6271 } 6272 6273 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) { 6274 // Get the basic block this bundle is in. All instructions in the bundle 6275 // should be in this block. 6276 auto *Front = E->getMainOp(); 6277 auto *BB = Front->getParent(); 6278 assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool { 6279 auto *I = cast<Instruction>(V); 6280 return !E->isOpcodeOrAlt(I) || I->getParent() == BB; 6281 })); 6282 6283 // The last instruction in the bundle in program order. 6284 Instruction *LastInst = nullptr; 6285 6286 // Find the last instruction. The common case should be that BB has been 6287 // scheduled, and the last instruction is VL.back(). So we start with 6288 // VL.back() and iterate over schedule data until we reach the end of the 6289 // bundle. The end of the bundle is marked by null ScheduleData. 6290 if (BlocksSchedules.count(BB)) { 6291 auto *Bundle = 6292 BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back())); 6293 if (Bundle && Bundle->isPartOfBundle()) 6294 for (; Bundle; Bundle = Bundle->NextInBundle) 6295 if (Bundle->OpValue == Bundle->Inst) 6296 LastInst = Bundle->Inst; 6297 } 6298 6299 // LastInst can still be null at this point if there's either not an entry 6300 // for BB in BlocksSchedules or there's no ScheduleData available for 6301 // VL.back(). This can be the case if buildTree_rec aborts for various 6302 // reasons (e.g., the maximum recursion depth is reached, the maximum region 6303 // size is reached, etc.). ScheduleData is initialized in the scheduling 6304 // "dry-run". 6305 // 6306 // If this happens, we can still find the last instruction by brute force. We 6307 // iterate forwards from Front (inclusive) until we either see all 6308 // instructions in the bundle or reach the end of the block. If Front is the 6309 // last instruction in program order, LastInst will be set to Front, and we 6310 // will visit all the remaining instructions in the block. 6311 // 6312 // One of the reasons we exit early from buildTree_rec is to place an upper 6313 // bound on compile-time. Thus, taking an additional compile-time hit here is 6314 // not ideal. However, this should be exceedingly rare since it requires that 6315 // we both exit early from buildTree_rec and that the bundle be out-of-order 6316 // (causing us to iterate all the way to the end of the block). 6317 if (!LastInst) { 6318 SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end()); 6319 for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) { 6320 if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I)) 6321 LastInst = &I; 6322 if (Bundle.empty()) 6323 break; 6324 } 6325 } 6326 assert(LastInst && "Failed to find last instruction in bundle"); 6327 6328 // Set the insertion point after the last instruction in the bundle. Set the 6329 // debug location to Front. 6330 Builder.SetInsertPoint(BB, ++LastInst->getIterator()); 6331 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 6332 } 6333 6334 Value *BoUpSLP::gather(ArrayRef<Value *> VL) { 6335 // List of instructions/lanes from current block and/or the blocks which are 6336 // part of the current loop. These instructions will be inserted at the end to 6337 // make it possible to optimize loops and hoist invariant instructions out of 6338 // the loops body with better chances for success. 6339 SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts; 6340 SmallSet<int, 4> PostponedIndices; 6341 Loop *L = LI->getLoopFor(Builder.GetInsertBlock()); 6342 auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) { 6343 SmallPtrSet<BasicBlock *, 4> Visited; 6344 while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second) 6345 InsertBB = InsertBB->getSinglePredecessor(); 6346 return InsertBB && InsertBB == InstBB; 6347 }; 6348 for (int I = 0, E = VL.size(); I < E; ++I) { 6349 if (auto *Inst = dyn_cast<Instruction>(VL[I])) 6350 if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) || 6351 getTreeEntry(Inst) || (L && (L->contains(Inst)))) && 6352 PostponedIndices.insert(I).second) 6353 PostponedInsts.emplace_back(Inst, I); 6354 } 6355 6356 auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) { 6357 Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos)); 6358 auto *InsElt = dyn_cast<InsertElementInst>(Vec); 6359 if (!InsElt) 6360 return Vec; 6361 GatherShuffleSeq.insert(InsElt); 6362 CSEBlocks.insert(InsElt->getParent()); 6363 // Add to our 'need-to-extract' list. 6364 if (TreeEntry *Entry = getTreeEntry(V)) { 6365 // Find which lane we need to extract. 6366 unsigned FoundLane = Entry->findLaneForValue(V); 6367 ExternalUses.emplace_back(V, InsElt, FoundLane); 6368 } 6369 return Vec; 6370 }; 6371 Value *Val0 = 6372 isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0]; 6373 FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size()); 6374 Value *Vec = PoisonValue::get(VecTy); 6375 SmallVector<int> NonConsts; 6376 // Insert constant values at first. 6377 for (int I = 0, E = VL.size(); I < E; ++I) { 6378 if (PostponedIndices.contains(I)) 6379 continue; 6380 if (!isConstant(VL[I])) { 6381 NonConsts.push_back(I); 6382 continue; 6383 } 6384 Vec = CreateInsertElement(Vec, VL[I], I); 6385 } 6386 // Insert non-constant values. 6387 for (int I : NonConsts) 6388 Vec = CreateInsertElement(Vec, VL[I], I); 6389 // Append instructions, which are/may be part of the loop, in the end to make 6390 // it possible to hoist non-loop-based instructions. 6391 for (const std::pair<Value *, unsigned> &Pair : PostponedInsts) 6392 Vec = CreateInsertElement(Vec, Pair.first, Pair.second); 6393 6394 return Vec; 6395 } 6396 6397 namespace { 6398 /// Merges shuffle masks and emits final shuffle instruction, if required. 6399 class ShuffleInstructionBuilder { 6400 IRBuilderBase &Builder; 6401 const unsigned VF = 0; 6402 bool IsFinalized = false; 6403 SmallVector<int, 4> Mask; 6404 /// Holds all of the instructions that we gathered. 6405 SetVector<Instruction *> &GatherShuffleSeq; 6406 /// A list of blocks that we are going to CSE. 6407 SetVector<BasicBlock *> &CSEBlocks; 6408 6409 public: 6410 ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF, 6411 SetVector<Instruction *> &GatherShuffleSeq, 6412 SetVector<BasicBlock *> &CSEBlocks) 6413 : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq), 6414 CSEBlocks(CSEBlocks) {} 6415 6416 /// Adds a mask, inverting it before applying. 6417 void addInversedMask(ArrayRef<unsigned> SubMask) { 6418 if (SubMask.empty()) 6419 return; 6420 SmallVector<int, 4> NewMask; 6421 inversePermutation(SubMask, NewMask); 6422 addMask(NewMask); 6423 } 6424 6425 /// Functions adds masks, merging them into single one. 6426 void addMask(ArrayRef<unsigned> SubMask) { 6427 SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end()); 6428 addMask(NewMask); 6429 } 6430 6431 void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); } 6432 6433 Value *finalize(Value *V) { 6434 IsFinalized = true; 6435 unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements(); 6436 if (VF == ValueVF && Mask.empty()) 6437 return V; 6438 SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem); 6439 std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0); 6440 addMask(NormalizedMask); 6441 6442 if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask)) 6443 return V; 6444 Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle"); 6445 if (auto *I = dyn_cast<Instruction>(Vec)) { 6446 GatherShuffleSeq.insert(I); 6447 CSEBlocks.insert(I->getParent()); 6448 } 6449 return Vec; 6450 } 6451 6452 ~ShuffleInstructionBuilder() { 6453 assert((IsFinalized || Mask.empty()) && 6454 "Shuffle construction must be finalized."); 6455 } 6456 }; 6457 } // namespace 6458 6459 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { 6460 unsigned VF = VL.size(); 6461 InstructionsState S = getSameOpcode(VL); 6462 if (S.getOpcode()) { 6463 if (TreeEntry *E = getTreeEntry(S.OpValue)) 6464 if (E->isSame(VL)) { 6465 Value *V = vectorizeTree(E); 6466 if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) { 6467 if (!E->ReuseShuffleIndices.empty()) { 6468 // Reshuffle to get only unique values. 6469 // If some of the scalars are duplicated in the vectorization tree 6470 // entry, we do not vectorize them but instead generate a mask for 6471 // the reuses. But if there are several users of the same entry, 6472 // they may have different vectorization factors. This is especially 6473 // important for PHI nodes. In this case, we need to adapt the 6474 // resulting instruction for the user vectorization factor and have 6475 // to reshuffle it again to take only unique elements of the vector. 6476 // Without this code the function incorrectly returns reduced vector 6477 // instruction with the same elements, not with the unique ones. 6478 6479 // block: 6480 // %phi = phi <2 x > { .., %entry} {%shuffle, %block} 6481 // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0> 6482 // ... (use %2) 6483 // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0} 6484 // br %block 6485 SmallVector<int> UniqueIdxs(VF, UndefMaskElem); 6486 SmallSet<int, 4> UsedIdxs; 6487 int Pos = 0; 6488 int Sz = VL.size(); 6489 for (int Idx : E->ReuseShuffleIndices) { 6490 if (Idx != Sz && Idx != UndefMaskElem && 6491 UsedIdxs.insert(Idx).second) 6492 UniqueIdxs[Idx] = Pos; 6493 ++Pos; 6494 } 6495 assert(VF >= UsedIdxs.size() && "Expected vectorization factor " 6496 "less than original vector size."); 6497 UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem); 6498 V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle"); 6499 } else { 6500 assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() && 6501 "Expected vectorization factor less " 6502 "than original vector size."); 6503 SmallVector<int> UniformMask(VF, 0); 6504 std::iota(UniformMask.begin(), UniformMask.end(), 0); 6505 V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle"); 6506 } 6507 if (auto *I = dyn_cast<Instruction>(V)) { 6508 GatherShuffleSeq.insert(I); 6509 CSEBlocks.insert(I->getParent()); 6510 } 6511 } 6512 return V; 6513 } 6514 } 6515 6516 // Check that every instruction appears once in this bundle. 6517 SmallVector<int> ReuseShuffleIndicies; 6518 SmallVector<Value *> UniqueValues; 6519 if (VL.size() > 2) { 6520 DenseMap<Value *, unsigned> UniquePositions; 6521 unsigned NumValues = 6522 std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) { 6523 return !isa<UndefValue>(V); 6524 }).base()); 6525 VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues)); 6526 int UniqueVals = 0; 6527 for (Value *V : VL.drop_back(VL.size() - VF)) { 6528 if (isa<UndefValue>(V)) { 6529 ReuseShuffleIndicies.emplace_back(UndefMaskElem); 6530 continue; 6531 } 6532 if (isConstant(V)) { 6533 ReuseShuffleIndicies.emplace_back(UniqueValues.size()); 6534 UniqueValues.emplace_back(V); 6535 continue; 6536 } 6537 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 6538 ReuseShuffleIndicies.emplace_back(Res.first->second); 6539 if (Res.second) { 6540 UniqueValues.emplace_back(V); 6541 ++UniqueVals; 6542 } 6543 } 6544 if (UniqueVals == 1 && UniqueValues.size() == 1) { 6545 // Emit pure splat vector. 6546 ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(), 6547 UndefMaskElem); 6548 } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) { 6549 ReuseShuffleIndicies.clear(); 6550 UniqueValues.clear(); 6551 UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues)); 6552 } 6553 UniqueValues.append(VF - UniqueValues.size(), 6554 PoisonValue::get(VL[0]->getType())); 6555 VL = UniqueValues; 6556 } 6557 6558 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 6559 CSEBlocks); 6560 Value *Vec = gather(VL); 6561 if (!ReuseShuffleIndicies.empty()) { 6562 ShuffleBuilder.addMask(ReuseShuffleIndicies); 6563 Vec = ShuffleBuilder.finalize(Vec); 6564 } 6565 return Vec; 6566 } 6567 6568 Value *BoUpSLP::vectorizeTree(TreeEntry *E) { 6569 IRBuilder<>::InsertPointGuard Guard(Builder); 6570 6571 if (E->VectorizedValue) { 6572 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"); 6573 return E->VectorizedValue; 6574 } 6575 6576 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 6577 unsigned VF = E->getVectorFactor(); 6578 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 6579 CSEBlocks); 6580 if (E->State == TreeEntry::NeedToGather) { 6581 if (E->getMainOp()) 6582 setInsertPointAfterBundle(E); 6583 Value *Vec; 6584 SmallVector<int> Mask; 6585 SmallVector<const TreeEntry *> Entries; 6586 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 6587 isGatherShuffledEntry(E, Mask, Entries); 6588 if (Shuffle.hasValue()) { 6589 assert((Entries.size() == 1 || Entries.size() == 2) && 6590 "Expected shuffle of 1 or 2 entries."); 6591 Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue, 6592 Entries.back()->VectorizedValue, Mask); 6593 if (auto *I = dyn_cast<Instruction>(Vec)) { 6594 GatherShuffleSeq.insert(I); 6595 CSEBlocks.insert(I->getParent()); 6596 } 6597 } else { 6598 Vec = gather(E->Scalars); 6599 } 6600 if (NeedToShuffleReuses) { 6601 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6602 Vec = ShuffleBuilder.finalize(Vec); 6603 } 6604 E->VectorizedValue = Vec; 6605 return Vec; 6606 } 6607 6608 assert((E->State == TreeEntry::Vectorize || 6609 E->State == TreeEntry::ScatterVectorize) && 6610 "Unhandled state"); 6611 unsigned ShuffleOrOp = 6612 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 6613 Instruction *VL0 = E->getMainOp(); 6614 Type *ScalarTy = VL0->getType(); 6615 if (auto *Store = dyn_cast<StoreInst>(VL0)) 6616 ScalarTy = Store->getValueOperand()->getType(); 6617 else if (auto *IE = dyn_cast<InsertElementInst>(VL0)) 6618 ScalarTy = IE->getOperand(1)->getType(); 6619 auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size()); 6620 switch (ShuffleOrOp) { 6621 case Instruction::PHI: { 6622 assert( 6623 (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) && 6624 "PHI reordering is free."); 6625 auto *PH = cast<PHINode>(VL0); 6626 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI()); 6627 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 6628 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); 6629 Value *V = NewPhi; 6630 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6631 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6632 V = ShuffleBuilder.finalize(V); 6633 6634 E->VectorizedValue = V; 6635 6636 // PHINodes may have multiple entries from the same block. We want to 6637 // visit every block once. 6638 SmallPtrSet<BasicBlock*, 4> VisitedBBs; 6639 6640 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 6641 ValueList Operands; 6642 BasicBlock *IBB = PH->getIncomingBlock(i); 6643 6644 if (!VisitedBBs.insert(IBB).second) { 6645 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB); 6646 continue; 6647 } 6648 6649 Builder.SetInsertPoint(IBB->getTerminator()); 6650 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 6651 Value *Vec = vectorizeTree(E->getOperand(i)); 6652 NewPhi->addIncoming(Vec, IBB); 6653 } 6654 6655 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && 6656 "Invalid number of incoming values"); 6657 return V; 6658 } 6659 6660 case Instruction::ExtractElement: { 6661 Value *V = E->getSingleOperand(0); 6662 Builder.SetInsertPoint(VL0); 6663 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6664 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6665 V = ShuffleBuilder.finalize(V); 6666 E->VectorizedValue = V; 6667 return V; 6668 } 6669 case Instruction::ExtractValue: { 6670 auto *LI = cast<LoadInst>(E->getSingleOperand(0)); 6671 Builder.SetInsertPoint(LI); 6672 auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace()); 6673 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy); 6674 LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign()); 6675 Value *NewV = propagateMetadata(V, E->Scalars); 6676 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6677 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6678 NewV = ShuffleBuilder.finalize(NewV); 6679 E->VectorizedValue = NewV; 6680 return NewV; 6681 } 6682 case Instruction::InsertElement: { 6683 assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique"); 6684 Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back())); 6685 Value *V = vectorizeTree(E->getOperand(1)); 6686 6687 // Create InsertVector shuffle if necessary 6688 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 6689 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); 6690 })); 6691 const unsigned NumElts = 6692 cast<FixedVectorType>(FirstInsert->getType())->getNumElements(); 6693 const unsigned NumScalars = E->Scalars.size(); 6694 6695 unsigned Offset = *getInsertIndex(VL0, 0); 6696 assert(Offset < NumElts && "Failed to find vector index offset"); 6697 6698 // Create shuffle to resize vector 6699 SmallVector<int> Mask; 6700 if (!E->ReorderIndices.empty()) { 6701 inversePermutation(E->ReorderIndices, Mask); 6702 Mask.append(NumElts - NumScalars, UndefMaskElem); 6703 } else { 6704 Mask.assign(NumElts, UndefMaskElem); 6705 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 6706 } 6707 // Create InsertVector shuffle if necessary 6708 bool IsIdentity = true; 6709 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 6710 Mask.swap(PrevMask); 6711 for (unsigned I = 0; I < NumScalars; ++I) { 6712 Value *Scalar = E->Scalars[PrevMask[I]]; 6713 Optional<int> InsertIdx = getInsertIndex(Scalar, 0); 6714 if (!InsertIdx || *InsertIdx == UndefMaskElem) 6715 continue; 6716 IsIdentity &= *InsertIdx - Offset == I; 6717 Mask[*InsertIdx - Offset] = I; 6718 } 6719 if (!IsIdentity || NumElts != NumScalars) { 6720 V = Builder.CreateShuffleVector(V, Mask); 6721 if (auto *I = dyn_cast<Instruction>(V)) { 6722 GatherShuffleSeq.insert(I); 6723 CSEBlocks.insert(I->getParent()); 6724 } 6725 } 6726 6727 if ((!IsIdentity || Offset != 0 || 6728 !isUndefVector(FirstInsert->getOperand(0))) && 6729 NumElts != NumScalars) { 6730 SmallVector<int> InsertMask(NumElts); 6731 std::iota(InsertMask.begin(), InsertMask.end(), 0); 6732 for (unsigned I = 0; I < NumElts; I++) { 6733 if (Mask[I] != UndefMaskElem) 6734 InsertMask[Offset + I] = NumElts + I; 6735 } 6736 6737 V = Builder.CreateShuffleVector( 6738 FirstInsert->getOperand(0), V, InsertMask, 6739 cast<Instruction>(E->Scalars.back())->getName()); 6740 if (auto *I = dyn_cast<Instruction>(V)) { 6741 GatherShuffleSeq.insert(I); 6742 CSEBlocks.insert(I->getParent()); 6743 } 6744 } 6745 6746 ++NumVectorInstructions; 6747 E->VectorizedValue = V; 6748 return V; 6749 } 6750 case Instruction::ZExt: 6751 case Instruction::SExt: 6752 case Instruction::FPToUI: 6753 case Instruction::FPToSI: 6754 case Instruction::FPExt: 6755 case Instruction::PtrToInt: 6756 case Instruction::IntToPtr: 6757 case Instruction::SIToFP: 6758 case Instruction::UIToFP: 6759 case Instruction::Trunc: 6760 case Instruction::FPTrunc: 6761 case Instruction::BitCast: { 6762 setInsertPointAfterBundle(E); 6763 6764 Value *InVec = vectorizeTree(E->getOperand(0)); 6765 6766 if (E->VectorizedValue) { 6767 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6768 return E->VectorizedValue; 6769 } 6770 6771 auto *CI = cast<CastInst>(VL0); 6772 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); 6773 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6774 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6775 V = ShuffleBuilder.finalize(V); 6776 6777 E->VectorizedValue = V; 6778 ++NumVectorInstructions; 6779 return V; 6780 } 6781 case Instruction::FCmp: 6782 case Instruction::ICmp: { 6783 setInsertPointAfterBundle(E); 6784 6785 Value *L = vectorizeTree(E->getOperand(0)); 6786 Value *R = vectorizeTree(E->getOperand(1)); 6787 6788 if (E->VectorizedValue) { 6789 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6790 return E->VectorizedValue; 6791 } 6792 6793 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 6794 Value *V = Builder.CreateCmp(P0, L, R); 6795 propagateIRFlags(V, E->Scalars, VL0); 6796 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6797 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6798 V = ShuffleBuilder.finalize(V); 6799 6800 E->VectorizedValue = V; 6801 ++NumVectorInstructions; 6802 return V; 6803 } 6804 case Instruction::Select: { 6805 setInsertPointAfterBundle(E); 6806 6807 Value *Cond = vectorizeTree(E->getOperand(0)); 6808 Value *True = vectorizeTree(E->getOperand(1)); 6809 Value *False = vectorizeTree(E->getOperand(2)); 6810 6811 if (E->VectorizedValue) { 6812 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6813 return E->VectorizedValue; 6814 } 6815 6816 Value *V = Builder.CreateSelect(Cond, True, False); 6817 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6818 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6819 V = ShuffleBuilder.finalize(V); 6820 6821 E->VectorizedValue = V; 6822 ++NumVectorInstructions; 6823 return V; 6824 } 6825 case Instruction::FNeg: { 6826 setInsertPointAfterBundle(E); 6827 6828 Value *Op = vectorizeTree(E->getOperand(0)); 6829 6830 if (E->VectorizedValue) { 6831 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6832 return E->VectorizedValue; 6833 } 6834 6835 Value *V = Builder.CreateUnOp( 6836 static_cast<Instruction::UnaryOps>(E->getOpcode()), Op); 6837 propagateIRFlags(V, E->Scalars, VL0); 6838 if (auto *I = dyn_cast<Instruction>(V)) 6839 V = propagateMetadata(I, E->Scalars); 6840 6841 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6842 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6843 V = ShuffleBuilder.finalize(V); 6844 6845 E->VectorizedValue = V; 6846 ++NumVectorInstructions; 6847 6848 return V; 6849 } 6850 case Instruction::Add: 6851 case Instruction::FAdd: 6852 case Instruction::Sub: 6853 case Instruction::FSub: 6854 case Instruction::Mul: 6855 case Instruction::FMul: 6856 case Instruction::UDiv: 6857 case Instruction::SDiv: 6858 case Instruction::FDiv: 6859 case Instruction::URem: 6860 case Instruction::SRem: 6861 case Instruction::FRem: 6862 case Instruction::Shl: 6863 case Instruction::LShr: 6864 case Instruction::AShr: 6865 case Instruction::And: 6866 case Instruction::Or: 6867 case Instruction::Xor: { 6868 setInsertPointAfterBundle(E); 6869 6870 Value *LHS = vectorizeTree(E->getOperand(0)); 6871 Value *RHS = vectorizeTree(E->getOperand(1)); 6872 6873 if (E->VectorizedValue) { 6874 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6875 return E->VectorizedValue; 6876 } 6877 6878 Value *V = Builder.CreateBinOp( 6879 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, 6880 RHS); 6881 propagateIRFlags(V, E->Scalars, VL0); 6882 if (auto *I = dyn_cast<Instruction>(V)) 6883 V = propagateMetadata(I, E->Scalars); 6884 6885 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6886 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6887 V = ShuffleBuilder.finalize(V); 6888 6889 E->VectorizedValue = V; 6890 ++NumVectorInstructions; 6891 6892 return V; 6893 } 6894 case Instruction::Load: { 6895 // Loads are inserted at the head of the tree because we don't want to 6896 // sink them all the way down past store instructions. 6897 setInsertPointAfterBundle(E); 6898 6899 LoadInst *LI = cast<LoadInst>(VL0); 6900 Instruction *NewLI; 6901 unsigned AS = LI->getPointerAddressSpace(); 6902 Value *PO = LI->getPointerOperand(); 6903 if (E->State == TreeEntry::Vectorize) { 6904 6905 Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS)); 6906 6907 // The pointer operand uses an in-tree scalar so we add the new BitCast 6908 // to ExternalUses list to make sure that an extract will be generated 6909 // in the future. 6910 if (TreeEntry *Entry = getTreeEntry(PO)) { 6911 // Find which lane we need to extract. 6912 unsigned FoundLane = Entry->findLaneForValue(PO); 6913 ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane); 6914 } 6915 6916 NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign()); 6917 } else { 6918 assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state"); 6919 Value *VecPtr = vectorizeTree(E->getOperand(0)); 6920 // Use the minimum alignment of the gathered loads. 6921 Align CommonAlignment = LI->getAlign(); 6922 for (Value *V : E->Scalars) 6923 CommonAlignment = 6924 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 6925 NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment); 6926 } 6927 Value *V = propagateMetadata(NewLI, E->Scalars); 6928 6929 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6930 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6931 V = ShuffleBuilder.finalize(V); 6932 E->VectorizedValue = V; 6933 ++NumVectorInstructions; 6934 return V; 6935 } 6936 case Instruction::Store: { 6937 auto *SI = cast<StoreInst>(VL0); 6938 unsigned AS = SI->getPointerAddressSpace(); 6939 6940 setInsertPointAfterBundle(E); 6941 6942 Value *VecValue = vectorizeTree(E->getOperand(0)); 6943 ShuffleBuilder.addMask(E->ReorderIndices); 6944 VecValue = ShuffleBuilder.finalize(VecValue); 6945 6946 Value *ScalarPtr = SI->getPointerOperand(); 6947 Value *VecPtr = Builder.CreateBitCast( 6948 ScalarPtr, VecValue->getType()->getPointerTo(AS)); 6949 StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr, 6950 SI->getAlign()); 6951 6952 // The pointer operand uses an in-tree scalar, so add the new BitCast to 6953 // ExternalUses to make sure that an extract will be generated in the 6954 // future. 6955 if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) { 6956 // Find which lane we need to extract. 6957 unsigned FoundLane = Entry->findLaneForValue(ScalarPtr); 6958 ExternalUses.push_back( 6959 ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane)); 6960 } 6961 6962 Value *V = propagateMetadata(ST, E->Scalars); 6963 6964 E->VectorizedValue = V; 6965 ++NumVectorInstructions; 6966 return V; 6967 } 6968 case Instruction::GetElementPtr: { 6969 auto *GEP0 = cast<GetElementPtrInst>(VL0); 6970 setInsertPointAfterBundle(E); 6971 6972 Value *Op0 = vectorizeTree(E->getOperand(0)); 6973 6974 SmallVector<Value *> OpVecs; 6975 for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) { 6976 Value *OpVec = vectorizeTree(E->getOperand(J)); 6977 OpVecs.push_back(OpVec); 6978 } 6979 6980 Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs); 6981 if (Instruction *I = dyn_cast<Instruction>(V)) 6982 V = propagateMetadata(I, E->Scalars); 6983 6984 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6985 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6986 V = ShuffleBuilder.finalize(V); 6987 6988 E->VectorizedValue = V; 6989 ++NumVectorInstructions; 6990 6991 return V; 6992 } 6993 case Instruction::Call: { 6994 CallInst *CI = cast<CallInst>(VL0); 6995 setInsertPointAfterBundle(E); 6996 6997 Intrinsic::ID IID = Intrinsic::not_intrinsic; 6998 if (Function *FI = CI->getCalledFunction()) 6999 IID = FI->getIntrinsicID(); 7000 7001 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 7002 7003 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 7004 bool UseIntrinsic = ID != Intrinsic::not_intrinsic && 7005 VecCallCosts.first <= VecCallCosts.second; 7006 7007 Value *ScalarArg = nullptr; 7008 std::vector<Value *> OpVecs; 7009 SmallVector<Type *, 2> TysForDecl = 7010 {FixedVectorType::get(CI->getType(), E->Scalars.size())}; 7011 for (int j = 0, e = CI->arg_size(); j < e; ++j) { 7012 ValueList OpVL; 7013 // Some intrinsics have scalar arguments. This argument should not be 7014 // vectorized. 7015 if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) { 7016 CallInst *CEI = cast<CallInst>(VL0); 7017 ScalarArg = CEI->getArgOperand(j); 7018 OpVecs.push_back(CEI->getArgOperand(j)); 7019 if (hasVectorInstrinsicOverloadedScalarOpd(IID, j)) 7020 TysForDecl.push_back(ScalarArg->getType()); 7021 continue; 7022 } 7023 7024 Value *OpVec = vectorizeTree(E->getOperand(j)); 7025 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n"); 7026 OpVecs.push_back(OpVec); 7027 } 7028 7029 Function *CF; 7030 if (!UseIntrinsic) { 7031 VFShape Shape = 7032 VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 7033 VecTy->getNumElements())), 7034 false /*HasGlobalPred*/); 7035 CF = VFDatabase(*CI).getVectorizedFunction(Shape); 7036 } else { 7037 CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl); 7038 } 7039 7040 SmallVector<OperandBundleDef, 1> OpBundles; 7041 CI->getOperandBundlesAsDefs(OpBundles); 7042 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles); 7043 7044 // The scalar argument uses an in-tree scalar so we add the new vectorized 7045 // call to ExternalUses list to make sure that an extract will be 7046 // generated in the future. 7047 if (ScalarArg) { 7048 if (TreeEntry *Entry = getTreeEntry(ScalarArg)) { 7049 // Find which lane we need to extract. 7050 unsigned FoundLane = Entry->findLaneForValue(ScalarArg); 7051 ExternalUses.push_back( 7052 ExternalUser(ScalarArg, cast<User>(V), FoundLane)); 7053 } 7054 } 7055 7056 propagateIRFlags(V, E->Scalars, VL0); 7057 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7058 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7059 V = ShuffleBuilder.finalize(V); 7060 7061 E->VectorizedValue = V; 7062 ++NumVectorInstructions; 7063 return V; 7064 } 7065 case Instruction::ShuffleVector: { 7066 assert(E->isAltShuffle() && 7067 ((Instruction::isBinaryOp(E->getOpcode()) && 7068 Instruction::isBinaryOp(E->getAltOpcode())) || 7069 (Instruction::isCast(E->getOpcode()) && 7070 Instruction::isCast(E->getAltOpcode())) || 7071 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 7072 "Invalid Shuffle Vector Operand"); 7073 7074 Value *LHS = nullptr, *RHS = nullptr; 7075 if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) { 7076 setInsertPointAfterBundle(E); 7077 LHS = vectorizeTree(E->getOperand(0)); 7078 RHS = vectorizeTree(E->getOperand(1)); 7079 } else { 7080 setInsertPointAfterBundle(E); 7081 LHS = vectorizeTree(E->getOperand(0)); 7082 } 7083 7084 if (E->VectorizedValue) { 7085 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7086 return E->VectorizedValue; 7087 } 7088 7089 Value *V0, *V1; 7090 if (Instruction::isBinaryOp(E->getOpcode())) { 7091 V0 = Builder.CreateBinOp( 7092 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS); 7093 V1 = Builder.CreateBinOp( 7094 static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS); 7095 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 7096 V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS); 7097 auto *AltCI = cast<CmpInst>(E->getAltOp()); 7098 CmpInst::Predicate AltPred = AltCI->getPredicate(); 7099 unsigned AltIdx = 7100 std::distance(E->Scalars.begin(), find(E->Scalars, AltCI)); 7101 if (AltCI->getOperand(0) != E->getOperand(0)[AltIdx]) 7102 AltPred = CmpInst::getSwappedPredicate(AltPred); 7103 V1 = Builder.CreateCmp(AltPred, LHS, RHS); 7104 } else { 7105 V0 = Builder.CreateCast( 7106 static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy); 7107 V1 = Builder.CreateCast( 7108 static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy); 7109 } 7110 // Add V0 and V1 to later analysis to try to find and remove matching 7111 // instruction, if any. 7112 for (Value *V : {V0, V1}) { 7113 if (auto *I = dyn_cast<Instruction>(V)) { 7114 GatherShuffleSeq.insert(I); 7115 CSEBlocks.insert(I->getParent()); 7116 } 7117 } 7118 7119 // Create shuffle to take alternate operations from the vector. 7120 // Also, gather up main and alt scalar ops to propagate IR flags to 7121 // each vector operation. 7122 ValueList OpScalars, AltScalars; 7123 SmallVector<int> Mask; 7124 buildSuffleEntryMask( 7125 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 7126 [E](Instruction *I) { 7127 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 7128 if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) { 7129 auto *AltCI0 = cast<CmpInst>(E->getAltOp()); 7130 auto *CI = cast<CmpInst>(I); 7131 CmpInst::Predicate P0 = CI0->getPredicate(); 7132 CmpInst::Predicate AltP0 = AltCI0->getPredicate(); 7133 assert(P0 != AltP0 && 7134 "Expected different main/alternate predicates."); 7135 CmpInst::Predicate AltP0Swapped = 7136 CmpInst::getSwappedPredicate(AltP0); 7137 CmpInst::Predicate CurrentPred = CI->getPredicate(); 7138 if (P0 == AltP0Swapped) 7139 return (P0 == CurrentPred && 7140 !areCompatibleCmpOps( 7141 CI0->getOperand(0), CI0->getOperand(1), 7142 CI->getOperand(0), CI->getOperand(1))) || 7143 (AltP0 == CurrentPred && 7144 !areCompatibleCmpOps( 7145 CI0->getOperand(0), CI0->getOperand(1), 7146 CI->getOperand(1), CI->getOperand(0))); 7147 return AltP0 == CurrentPred || AltP0Swapped == CurrentPred; 7148 } 7149 return I->getOpcode() == E->getAltOpcode(); 7150 }, 7151 Mask, &OpScalars, &AltScalars); 7152 7153 propagateIRFlags(V0, OpScalars); 7154 propagateIRFlags(V1, AltScalars); 7155 7156 Value *V = Builder.CreateShuffleVector(V0, V1, Mask); 7157 if (auto *I = dyn_cast<Instruction>(V)) { 7158 V = propagateMetadata(I, E->Scalars); 7159 GatherShuffleSeq.insert(I); 7160 CSEBlocks.insert(I->getParent()); 7161 } 7162 V = ShuffleBuilder.finalize(V); 7163 7164 E->VectorizedValue = V; 7165 ++NumVectorInstructions; 7166 7167 return V; 7168 } 7169 default: 7170 llvm_unreachable("unknown inst"); 7171 } 7172 return nullptr; 7173 } 7174 7175 Value *BoUpSLP::vectorizeTree() { 7176 ExtraValueToDebugLocsMap ExternallyUsedValues; 7177 return vectorizeTree(ExternallyUsedValues); 7178 } 7179 7180 Value * 7181 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) { 7182 // All blocks must be scheduled before any instructions are inserted. 7183 for (auto &BSIter : BlocksSchedules) { 7184 scheduleBlock(BSIter.second.get()); 7185 } 7186 7187 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7188 auto *VectorRoot = vectorizeTree(VectorizableTree[0].get()); 7189 7190 // If the vectorized tree can be rewritten in a smaller type, we truncate the 7191 // vectorized root. InstCombine will then rewrite the entire expression. We 7192 // sign extend the extracted values below. 7193 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 7194 if (MinBWs.count(ScalarRoot)) { 7195 if (auto *I = dyn_cast<Instruction>(VectorRoot)) { 7196 // If current instr is a phi and not the last phi, insert it after the 7197 // last phi node. 7198 if (isa<PHINode>(I)) 7199 Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt()); 7200 else 7201 Builder.SetInsertPoint(&*++BasicBlock::iterator(I)); 7202 } 7203 auto BundleWidth = VectorizableTree[0]->Scalars.size(); 7204 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 7205 auto *VecTy = FixedVectorType::get(MinTy, BundleWidth); 7206 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy); 7207 VectorizableTree[0]->VectorizedValue = Trunc; 7208 } 7209 7210 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() 7211 << " values .\n"); 7212 7213 // Extract all of the elements with the external uses. 7214 for (const auto &ExternalUse : ExternalUses) { 7215 Value *Scalar = ExternalUse.Scalar; 7216 llvm::User *User = ExternalUse.User; 7217 7218 // Skip users that we already RAUW. This happens when one instruction 7219 // has multiple uses of the same value. 7220 if (User && !is_contained(Scalar->users(), User)) 7221 continue; 7222 TreeEntry *E = getTreeEntry(Scalar); 7223 assert(E && "Invalid scalar"); 7224 assert(E->State != TreeEntry::NeedToGather && 7225 "Extracting from a gather list"); 7226 7227 Value *Vec = E->VectorizedValue; 7228 assert(Vec && "Can't find vectorizable value"); 7229 7230 Value *Lane = Builder.getInt32(ExternalUse.Lane); 7231 auto ExtractAndExtendIfNeeded = [&](Value *Vec) { 7232 if (Scalar->getType() != Vec->getType()) { 7233 Value *Ex; 7234 // "Reuse" the existing extract to improve final codegen. 7235 if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) { 7236 Ex = Builder.CreateExtractElement(ES->getOperand(0), 7237 ES->getOperand(1)); 7238 } else { 7239 Ex = Builder.CreateExtractElement(Vec, Lane); 7240 } 7241 // If necessary, sign-extend or zero-extend ScalarRoot 7242 // to the larger type. 7243 if (!MinBWs.count(ScalarRoot)) 7244 return Ex; 7245 if (MinBWs[ScalarRoot].second) 7246 return Builder.CreateSExt(Ex, Scalar->getType()); 7247 return Builder.CreateZExt(Ex, Scalar->getType()); 7248 } 7249 assert(isa<FixedVectorType>(Scalar->getType()) && 7250 isa<InsertElementInst>(Scalar) && 7251 "In-tree scalar of vector type is not insertelement?"); 7252 return Vec; 7253 }; 7254 // If User == nullptr, the Scalar is used as extra arg. Generate 7255 // ExtractElement instruction and update the record for this scalar in 7256 // ExternallyUsedValues. 7257 if (!User) { 7258 assert(ExternallyUsedValues.count(Scalar) && 7259 "Scalar with nullptr as an external user must be registered in " 7260 "ExternallyUsedValues map"); 7261 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 7262 Builder.SetInsertPoint(VecI->getParent(), 7263 std::next(VecI->getIterator())); 7264 } else { 7265 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7266 } 7267 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7268 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent()); 7269 auto &NewInstLocs = ExternallyUsedValues[NewInst]; 7270 auto It = ExternallyUsedValues.find(Scalar); 7271 assert(It != ExternallyUsedValues.end() && 7272 "Externally used scalar is not found in ExternallyUsedValues"); 7273 NewInstLocs.append(It->second); 7274 ExternallyUsedValues.erase(Scalar); 7275 // Required to update internally referenced instructions. 7276 Scalar->replaceAllUsesWith(NewInst); 7277 continue; 7278 } 7279 7280 // Generate extracts for out-of-tree users. 7281 // Find the insertion point for the extractelement lane. 7282 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 7283 if (PHINode *PH = dyn_cast<PHINode>(User)) { 7284 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { 7285 if (PH->getIncomingValue(i) == Scalar) { 7286 Instruction *IncomingTerminator = 7287 PH->getIncomingBlock(i)->getTerminator(); 7288 if (isa<CatchSwitchInst>(IncomingTerminator)) { 7289 Builder.SetInsertPoint(VecI->getParent(), 7290 std::next(VecI->getIterator())); 7291 } else { 7292 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator()); 7293 } 7294 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7295 CSEBlocks.insert(PH->getIncomingBlock(i)); 7296 PH->setOperand(i, NewInst); 7297 } 7298 } 7299 } else { 7300 Builder.SetInsertPoint(cast<Instruction>(User)); 7301 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7302 CSEBlocks.insert(cast<Instruction>(User)->getParent()); 7303 User->replaceUsesOfWith(Scalar, NewInst); 7304 } 7305 } else { 7306 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7307 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7308 CSEBlocks.insert(&F->getEntryBlock()); 7309 User->replaceUsesOfWith(Scalar, NewInst); 7310 } 7311 7312 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n"); 7313 } 7314 7315 // For each vectorized value: 7316 for (auto &TEPtr : VectorizableTree) { 7317 TreeEntry *Entry = TEPtr.get(); 7318 7319 // No need to handle users of gathered values. 7320 if (Entry->State == TreeEntry::NeedToGather) 7321 continue; 7322 7323 assert(Entry->VectorizedValue && "Can't find vectorizable value"); 7324 7325 // For each lane: 7326 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 7327 Value *Scalar = Entry->Scalars[Lane]; 7328 7329 #ifndef NDEBUG 7330 Type *Ty = Scalar->getType(); 7331 if (!Ty->isVoidTy()) { 7332 for (User *U : Scalar->users()) { 7333 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n"); 7334 7335 // It is legal to delete users in the ignorelist. 7336 assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) || 7337 (isa_and_nonnull<Instruction>(U) && 7338 isDeleted(cast<Instruction>(U)))) && 7339 "Deleting out-of-tree value"); 7340 } 7341 } 7342 #endif 7343 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n"); 7344 eraseInstruction(cast<Instruction>(Scalar)); 7345 } 7346 } 7347 7348 Builder.ClearInsertionPoint(); 7349 InstrElementSize.clear(); 7350 7351 return VectorizableTree[0]->VectorizedValue; 7352 } 7353 7354 void BoUpSLP::optimizeGatherSequence() { 7355 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size() 7356 << " gather sequences instructions.\n"); 7357 // LICM InsertElementInst sequences. 7358 for (Instruction *I : GatherShuffleSeq) { 7359 if (isDeleted(I)) 7360 continue; 7361 7362 // Check if this block is inside a loop. 7363 Loop *L = LI->getLoopFor(I->getParent()); 7364 if (!L) 7365 continue; 7366 7367 // Check if it has a preheader. 7368 BasicBlock *PreHeader = L->getLoopPreheader(); 7369 if (!PreHeader) 7370 continue; 7371 7372 // If the vector or the element that we insert into it are 7373 // instructions that are defined in this basic block then we can't 7374 // hoist this instruction. 7375 if (any_of(I->operands(), [L](Value *V) { 7376 auto *OpI = dyn_cast<Instruction>(V); 7377 return OpI && L->contains(OpI); 7378 })) 7379 continue; 7380 7381 // We can hoist this instruction. Move it to the pre-header. 7382 I->moveBefore(PreHeader->getTerminator()); 7383 } 7384 7385 // Make a list of all reachable blocks in our CSE queue. 7386 SmallVector<const DomTreeNode *, 8> CSEWorkList; 7387 CSEWorkList.reserve(CSEBlocks.size()); 7388 for (BasicBlock *BB : CSEBlocks) 7389 if (DomTreeNode *N = DT->getNode(BB)) { 7390 assert(DT->isReachableFromEntry(N)); 7391 CSEWorkList.push_back(N); 7392 } 7393 7394 // Sort blocks by domination. This ensures we visit a block after all blocks 7395 // dominating it are visited. 7396 llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) { 7397 assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && 7398 "Different nodes should have different DFS numbers"); 7399 return A->getDFSNumIn() < B->getDFSNumIn(); 7400 }); 7401 7402 // Less defined shuffles can be replaced by the more defined copies. 7403 // Between two shuffles one is less defined if it has the same vector operands 7404 // and its mask indeces are the same as in the first one or undefs. E.g. 7405 // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0, 7406 // poison, <0, 0, 0, 0>. 7407 auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2, 7408 SmallVectorImpl<int> &NewMask) { 7409 if (I1->getType() != I2->getType()) 7410 return false; 7411 auto *SI1 = dyn_cast<ShuffleVectorInst>(I1); 7412 auto *SI2 = dyn_cast<ShuffleVectorInst>(I2); 7413 if (!SI1 || !SI2) 7414 return I1->isIdenticalTo(I2); 7415 if (SI1->isIdenticalTo(SI2)) 7416 return true; 7417 for (int I = 0, E = SI1->getNumOperands(); I < E; ++I) 7418 if (SI1->getOperand(I) != SI2->getOperand(I)) 7419 return false; 7420 // Check if the second instruction is more defined than the first one. 7421 NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end()); 7422 ArrayRef<int> SM1 = SI1->getShuffleMask(); 7423 // Count trailing undefs in the mask to check the final number of used 7424 // registers. 7425 unsigned LastUndefsCnt = 0; 7426 for (int I = 0, E = NewMask.size(); I < E; ++I) { 7427 if (SM1[I] == UndefMaskElem) 7428 ++LastUndefsCnt; 7429 else 7430 LastUndefsCnt = 0; 7431 if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem && 7432 NewMask[I] != SM1[I]) 7433 return false; 7434 if (NewMask[I] == UndefMaskElem) 7435 NewMask[I] = SM1[I]; 7436 } 7437 // Check if the last undefs actually change the final number of used vector 7438 // registers. 7439 return SM1.size() - LastUndefsCnt > 1 && 7440 TTI->getNumberOfParts(SI1->getType()) == 7441 TTI->getNumberOfParts( 7442 FixedVectorType::get(SI1->getType()->getElementType(), 7443 SM1.size() - LastUndefsCnt)); 7444 }; 7445 // Perform O(N^2) search over the gather/shuffle sequences and merge identical 7446 // instructions. TODO: We can further optimize this scan if we split the 7447 // instructions into different buckets based on the insert lane. 7448 SmallVector<Instruction *, 16> Visited; 7449 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) { 7450 assert(*I && 7451 (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && 7452 "Worklist not sorted properly!"); 7453 BasicBlock *BB = (*I)->getBlock(); 7454 // For all instructions in blocks containing gather sequences: 7455 for (Instruction &In : llvm::make_early_inc_range(*BB)) { 7456 if (isDeleted(&In)) 7457 continue; 7458 if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) && 7459 !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In)) 7460 continue; 7461 7462 // Check if we can replace this instruction with any of the 7463 // visited instructions. 7464 bool Replaced = false; 7465 for (Instruction *&V : Visited) { 7466 SmallVector<int> NewMask; 7467 if (IsIdenticalOrLessDefined(&In, V, NewMask) && 7468 DT->dominates(V->getParent(), In.getParent())) { 7469 In.replaceAllUsesWith(V); 7470 eraseInstruction(&In); 7471 if (auto *SI = dyn_cast<ShuffleVectorInst>(V)) 7472 if (!NewMask.empty()) 7473 SI->setShuffleMask(NewMask); 7474 Replaced = true; 7475 break; 7476 } 7477 if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) && 7478 GatherShuffleSeq.contains(V) && 7479 IsIdenticalOrLessDefined(V, &In, NewMask) && 7480 DT->dominates(In.getParent(), V->getParent())) { 7481 In.moveAfter(V); 7482 V->replaceAllUsesWith(&In); 7483 eraseInstruction(V); 7484 if (auto *SI = dyn_cast<ShuffleVectorInst>(&In)) 7485 if (!NewMask.empty()) 7486 SI->setShuffleMask(NewMask); 7487 V = &In; 7488 Replaced = true; 7489 break; 7490 } 7491 } 7492 if (!Replaced) { 7493 assert(!is_contained(Visited, &In)); 7494 Visited.push_back(&In); 7495 } 7496 } 7497 } 7498 CSEBlocks.clear(); 7499 GatherShuffleSeq.clear(); 7500 } 7501 7502 BoUpSLP::ScheduleData * 7503 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) { 7504 ScheduleData *Bundle = nullptr; 7505 ScheduleData *PrevInBundle = nullptr; 7506 for (Value *V : VL) { 7507 ScheduleData *BundleMember = getScheduleData(V); 7508 assert(BundleMember && 7509 "no ScheduleData for bundle member " 7510 "(maybe not in same basic block)"); 7511 assert(BundleMember->isSchedulingEntity() && 7512 "bundle member already part of other bundle"); 7513 if (PrevInBundle) { 7514 PrevInBundle->NextInBundle = BundleMember; 7515 } else { 7516 Bundle = BundleMember; 7517 } 7518 7519 // Group the instructions to a bundle. 7520 BundleMember->FirstInBundle = Bundle; 7521 PrevInBundle = BundleMember; 7522 } 7523 assert(Bundle && "Failed to find schedule bundle"); 7524 return Bundle; 7525 } 7526 7527 // Groups the instructions to a bundle (which is then a single scheduling entity) 7528 // and schedules instructions until the bundle gets ready. 7529 Optional<BoUpSLP::ScheduleData *> 7530 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 7531 const InstructionsState &S) { 7532 // No need to schedule PHIs, insertelement, extractelement and extractvalue 7533 // instructions. 7534 if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue)) 7535 return nullptr; 7536 7537 // Initialize the instruction bundle. 7538 Instruction *OldScheduleEnd = ScheduleEnd; 7539 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n"); 7540 7541 auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule, 7542 ScheduleData *Bundle) { 7543 // The scheduling region got new instructions at the lower end (or it is a 7544 // new region for the first bundle). This makes it necessary to 7545 // recalculate all dependencies. 7546 // It is seldom that this needs to be done a second time after adding the 7547 // initial bundle to the region. 7548 if (ScheduleEnd != OldScheduleEnd) { 7549 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) 7550 doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); }); 7551 ReSchedule = true; 7552 } 7553 if (Bundle) { 7554 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle 7555 << " in block " << BB->getName() << "\n"); 7556 calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP); 7557 } 7558 7559 if (ReSchedule) { 7560 resetSchedule(); 7561 initialFillReadyList(ReadyInsts); 7562 } 7563 7564 // Now try to schedule the new bundle or (if no bundle) just calculate 7565 // dependencies. As soon as the bundle is "ready" it means that there are no 7566 // cyclic dependencies and we can schedule it. Note that's important that we 7567 // don't "schedule" the bundle yet (see cancelScheduling). 7568 while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) && 7569 !ReadyInsts.empty()) { 7570 ScheduleData *Picked = ReadyInsts.pop_back_val(); 7571 assert(Picked->isSchedulingEntity() && Picked->isReady() && 7572 "must be ready to schedule"); 7573 schedule(Picked, ReadyInsts); 7574 } 7575 }; 7576 7577 // Make sure that the scheduling region contains all 7578 // instructions of the bundle. 7579 for (Value *V : VL) { 7580 if (!extendSchedulingRegion(V, S)) { 7581 // If the scheduling region got new instructions at the lower end (or it 7582 // is a new region for the first bundle). This makes it necessary to 7583 // recalculate all dependencies. 7584 // Otherwise the compiler may crash trying to incorrectly calculate 7585 // dependencies and emit instruction in the wrong order at the actual 7586 // scheduling. 7587 TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr); 7588 return None; 7589 } 7590 } 7591 7592 bool ReSchedule = false; 7593 for (Value *V : VL) { 7594 ScheduleData *BundleMember = getScheduleData(V); 7595 assert(BundleMember && 7596 "no ScheduleData for bundle member (maybe not in same basic block)"); 7597 7598 // Make sure we don't leave the pieces of the bundle in the ready list when 7599 // whole bundle might not be ready. 7600 ReadyInsts.remove(BundleMember); 7601 7602 if (!BundleMember->IsScheduled) 7603 continue; 7604 // A bundle member was scheduled as single instruction before and now 7605 // needs to be scheduled as part of the bundle. We just get rid of the 7606 // existing schedule. 7607 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember 7608 << " was already scheduled\n"); 7609 ReSchedule = true; 7610 } 7611 7612 auto *Bundle = buildBundle(VL); 7613 TryScheduleBundleImpl(ReSchedule, Bundle); 7614 if (!Bundle->isReady()) { 7615 cancelScheduling(VL, S.OpValue); 7616 return None; 7617 } 7618 return Bundle; 7619 } 7620 7621 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL, 7622 Value *OpValue) { 7623 if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue)) 7624 return; 7625 7626 ScheduleData *Bundle = getScheduleData(OpValue); 7627 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n"); 7628 assert(!Bundle->IsScheduled && 7629 "Can't cancel bundle which is already scheduled"); 7630 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() && 7631 "tried to unbundle something which is not a bundle"); 7632 7633 // Remove the bundle from the ready list. 7634 if (Bundle->isReady()) 7635 ReadyInsts.remove(Bundle); 7636 7637 // Un-bundle: make single instructions out of the bundle. 7638 ScheduleData *BundleMember = Bundle; 7639 while (BundleMember) { 7640 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links"); 7641 BundleMember->FirstInBundle = BundleMember; 7642 ScheduleData *Next = BundleMember->NextInBundle; 7643 BundleMember->NextInBundle = nullptr; 7644 if (BundleMember->unscheduledDepsInBundle() == 0) { 7645 ReadyInsts.insert(BundleMember); 7646 } 7647 BundleMember = Next; 7648 } 7649 } 7650 7651 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() { 7652 // Allocate a new ScheduleData for the instruction. 7653 if (ChunkPos >= ChunkSize) { 7654 ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize)); 7655 ChunkPos = 0; 7656 } 7657 return &(ScheduleDataChunks.back()[ChunkPos++]); 7658 } 7659 7660 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V, 7661 const InstructionsState &S) { 7662 if (getScheduleData(V, isOneOf(S, V))) 7663 return true; 7664 Instruction *I = dyn_cast<Instruction>(V); 7665 assert(I && "bundle member must be an instruction"); 7666 assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && 7667 "phi nodes/insertelements/extractelements/extractvalues don't need to " 7668 "be scheduled"); 7669 auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool { 7670 ScheduleData *ISD = getScheduleData(I); 7671 if (!ISD) 7672 return false; 7673 assert(isInSchedulingRegion(ISD) && 7674 "ScheduleData not in scheduling region"); 7675 ScheduleData *SD = allocateScheduleDataChunks(); 7676 SD->Inst = I; 7677 SD->init(SchedulingRegionID, S.OpValue); 7678 ExtraScheduleDataMap[I][S.OpValue] = SD; 7679 return true; 7680 }; 7681 if (CheckSheduleForI(I)) 7682 return true; 7683 if (!ScheduleStart) { 7684 // It's the first instruction in the new region. 7685 initScheduleData(I, I->getNextNode(), nullptr, nullptr); 7686 ScheduleStart = I; 7687 ScheduleEnd = I->getNextNode(); 7688 if (isOneOf(S, I) != I) 7689 CheckSheduleForI(I); 7690 assert(ScheduleEnd && "tried to vectorize a terminator?"); 7691 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n"); 7692 return true; 7693 } 7694 // Search up and down at the same time, because we don't know if the new 7695 // instruction is above or below the existing scheduling region. 7696 BasicBlock::reverse_iterator UpIter = 7697 ++ScheduleStart->getIterator().getReverse(); 7698 BasicBlock::reverse_iterator UpperEnd = BB->rend(); 7699 BasicBlock::iterator DownIter = ScheduleEnd->getIterator(); 7700 BasicBlock::iterator LowerEnd = BB->end(); 7701 while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I && 7702 &*DownIter != I) { 7703 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) { 7704 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n"); 7705 return false; 7706 } 7707 7708 ++UpIter; 7709 ++DownIter; 7710 } 7711 if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) { 7712 assert(I->getParent() == ScheduleStart->getParent() && 7713 "Instruction is in wrong basic block."); 7714 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion); 7715 ScheduleStart = I; 7716 if (isOneOf(S, I) != I) 7717 CheckSheduleForI(I); 7718 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I 7719 << "\n"); 7720 return true; 7721 } 7722 assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && 7723 "Expected to reach top of the basic block or instruction down the " 7724 "lower end."); 7725 assert(I->getParent() == ScheduleEnd->getParent() && 7726 "Instruction is in wrong basic block."); 7727 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion, 7728 nullptr); 7729 ScheduleEnd = I->getNextNode(); 7730 if (isOneOf(S, I) != I) 7731 CheckSheduleForI(I); 7732 assert(ScheduleEnd && "tried to vectorize a terminator?"); 7733 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n"); 7734 return true; 7735 } 7736 7737 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI, 7738 Instruction *ToI, 7739 ScheduleData *PrevLoadStore, 7740 ScheduleData *NextLoadStore) { 7741 ScheduleData *CurrentLoadStore = PrevLoadStore; 7742 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) { 7743 ScheduleData *SD = ScheduleDataMap[I]; 7744 if (!SD) { 7745 SD = allocateScheduleDataChunks(); 7746 ScheduleDataMap[I] = SD; 7747 SD->Inst = I; 7748 } 7749 assert(!isInSchedulingRegion(SD) && 7750 "new ScheduleData already in scheduling region"); 7751 SD->init(SchedulingRegionID, I); 7752 7753 if (I->mayReadOrWriteMemory() && 7754 (!isa<IntrinsicInst>(I) || 7755 (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect && 7756 cast<IntrinsicInst>(I)->getIntrinsicID() != 7757 Intrinsic::pseudoprobe))) { 7758 // Update the linked list of memory accessing instructions. 7759 if (CurrentLoadStore) { 7760 CurrentLoadStore->NextLoadStore = SD; 7761 } else { 7762 FirstLoadStoreInRegion = SD; 7763 } 7764 CurrentLoadStore = SD; 7765 } 7766 } 7767 if (NextLoadStore) { 7768 if (CurrentLoadStore) 7769 CurrentLoadStore->NextLoadStore = NextLoadStore; 7770 } else { 7771 LastLoadStoreInRegion = CurrentLoadStore; 7772 } 7773 } 7774 7775 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD, 7776 bool InsertInReadyList, 7777 BoUpSLP *SLP) { 7778 assert(SD->isSchedulingEntity()); 7779 7780 SmallVector<ScheduleData *, 10> WorkList; 7781 WorkList.push_back(SD); 7782 7783 while (!WorkList.empty()) { 7784 ScheduleData *SD = WorkList.pop_back_val(); 7785 for (ScheduleData *BundleMember = SD; BundleMember; 7786 BundleMember = BundleMember->NextInBundle) { 7787 assert(isInSchedulingRegion(BundleMember)); 7788 if (BundleMember->hasValidDependencies()) 7789 continue; 7790 7791 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember 7792 << "\n"); 7793 BundleMember->Dependencies = 0; 7794 BundleMember->resetUnscheduledDeps(); 7795 7796 // Handle def-use chain dependencies. 7797 if (BundleMember->OpValue != BundleMember->Inst) { 7798 ScheduleData *UseSD = getScheduleData(BundleMember->Inst); 7799 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) { 7800 BundleMember->Dependencies++; 7801 ScheduleData *DestBundle = UseSD->FirstInBundle; 7802 if (!DestBundle->IsScheduled) 7803 BundleMember->incrementUnscheduledDeps(1); 7804 if (!DestBundle->hasValidDependencies()) 7805 WorkList.push_back(DestBundle); 7806 } 7807 } else { 7808 for (User *U : BundleMember->Inst->users()) { 7809 assert(isa<Instruction>(U) && 7810 "user of instruction must be instruction"); 7811 ScheduleData *UseSD = getScheduleData(U); 7812 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) { 7813 BundleMember->Dependencies++; 7814 ScheduleData *DestBundle = UseSD->FirstInBundle; 7815 if (!DestBundle->IsScheduled) 7816 BundleMember->incrementUnscheduledDeps(1); 7817 if (!DestBundle->hasValidDependencies()) 7818 WorkList.push_back(DestBundle); 7819 } 7820 } 7821 } 7822 7823 // Handle the memory dependencies (if any). 7824 ScheduleData *DepDest = BundleMember->NextLoadStore; 7825 if (!DepDest) 7826 continue; 7827 Instruction *SrcInst = BundleMember->Inst; 7828 assert(SrcInst->mayReadOrWriteMemory() && 7829 "NextLoadStore list for non memory effecting bundle?"); 7830 MemoryLocation SrcLoc = getLocation(SrcInst); 7831 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory(); 7832 unsigned numAliased = 0; 7833 unsigned DistToSrc = 1; 7834 7835 for ( ; DepDest; DepDest = DepDest->NextLoadStore) { 7836 assert(isInSchedulingRegion(DepDest)); 7837 7838 // We have two limits to reduce the complexity: 7839 // 1) AliasedCheckLimit: It's a small limit to reduce calls to 7840 // SLP->isAliased (which is the expensive part in this loop). 7841 // 2) MaxMemDepDistance: It's for very large blocks and it aborts 7842 // the whole loop (even if the loop is fast, it's quadratic). 7843 // It's important for the loop break condition (see below) to 7844 // check this limit even between two read-only instructions. 7845 if (DistToSrc >= MaxMemDepDistance || 7846 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) && 7847 (numAliased >= AliasedCheckLimit || 7848 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) { 7849 7850 // We increment the counter only if the locations are aliased 7851 // (instead of counting all alias checks). This gives a better 7852 // balance between reduced runtime and accurate dependencies. 7853 numAliased++; 7854 7855 DepDest->MemoryDependencies.push_back(BundleMember); 7856 BundleMember->Dependencies++; 7857 ScheduleData *DestBundle = DepDest->FirstInBundle; 7858 if (!DestBundle->IsScheduled) { 7859 BundleMember->incrementUnscheduledDeps(1); 7860 } 7861 if (!DestBundle->hasValidDependencies()) { 7862 WorkList.push_back(DestBundle); 7863 } 7864 } 7865 7866 // Example, explaining the loop break condition: Let's assume our 7867 // starting instruction is i0 and MaxMemDepDistance = 3. 7868 // 7869 // +--------v--v--v 7870 // i0,i1,i2,i3,i4,i5,i6,i7,i8 7871 // +--------^--^--^ 7872 // 7873 // MaxMemDepDistance let us stop alias-checking at i3 and we add 7874 // dependencies from i0 to i3,i4,.. (even if they are not aliased). 7875 // Previously we already added dependencies from i3 to i6,i7,i8 7876 // (because of MaxMemDepDistance). As we added a dependency from 7877 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8 7878 // and we can abort this loop at i6. 7879 if (DistToSrc >= 2 * MaxMemDepDistance) 7880 break; 7881 DistToSrc++; 7882 } 7883 } 7884 if (InsertInReadyList && SD->isReady()) { 7885 ReadyInsts.insert(SD); 7886 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst 7887 << "\n"); 7888 } 7889 } 7890 } 7891 7892 void BoUpSLP::BlockScheduling::resetSchedule() { 7893 assert(ScheduleStart && 7894 "tried to reset schedule on block which has not been scheduled"); 7895 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 7896 doForAllOpcodes(I, [&](ScheduleData *SD) { 7897 assert(isInSchedulingRegion(SD) && 7898 "ScheduleData not in scheduling region"); 7899 SD->IsScheduled = false; 7900 SD->resetUnscheduledDeps(); 7901 }); 7902 } 7903 ReadyInsts.clear(); 7904 } 7905 7906 void BoUpSLP::scheduleBlock(BlockScheduling *BS) { 7907 if (!BS->ScheduleStart) 7908 return; 7909 7910 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n"); 7911 7912 BS->resetSchedule(); 7913 7914 // For the real scheduling we use a more sophisticated ready-list: it is 7915 // sorted by the original instruction location. This lets the final schedule 7916 // be as close as possible to the original instruction order. 7917 struct ScheduleDataCompare { 7918 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const { 7919 return SD2->SchedulingPriority < SD1->SchedulingPriority; 7920 } 7921 }; 7922 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts; 7923 7924 // Ensure that all dependency data is updated and fill the ready-list with 7925 // initial instructions. 7926 int Idx = 0; 7927 int NumToSchedule = 0; 7928 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; 7929 I = I->getNextNode()) { 7930 BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) { 7931 assert((isVectorLikeInstWithConstOps(SD->Inst) || 7932 SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) && 7933 "scheduler and vectorizer bundle mismatch"); 7934 SD->FirstInBundle->SchedulingPriority = Idx++; 7935 if (SD->isSchedulingEntity()) { 7936 BS->calculateDependencies(SD, false, this); 7937 NumToSchedule++; 7938 } 7939 }); 7940 } 7941 BS->initialFillReadyList(ReadyInsts); 7942 7943 Instruction *LastScheduledInst = BS->ScheduleEnd; 7944 7945 // Do the "real" scheduling. 7946 while (!ReadyInsts.empty()) { 7947 ScheduleData *picked = *ReadyInsts.begin(); 7948 ReadyInsts.erase(ReadyInsts.begin()); 7949 7950 // Move the scheduled instruction(s) to their dedicated places, if not 7951 // there yet. 7952 for (ScheduleData *BundleMember = picked; BundleMember; 7953 BundleMember = BundleMember->NextInBundle) { 7954 Instruction *pickedInst = BundleMember->Inst; 7955 if (pickedInst->getNextNode() != LastScheduledInst) 7956 pickedInst->moveBefore(LastScheduledInst); 7957 LastScheduledInst = pickedInst; 7958 } 7959 7960 BS->schedule(picked, ReadyInsts); 7961 NumToSchedule--; 7962 } 7963 assert(NumToSchedule == 0 && "could not schedule all instructions"); 7964 7965 // Check that we didn't break any of our invariants. 7966 #ifdef EXPENSIVE_CHECKS 7967 BS->verify(); 7968 #endif 7969 7970 // Avoid duplicate scheduling of the block. 7971 BS->ScheduleStart = nullptr; 7972 } 7973 7974 unsigned BoUpSLP::getVectorElementSize(Value *V) { 7975 // If V is a store, just return the width of the stored value (or value 7976 // truncated just before storing) without traversing the expression tree. 7977 // This is the common case. 7978 if (auto *Store = dyn_cast<StoreInst>(V)) { 7979 if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand())) 7980 return DL->getTypeSizeInBits(Trunc->getSrcTy()); 7981 return DL->getTypeSizeInBits(Store->getValueOperand()->getType()); 7982 } 7983 7984 if (auto *IEI = dyn_cast<InsertElementInst>(V)) 7985 return getVectorElementSize(IEI->getOperand(1)); 7986 7987 auto E = InstrElementSize.find(V); 7988 if (E != InstrElementSize.end()) 7989 return E->second; 7990 7991 // If V is not a store, we can traverse the expression tree to find loads 7992 // that feed it. The type of the loaded value may indicate a more suitable 7993 // width than V's type. We want to base the vector element size on the width 7994 // of memory operations where possible. 7995 SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist; 7996 SmallPtrSet<Instruction *, 16> Visited; 7997 if (auto *I = dyn_cast<Instruction>(V)) { 7998 Worklist.emplace_back(I, I->getParent()); 7999 Visited.insert(I); 8000 } 8001 8002 // Traverse the expression tree in bottom-up order looking for loads. If we 8003 // encounter an instruction we don't yet handle, we give up. 8004 auto Width = 0u; 8005 while (!Worklist.empty()) { 8006 Instruction *I; 8007 BasicBlock *Parent; 8008 std::tie(I, Parent) = Worklist.pop_back_val(); 8009 8010 // We should only be looking at scalar instructions here. If the current 8011 // instruction has a vector type, skip. 8012 auto *Ty = I->getType(); 8013 if (isa<VectorType>(Ty)) 8014 continue; 8015 8016 // If the current instruction is a load, update MaxWidth to reflect the 8017 // width of the loaded value. 8018 if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) || 8019 isa<ExtractValueInst>(I)) 8020 Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty)); 8021 8022 // Otherwise, we need to visit the operands of the instruction. We only 8023 // handle the interesting cases from buildTree here. If an operand is an 8024 // instruction we haven't yet visited and from the same basic block as the 8025 // user or the use is a PHI node, we add it to the worklist. 8026 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8027 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) || 8028 isa<UnaryOperator>(I)) { 8029 for (Use &U : I->operands()) 8030 if (auto *J = dyn_cast<Instruction>(U.get())) 8031 if (Visited.insert(J).second && 8032 (isa<PHINode>(I) || J->getParent() == Parent)) 8033 Worklist.emplace_back(J, J->getParent()); 8034 } else { 8035 break; 8036 } 8037 } 8038 8039 // If we didn't encounter a memory access in the expression tree, or if we 8040 // gave up for some reason, just return the width of V. Otherwise, return the 8041 // maximum width we found. 8042 if (!Width) { 8043 if (auto *CI = dyn_cast<CmpInst>(V)) 8044 V = CI->getOperand(0); 8045 Width = DL->getTypeSizeInBits(V->getType()); 8046 } 8047 8048 for (Instruction *I : Visited) 8049 InstrElementSize[I] = Width; 8050 8051 return Width; 8052 } 8053 8054 // Determine if a value V in a vectorizable expression Expr can be demoted to a 8055 // smaller type with a truncation. We collect the values that will be demoted 8056 // in ToDemote and additional roots that require investigating in Roots. 8057 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr, 8058 SmallVectorImpl<Value *> &ToDemote, 8059 SmallVectorImpl<Value *> &Roots) { 8060 // We can always demote constants. 8061 if (isa<Constant>(V)) { 8062 ToDemote.push_back(V); 8063 return true; 8064 } 8065 8066 // If the value is not an instruction in the expression with only one use, it 8067 // cannot be demoted. 8068 auto *I = dyn_cast<Instruction>(V); 8069 if (!I || !I->hasOneUse() || !Expr.count(I)) 8070 return false; 8071 8072 switch (I->getOpcode()) { 8073 8074 // We can always demote truncations and extensions. Since truncations can 8075 // seed additional demotion, we save the truncated value. 8076 case Instruction::Trunc: 8077 Roots.push_back(I->getOperand(0)); 8078 break; 8079 case Instruction::ZExt: 8080 case Instruction::SExt: 8081 if (isa<ExtractElementInst>(I->getOperand(0)) || 8082 isa<InsertElementInst>(I->getOperand(0))) 8083 return false; 8084 break; 8085 8086 // We can demote certain binary operations if we can demote both of their 8087 // operands. 8088 case Instruction::Add: 8089 case Instruction::Sub: 8090 case Instruction::Mul: 8091 case Instruction::And: 8092 case Instruction::Or: 8093 case Instruction::Xor: 8094 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) || 8095 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots)) 8096 return false; 8097 break; 8098 8099 // We can demote selects if we can demote their true and false values. 8100 case Instruction::Select: { 8101 SelectInst *SI = cast<SelectInst>(I); 8102 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) || 8103 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots)) 8104 return false; 8105 break; 8106 } 8107 8108 // We can demote phis if we can demote all their incoming operands. Note that 8109 // we don't need to worry about cycles since we ensure single use above. 8110 case Instruction::PHI: { 8111 PHINode *PN = cast<PHINode>(I); 8112 for (Value *IncValue : PN->incoming_values()) 8113 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots)) 8114 return false; 8115 break; 8116 } 8117 8118 // Otherwise, conservatively give up. 8119 default: 8120 return false; 8121 } 8122 8123 // Record the value that we can demote. 8124 ToDemote.push_back(V); 8125 return true; 8126 } 8127 8128 void BoUpSLP::computeMinimumValueSizes() { 8129 // If there are no external uses, the expression tree must be rooted by a 8130 // store. We can't demote in-memory values, so there is nothing to do here. 8131 if (ExternalUses.empty()) 8132 return; 8133 8134 // We only attempt to truncate integer expressions. 8135 auto &TreeRoot = VectorizableTree[0]->Scalars; 8136 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType()); 8137 if (!TreeRootIT) 8138 return; 8139 8140 // If the expression is not rooted by a store, these roots should have 8141 // external uses. We will rely on InstCombine to rewrite the expression in 8142 // the narrower type. However, InstCombine only rewrites single-use values. 8143 // This means that if a tree entry other than a root is used externally, it 8144 // must have multiple uses and InstCombine will not rewrite it. The code 8145 // below ensures that only the roots are used externally. 8146 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end()); 8147 for (auto &EU : ExternalUses) 8148 if (!Expr.erase(EU.Scalar)) 8149 return; 8150 if (!Expr.empty()) 8151 return; 8152 8153 // Collect the scalar values of the vectorizable expression. We will use this 8154 // context to determine which values can be demoted. If we see a truncation, 8155 // we mark it as seeding another demotion. 8156 for (auto &EntryPtr : VectorizableTree) 8157 Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end()); 8158 8159 // Ensure the roots of the vectorizable tree don't form a cycle. They must 8160 // have a single external user that is not in the vectorizable tree. 8161 for (auto *Root : TreeRoot) 8162 if (!Root->hasOneUse() || Expr.count(*Root->user_begin())) 8163 return; 8164 8165 // Conservatively determine if we can actually truncate the roots of the 8166 // expression. Collect the values that can be demoted in ToDemote and 8167 // additional roots that require investigating in Roots. 8168 SmallVector<Value *, 32> ToDemote; 8169 SmallVector<Value *, 4> Roots; 8170 for (auto *Root : TreeRoot) 8171 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots)) 8172 return; 8173 8174 // The maximum bit width required to represent all the values that can be 8175 // demoted without loss of precision. It would be safe to truncate the roots 8176 // of the expression to this width. 8177 auto MaxBitWidth = 8u; 8178 8179 // We first check if all the bits of the roots are demanded. If they're not, 8180 // we can truncate the roots to this narrower type. 8181 for (auto *Root : TreeRoot) { 8182 auto Mask = DB->getDemandedBits(cast<Instruction>(Root)); 8183 MaxBitWidth = std::max<unsigned>( 8184 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth); 8185 } 8186 8187 // True if the roots can be zero-extended back to their original type, rather 8188 // than sign-extended. We know that if the leading bits are not demanded, we 8189 // can safely zero-extend. So we initialize IsKnownPositive to True. 8190 bool IsKnownPositive = true; 8191 8192 // If all the bits of the roots are demanded, we can try a little harder to 8193 // compute a narrower type. This can happen, for example, if the roots are 8194 // getelementptr indices. InstCombine promotes these indices to the pointer 8195 // width. Thus, all their bits are technically demanded even though the 8196 // address computation might be vectorized in a smaller type. 8197 // 8198 // We start by looking at each entry that can be demoted. We compute the 8199 // maximum bit width required to store the scalar by using ValueTracking to 8200 // compute the number of high-order bits we can truncate. 8201 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) && 8202 llvm::all_of(TreeRoot, [](Value *R) { 8203 assert(R->hasOneUse() && "Root should have only one use!"); 8204 return isa<GetElementPtrInst>(R->user_back()); 8205 })) { 8206 MaxBitWidth = 8u; 8207 8208 // Determine if the sign bit of all the roots is known to be zero. If not, 8209 // IsKnownPositive is set to False. 8210 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) { 8211 KnownBits Known = computeKnownBits(R, *DL); 8212 return Known.isNonNegative(); 8213 }); 8214 8215 // Determine the maximum number of bits required to store the scalar 8216 // values. 8217 for (auto *Scalar : ToDemote) { 8218 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT); 8219 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType()); 8220 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth); 8221 } 8222 8223 // If we can't prove that the sign bit is zero, we must add one to the 8224 // maximum bit width to account for the unknown sign bit. This preserves 8225 // the existing sign bit so we can safely sign-extend the root back to the 8226 // original type. Otherwise, if we know the sign bit is zero, we will 8227 // zero-extend the root instead. 8228 // 8229 // FIXME: This is somewhat suboptimal, as there will be cases where adding 8230 // one to the maximum bit width will yield a larger-than-necessary 8231 // type. In general, we need to add an extra bit only if we can't 8232 // prove that the upper bit of the original type is equal to the 8233 // upper bit of the proposed smaller type. If these two bits are the 8234 // same (either zero or one) we know that sign-extending from the 8235 // smaller type will result in the same value. Here, since we can't 8236 // yet prove this, we are just making the proposed smaller type 8237 // larger to ensure correctness. 8238 if (!IsKnownPositive) 8239 ++MaxBitWidth; 8240 } 8241 8242 // Round MaxBitWidth up to the next power-of-two. 8243 if (!isPowerOf2_64(MaxBitWidth)) 8244 MaxBitWidth = NextPowerOf2(MaxBitWidth); 8245 8246 // If the maximum bit width we compute is less than the with of the roots' 8247 // type, we can proceed with the narrowing. Otherwise, do nothing. 8248 if (MaxBitWidth >= TreeRootIT->getBitWidth()) 8249 return; 8250 8251 // If we can truncate the root, we must collect additional values that might 8252 // be demoted as a result. That is, those seeded by truncations we will 8253 // modify. 8254 while (!Roots.empty()) 8255 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots); 8256 8257 // Finally, map the values we can demote to the maximum bit with we computed. 8258 for (auto *Scalar : ToDemote) 8259 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive); 8260 } 8261 8262 namespace { 8263 8264 /// The SLPVectorizer Pass. 8265 struct SLPVectorizer : public FunctionPass { 8266 SLPVectorizerPass Impl; 8267 8268 /// Pass identification, replacement for typeid 8269 static char ID; 8270 8271 explicit SLPVectorizer() : FunctionPass(ID) { 8272 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); 8273 } 8274 8275 bool doInitialization(Module &M) override { return false; } 8276 8277 bool runOnFunction(Function &F) override { 8278 if (skipFunction(F)) 8279 return false; 8280 8281 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 8282 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 8283 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 8284 auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr; 8285 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 8286 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 8287 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 8288 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 8289 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); 8290 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 8291 8292 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 8293 } 8294 8295 void getAnalysisUsage(AnalysisUsage &AU) const override { 8296 FunctionPass::getAnalysisUsage(AU); 8297 AU.addRequired<AssumptionCacheTracker>(); 8298 AU.addRequired<ScalarEvolutionWrapperPass>(); 8299 AU.addRequired<AAResultsWrapperPass>(); 8300 AU.addRequired<TargetTransformInfoWrapperPass>(); 8301 AU.addRequired<LoopInfoWrapperPass>(); 8302 AU.addRequired<DominatorTreeWrapperPass>(); 8303 AU.addRequired<DemandedBitsWrapperPass>(); 8304 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 8305 AU.addRequired<InjectTLIMappingsLegacy>(); 8306 AU.addPreserved<LoopInfoWrapperPass>(); 8307 AU.addPreserved<DominatorTreeWrapperPass>(); 8308 AU.addPreserved<AAResultsWrapperPass>(); 8309 AU.addPreserved<GlobalsAAWrapperPass>(); 8310 AU.setPreservesCFG(); 8311 } 8312 }; 8313 8314 } // end anonymous namespace 8315 8316 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) { 8317 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 8318 auto *TTI = &AM.getResult<TargetIRAnalysis>(F); 8319 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F); 8320 auto *AA = &AM.getResult<AAManager>(F); 8321 auto *LI = &AM.getResult<LoopAnalysis>(F); 8322 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 8323 auto *AC = &AM.getResult<AssumptionAnalysis>(F); 8324 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F); 8325 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 8326 8327 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 8328 if (!Changed) 8329 return PreservedAnalyses::all(); 8330 8331 PreservedAnalyses PA; 8332 PA.preserveSet<CFGAnalyses>(); 8333 return PA; 8334 } 8335 8336 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_, 8337 TargetTransformInfo *TTI_, 8338 TargetLibraryInfo *TLI_, AAResults *AA_, 8339 LoopInfo *LI_, DominatorTree *DT_, 8340 AssumptionCache *AC_, DemandedBits *DB_, 8341 OptimizationRemarkEmitter *ORE_) { 8342 if (!RunSLPVectorization) 8343 return false; 8344 SE = SE_; 8345 TTI = TTI_; 8346 TLI = TLI_; 8347 AA = AA_; 8348 LI = LI_; 8349 DT = DT_; 8350 AC = AC_; 8351 DB = DB_; 8352 DL = &F.getParent()->getDataLayout(); 8353 8354 Stores.clear(); 8355 GEPs.clear(); 8356 bool Changed = false; 8357 8358 // If the target claims to have no vector registers don't attempt 8359 // vectorization. 8360 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) { 8361 LLVM_DEBUG( 8362 dbgs() << "SLP: Didn't find any vector registers for target, abort.\n"); 8363 return false; 8364 } 8365 8366 // Don't vectorize when the attribute NoImplicitFloat is used. 8367 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) 8368 return false; 8369 8370 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"); 8371 8372 // Use the bottom up slp vectorizer to construct chains that start with 8373 // store instructions. 8374 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_); 8375 8376 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to 8377 // delete instructions. 8378 8379 // Update DFS numbers now so that we can use them for ordering. 8380 DT->updateDFSNumbers(); 8381 8382 // Scan the blocks in the function in post order. 8383 for (auto BB : post_order(&F.getEntryBlock())) { 8384 collectSeedInstructions(BB); 8385 8386 // Vectorize trees that end at stores. 8387 if (!Stores.empty()) { 8388 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size() 8389 << " underlying objects.\n"); 8390 Changed |= vectorizeStoreChains(R); 8391 } 8392 8393 // Vectorize trees that end at reductions. 8394 Changed |= vectorizeChainsInBlock(BB, R); 8395 8396 // Vectorize the index computations of getelementptr instructions. This 8397 // is primarily intended to catch gather-like idioms ending at 8398 // non-consecutive loads. 8399 if (!GEPs.empty()) { 8400 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size() 8401 << " underlying objects.\n"); 8402 Changed |= vectorizeGEPIndices(BB, R); 8403 } 8404 } 8405 8406 if (Changed) { 8407 R.optimizeGatherSequence(); 8408 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n"); 8409 } 8410 return Changed; 8411 } 8412 8413 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R, 8414 unsigned Idx) { 8415 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size() 8416 << "\n"); 8417 const unsigned Sz = R.getVectorElementSize(Chain[0]); 8418 const unsigned MinVF = R.getMinVecRegSize() / Sz; 8419 unsigned VF = Chain.size(); 8420 8421 if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF) 8422 return false; 8423 8424 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx 8425 << "\n"); 8426 8427 R.buildTree(Chain); 8428 if (R.isTreeTinyAndNotFullyVectorizable()) 8429 return false; 8430 if (R.isLoadCombineCandidate()) 8431 return false; 8432 R.reorderTopToBottom(); 8433 R.reorderBottomToTop(); 8434 R.buildExternalUses(); 8435 8436 R.computeMinimumValueSizes(); 8437 8438 InstructionCost Cost = R.getTreeCost(); 8439 8440 LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n"); 8441 if (Cost < -SLPCostThreshold) { 8442 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n"); 8443 8444 using namespace ore; 8445 8446 R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized", 8447 cast<StoreInst>(Chain[0])) 8448 << "Stores SLP vectorized with cost " << NV("Cost", Cost) 8449 << " and with tree size " 8450 << NV("TreeSize", R.getTreeSize())); 8451 8452 R.vectorizeTree(); 8453 return true; 8454 } 8455 8456 return false; 8457 } 8458 8459 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores, 8460 BoUpSLP &R) { 8461 // We may run into multiple chains that merge into a single chain. We mark the 8462 // stores that we vectorized so that we don't visit the same store twice. 8463 BoUpSLP::ValueSet VectorizedStores; 8464 bool Changed = false; 8465 8466 int E = Stores.size(); 8467 SmallBitVector Tails(E, false); 8468 int MaxIter = MaxStoreLookup.getValue(); 8469 SmallVector<std::pair<int, int>, 16> ConsecutiveChain( 8470 E, std::make_pair(E, INT_MAX)); 8471 SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false)); 8472 int IterCnt; 8473 auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter, 8474 &CheckedPairs, 8475 &ConsecutiveChain](int K, int Idx) { 8476 if (IterCnt >= MaxIter) 8477 return true; 8478 if (CheckedPairs[Idx].test(K)) 8479 return ConsecutiveChain[K].second == 1 && 8480 ConsecutiveChain[K].first == Idx; 8481 ++IterCnt; 8482 CheckedPairs[Idx].set(K); 8483 CheckedPairs[K].set(Idx); 8484 Optional<int> Diff = getPointersDiff( 8485 Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(), 8486 Stores[Idx]->getValueOperand()->getType(), 8487 Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true); 8488 if (!Diff || *Diff == 0) 8489 return false; 8490 int Val = *Diff; 8491 if (Val < 0) { 8492 if (ConsecutiveChain[Idx].second > -Val) { 8493 Tails.set(K); 8494 ConsecutiveChain[Idx] = std::make_pair(K, -Val); 8495 } 8496 return false; 8497 } 8498 if (ConsecutiveChain[K].second <= Val) 8499 return false; 8500 8501 Tails.set(Idx); 8502 ConsecutiveChain[K] = std::make_pair(Idx, Val); 8503 return Val == 1; 8504 }; 8505 // Do a quadratic search on all of the given stores in reverse order and find 8506 // all of the pairs of stores that follow each other. 8507 for (int Idx = E - 1; Idx >= 0; --Idx) { 8508 // If a store has multiple consecutive store candidates, search according 8509 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ... 8510 // This is because usually pairing with immediate succeeding or preceding 8511 // candidate create the best chance to find slp vectorization opportunity. 8512 const int MaxLookDepth = std::max(E - Idx, Idx + 1); 8513 IterCnt = 0; 8514 for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset) 8515 if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) || 8516 (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx))) 8517 break; 8518 } 8519 8520 // Tracks if we tried to vectorize stores starting from the given tail 8521 // already. 8522 SmallBitVector TriedTails(E, false); 8523 // For stores that start but don't end a link in the chain: 8524 for (int Cnt = E; Cnt > 0; --Cnt) { 8525 int I = Cnt - 1; 8526 if (ConsecutiveChain[I].first == E || Tails.test(I)) 8527 continue; 8528 // We found a store instr that starts a chain. Now follow the chain and try 8529 // to vectorize it. 8530 BoUpSLP::ValueList Operands; 8531 // Collect the chain into a list. 8532 while (I != E && !VectorizedStores.count(Stores[I])) { 8533 Operands.push_back(Stores[I]); 8534 Tails.set(I); 8535 if (ConsecutiveChain[I].second != 1) { 8536 // Mark the new end in the chain and go back, if required. It might be 8537 // required if the original stores come in reversed order, for example. 8538 if (ConsecutiveChain[I].first != E && 8539 Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) && 8540 !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) { 8541 TriedTails.set(I); 8542 Tails.reset(ConsecutiveChain[I].first); 8543 if (Cnt < ConsecutiveChain[I].first + 2) 8544 Cnt = ConsecutiveChain[I].first + 2; 8545 } 8546 break; 8547 } 8548 // Move to the next value in the chain. 8549 I = ConsecutiveChain[I].first; 8550 } 8551 assert(!Operands.empty() && "Expected non-empty list of stores."); 8552 8553 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 8554 unsigned EltSize = R.getVectorElementSize(Operands[0]); 8555 unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize); 8556 8557 unsigned MinVF = R.getMinVF(EltSize); 8558 unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store), 8559 MaxElts); 8560 8561 // FIXME: Is division-by-2 the correct step? Should we assert that the 8562 // register size is a power-of-2? 8563 unsigned StartIdx = 0; 8564 for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) { 8565 for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) { 8566 ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size); 8567 if (!VectorizedStores.count(Slice.front()) && 8568 !VectorizedStores.count(Slice.back()) && 8569 vectorizeStoreChain(Slice, R, Cnt)) { 8570 // Mark the vectorized stores so that we don't vectorize them again. 8571 VectorizedStores.insert(Slice.begin(), Slice.end()); 8572 Changed = true; 8573 // If we vectorized initial block, no need to try to vectorize it 8574 // again. 8575 if (Cnt == StartIdx) 8576 StartIdx += Size; 8577 Cnt += Size; 8578 continue; 8579 } 8580 ++Cnt; 8581 } 8582 // Check if the whole array was vectorized already - exit. 8583 if (StartIdx >= Operands.size()) 8584 break; 8585 } 8586 } 8587 8588 return Changed; 8589 } 8590 8591 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) { 8592 // Initialize the collections. We will make a single pass over the block. 8593 Stores.clear(); 8594 GEPs.clear(); 8595 8596 // Visit the store and getelementptr instructions in BB and organize them in 8597 // Stores and GEPs according to the underlying objects of their pointer 8598 // operands. 8599 for (Instruction &I : *BB) { 8600 // Ignore store instructions that are volatile or have a pointer operand 8601 // that doesn't point to a scalar type. 8602 if (auto *SI = dyn_cast<StoreInst>(&I)) { 8603 if (!SI->isSimple()) 8604 continue; 8605 if (!isValidElementType(SI->getValueOperand()->getType())) 8606 continue; 8607 Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI); 8608 } 8609 8610 // Ignore getelementptr instructions that have more than one index, a 8611 // constant index, or a pointer operand that doesn't point to a scalar 8612 // type. 8613 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 8614 auto Idx = GEP->idx_begin()->get(); 8615 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx)) 8616 continue; 8617 if (!isValidElementType(Idx->getType())) 8618 continue; 8619 if (GEP->getType()->isVectorTy()) 8620 continue; 8621 GEPs[GEP->getPointerOperand()].push_back(GEP); 8622 } 8623 } 8624 } 8625 8626 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { 8627 if (!A || !B) 8628 return false; 8629 Value *VL[] = {A, B}; 8630 return tryToVectorizeList(VL, R); 8631 } 8632 8633 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, 8634 bool LimitForRegisterSize) { 8635 if (VL.size() < 2) 8636 return false; 8637 8638 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " 8639 << VL.size() << ".\n"); 8640 8641 // Check that all of the parts are instructions of the same type, 8642 // we permit an alternate opcode via InstructionsState. 8643 InstructionsState S = getSameOpcode(VL); 8644 if (!S.getOpcode()) 8645 return false; 8646 8647 Instruction *I0 = cast<Instruction>(S.OpValue); 8648 // Make sure invalid types (including vector type) are rejected before 8649 // determining vectorization factor for scalar instructions. 8650 for (Value *V : VL) { 8651 Type *Ty = V->getType(); 8652 if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) { 8653 // NOTE: the following will give user internal llvm type name, which may 8654 // not be useful. 8655 R.getORE()->emit([&]() { 8656 std::string type_str; 8657 llvm::raw_string_ostream rso(type_str); 8658 Ty->print(rso); 8659 return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0) 8660 << "Cannot SLP vectorize list: type " 8661 << rso.str() + " is unsupported by vectorizer"; 8662 }); 8663 return false; 8664 } 8665 } 8666 8667 unsigned Sz = R.getVectorElementSize(I0); 8668 unsigned MinVF = R.getMinVF(Sz); 8669 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF); 8670 MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF); 8671 if (MaxVF < 2) { 8672 R.getORE()->emit([&]() { 8673 return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0) 8674 << "Cannot SLP vectorize list: vectorization factor " 8675 << "less than 2 is not supported"; 8676 }); 8677 return false; 8678 } 8679 8680 bool Changed = false; 8681 bool CandidateFound = false; 8682 InstructionCost MinCost = SLPCostThreshold.getValue(); 8683 Type *ScalarTy = VL[0]->getType(); 8684 if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 8685 ScalarTy = IE->getOperand(1)->getType(); 8686 8687 unsigned NextInst = 0, MaxInst = VL.size(); 8688 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) { 8689 // No actual vectorization should happen, if number of parts is the same as 8690 // provided vectorization factor (i.e. the scalar type is used for vector 8691 // code during codegen). 8692 auto *VecTy = FixedVectorType::get(ScalarTy, VF); 8693 if (TTI->getNumberOfParts(VecTy) == VF) 8694 continue; 8695 for (unsigned I = NextInst; I < MaxInst; ++I) { 8696 unsigned OpsWidth = 0; 8697 8698 if (I + VF > MaxInst) 8699 OpsWidth = MaxInst - I; 8700 else 8701 OpsWidth = VF; 8702 8703 if (!isPowerOf2_32(OpsWidth)) 8704 continue; 8705 8706 if ((LimitForRegisterSize && OpsWidth < MaxVF) || 8707 (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2)) 8708 break; 8709 8710 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth); 8711 // Check that a previous iteration of this loop did not delete the Value. 8712 if (llvm::any_of(Ops, [&R](Value *V) { 8713 auto *I = dyn_cast<Instruction>(V); 8714 return I && R.isDeleted(I); 8715 })) 8716 continue; 8717 8718 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " 8719 << "\n"); 8720 8721 R.buildTree(Ops); 8722 if (R.isTreeTinyAndNotFullyVectorizable()) 8723 continue; 8724 R.reorderTopToBottom(); 8725 R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front())); 8726 R.buildExternalUses(); 8727 8728 R.computeMinimumValueSizes(); 8729 InstructionCost Cost = R.getTreeCost(); 8730 CandidateFound = true; 8731 MinCost = std::min(MinCost, Cost); 8732 8733 if (Cost < -SLPCostThreshold) { 8734 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n"); 8735 R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList", 8736 cast<Instruction>(Ops[0])) 8737 << "SLP vectorized with cost " << ore::NV("Cost", Cost) 8738 << " and with tree size " 8739 << ore::NV("TreeSize", R.getTreeSize())); 8740 8741 R.vectorizeTree(); 8742 // Move to the next bundle. 8743 I += VF - 1; 8744 NextInst = I + 1; 8745 Changed = true; 8746 } 8747 } 8748 } 8749 8750 if (!Changed && CandidateFound) { 8751 R.getORE()->emit([&]() { 8752 return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0) 8753 << "List vectorization was possible but not beneficial with cost " 8754 << ore::NV("Cost", MinCost) << " >= " 8755 << ore::NV("Treshold", -SLPCostThreshold); 8756 }); 8757 } else if (!Changed) { 8758 R.getORE()->emit([&]() { 8759 return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0) 8760 << "Cannot SLP vectorize list: vectorization was impossible" 8761 << " with available vectorization factors"; 8762 }); 8763 } 8764 return Changed; 8765 } 8766 8767 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) { 8768 if (!I) 8769 return false; 8770 8771 if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) 8772 return false; 8773 8774 Value *P = I->getParent(); 8775 8776 // Vectorize in current basic block only. 8777 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0)); 8778 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1)); 8779 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P) 8780 return false; 8781 8782 // Try to vectorize V. 8783 if (tryToVectorizePair(Op0, Op1, R)) 8784 return true; 8785 8786 auto *A = dyn_cast<BinaryOperator>(Op0); 8787 auto *B = dyn_cast<BinaryOperator>(Op1); 8788 // Try to skip B. 8789 if (B && B->hasOneUse()) { 8790 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); 8791 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); 8792 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R)) 8793 return true; 8794 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R)) 8795 return true; 8796 } 8797 8798 // Try to skip A. 8799 if (A && A->hasOneUse()) { 8800 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); 8801 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); 8802 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R)) 8803 return true; 8804 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R)) 8805 return true; 8806 } 8807 return false; 8808 } 8809 8810 namespace { 8811 8812 /// Model horizontal reductions. 8813 /// 8814 /// A horizontal reduction is a tree of reduction instructions that has values 8815 /// that can be put into a vector as its leaves. For example: 8816 /// 8817 /// mul mul mul mul 8818 /// \ / \ / 8819 /// + + 8820 /// \ / 8821 /// + 8822 /// This tree has "mul" as its leaf values and "+" as its reduction 8823 /// instructions. A reduction can feed into a store or a binary operation 8824 /// feeding a phi. 8825 /// ... 8826 /// \ / 8827 /// + 8828 /// | 8829 /// phi += 8830 /// 8831 /// Or: 8832 /// ... 8833 /// \ / 8834 /// + 8835 /// | 8836 /// *p = 8837 /// 8838 class HorizontalReduction { 8839 using ReductionOpsType = SmallVector<Value *, 16>; 8840 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>; 8841 ReductionOpsListType ReductionOps; 8842 SmallVector<Value *, 32> ReducedVals; 8843 // Use map vector to make stable output. 8844 MapVector<Instruction *, Value *> ExtraArgs; 8845 WeakTrackingVH ReductionRoot; 8846 /// The type of reduction operation. 8847 RecurKind RdxKind; 8848 8849 const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max(); 8850 8851 static bool isCmpSelMinMax(Instruction *I) { 8852 return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) && 8853 RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I)); 8854 } 8855 8856 // And/or are potentially poison-safe logical patterns like: 8857 // select x, y, false 8858 // select x, true, y 8859 static bool isBoolLogicOp(Instruction *I) { 8860 return match(I, m_LogicalAnd(m_Value(), m_Value())) || 8861 match(I, m_LogicalOr(m_Value(), m_Value())); 8862 } 8863 8864 /// Checks if instruction is associative and can be vectorized. 8865 static bool isVectorizable(RecurKind Kind, Instruction *I) { 8866 if (Kind == RecurKind::None) 8867 return false; 8868 8869 // Integer ops that map to select instructions or intrinsics are fine. 8870 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) || 8871 isBoolLogicOp(I)) 8872 return true; 8873 8874 if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) { 8875 // FP min/max are associative except for NaN and -0.0. We do not 8876 // have to rule out -0.0 here because the intrinsic semantics do not 8877 // specify a fixed result for it. 8878 return I->getFastMathFlags().noNaNs(); 8879 } 8880 8881 return I->isAssociative(); 8882 } 8883 8884 static Value *getRdxOperand(Instruction *I, unsigned Index) { 8885 // Poison-safe 'or' takes the form: select X, true, Y 8886 // To make that work with the normal operand processing, we skip the 8887 // true value operand. 8888 // TODO: Change the code and data structures to handle this without a hack. 8889 if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1) 8890 return I->getOperand(2); 8891 return I->getOperand(Index); 8892 } 8893 8894 /// Checks if the ParentStackElem.first should be marked as a reduction 8895 /// operation with an extra argument or as extra argument itself. 8896 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem, 8897 Value *ExtraArg) { 8898 if (ExtraArgs.count(ParentStackElem.first)) { 8899 ExtraArgs[ParentStackElem.first] = nullptr; 8900 // We ran into something like: 8901 // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg. 8902 // The whole ParentStackElem.first should be considered as an extra value 8903 // in this case. 8904 // Do not perform analysis of remaining operands of ParentStackElem.first 8905 // instruction, this whole instruction is an extra argument. 8906 ParentStackElem.second = INVALID_OPERAND_INDEX; 8907 } else { 8908 // We ran into something like: 8909 // ParentStackElem.first += ... + ExtraArg + ... 8910 ExtraArgs[ParentStackElem.first] = ExtraArg; 8911 } 8912 } 8913 8914 /// Creates reduction operation with the current opcode. 8915 static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS, 8916 Value *RHS, const Twine &Name, bool UseSelect) { 8917 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind); 8918 switch (Kind) { 8919 case RecurKind::Or: 8920 if (UseSelect && 8921 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 8922 return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name); 8923 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8924 Name); 8925 case RecurKind::And: 8926 if (UseSelect && 8927 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 8928 return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name); 8929 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8930 Name); 8931 case RecurKind::Add: 8932 case RecurKind::Mul: 8933 case RecurKind::Xor: 8934 case RecurKind::FAdd: 8935 case RecurKind::FMul: 8936 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8937 Name); 8938 case RecurKind::FMax: 8939 return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS); 8940 case RecurKind::FMin: 8941 return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS); 8942 case RecurKind::SMax: 8943 if (UseSelect) { 8944 Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name); 8945 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8946 } 8947 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS); 8948 case RecurKind::SMin: 8949 if (UseSelect) { 8950 Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name); 8951 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8952 } 8953 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS); 8954 case RecurKind::UMax: 8955 if (UseSelect) { 8956 Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name); 8957 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8958 } 8959 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS); 8960 case RecurKind::UMin: 8961 if (UseSelect) { 8962 Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name); 8963 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8964 } 8965 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS); 8966 default: 8967 llvm_unreachable("Unknown reduction operation."); 8968 } 8969 } 8970 8971 /// Creates reduction operation with the current opcode with the IR flags 8972 /// from \p ReductionOps. 8973 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 8974 Value *RHS, const Twine &Name, 8975 const ReductionOpsListType &ReductionOps) { 8976 bool UseSelect = ReductionOps.size() == 2 || 8977 // Logical or/and. 8978 (ReductionOps.size() == 1 && 8979 isa<SelectInst>(ReductionOps.front().front())); 8980 assert((!UseSelect || ReductionOps.size() != 2 || 8981 isa<SelectInst>(ReductionOps[1][0])) && 8982 "Expected cmp + select pairs for reduction"); 8983 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect); 8984 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 8985 if (auto *Sel = dyn_cast<SelectInst>(Op)) { 8986 propagateIRFlags(Sel->getCondition(), ReductionOps[0]); 8987 propagateIRFlags(Op, ReductionOps[1]); 8988 return Op; 8989 } 8990 } 8991 propagateIRFlags(Op, ReductionOps[0]); 8992 return Op; 8993 } 8994 8995 /// Creates reduction operation with the current opcode with the IR flags 8996 /// from \p I. 8997 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 8998 Value *RHS, const Twine &Name, Instruction *I) { 8999 auto *SelI = dyn_cast<SelectInst>(I); 9000 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr); 9001 if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 9002 if (auto *Sel = dyn_cast<SelectInst>(Op)) 9003 propagateIRFlags(Sel->getCondition(), SelI->getCondition()); 9004 } 9005 propagateIRFlags(Op, I); 9006 return Op; 9007 } 9008 9009 static RecurKind getRdxKind(Instruction *I) { 9010 assert(I && "Expected instruction for reduction matching"); 9011 if (match(I, m_Add(m_Value(), m_Value()))) 9012 return RecurKind::Add; 9013 if (match(I, m_Mul(m_Value(), m_Value()))) 9014 return RecurKind::Mul; 9015 if (match(I, m_And(m_Value(), m_Value())) || 9016 match(I, m_LogicalAnd(m_Value(), m_Value()))) 9017 return RecurKind::And; 9018 if (match(I, m_Or(m_Value(), m_Value())) || 9019 match(I, m_LogicalOr(m_Value(), m_Value()))) 9020 return RecurKind::Or; 9021 if (match(I, m_Xor(m_Value(), m_Value()))) 9022 return RecurKind::Xor; 9023 if (match(I, m_FAdd(m_Value(), m_Value()))) 9024 return RecurKind::FAdd; 9025 if (match(I, m_FMul(m_Value(), m_Value()))) 9026 return RecurKind::FMul; 9027 9028 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value()))) 9029 return RecurKind::FMax; 9030 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value()))) 9031 return RecurKind::FMin; 9032 9033 // This matches either cmp+select or intrinsics. SLP is expected to handle 9034 // either form. 9035 // TODO: If we are canonicalizing to intrinsics, we can remove several 9036 // special-case paths that deal with selects. 9037 if (match(I, m_SMax(m_Value(), m_Value()))) 9038 return RecurKind::SMax; 9039 if (match(I, m_SMin(m_Value(), m_Value()))) 9040 return RecurKind::SMin; 9041 if (match(I, m_UMax(m_Value(), m_Value()))) 9042 return RecurKind::UMax; 9043 if (match(I, m_UMin(m_Value(), m_Value()))) 9044 return RecurKind::UMin; 9045 9046 if (auto *Select = dyn_cast<SelectInst>(I)) { 9047 // Try harder: look for min/max pattern based on instructions producing 9048 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2). 9049 // During the intermediate stages of SLP, it's very common to have 9050 // pattern like this (since optimizeGatherSequence is run only once 9051 // at the end): 9052 // %1 = extractelement <2 x i32> %a, i32 0 9053 // %2 = extractelement <2 x i32> %a, i32 1 9054 // %cond = icmp sgt i32 %1, %2 9055 // %3 = extractelement <2 x i32> %a, i32 0 9056 // %4 = extractelement <2 x i32> %a, i32 1 9057 // %select = select i1 %cond, i32 %3, i32 %4 9058 CmpInst::Predicate Pred; 9059 Instruction *L1; 9060 Instruction *L2; 9061 9062 Value *LHS = Select->getTrueValue(); 9063 Value *RHS = Select->getFalseValue(); 9064 Value *Cond = Select->getCondition(); 9065 9066 // TODO: Support inverse predicates. 9067 if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) { 9068 if (!isa<ExtractElementInst>(RHS) || 9069 !L2->isIdenticalTo(cast<Instruction>(RHS))) 9070 return RecurKind::None; 9071 } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) { 9072 if (!isa<ExtractElementInst>(LHS) || 9073 !L1->isIdenticalTo(cast<Instruction>(LHS))) 9074 return RecurKind::None; 9075 } else { 9076 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS)) 9077 return RecurKind::None; 9078 if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) || 9079 !L1->isIdenticalTo(cast<Instruction>(LHS)) || 9080 !L2->isIdenticalTo(cast<Instruction>(RHS))) 9081 return RecurKind::None; 9082 } 9083 9084 switch (Pred) { 9085 default: 9086 return RecurKind::None; 9087 case CmpInst::ICMP_SGT: 9088 case CmpInst::ICMP_SGE: 9089 return RecurKind::SMax; 9090 case CmpInst::ICMP_SLT: 9091 case CmpInst::ICMP_SLE: 9092 return RecurKind::SMin; 9093 case CmpInst::ICMP_UGT: 9094 case CmpInst::ICMP_UGE: 9095 return RecurKind::UMax; 9096 case CmpInst::ICMP_ULT: 9097 case CmpInst::ICMP_ULE: 9098 return RecurKind::UMin; 9099 } 9100 } 9101 return RecurKind::None; 9102 } 9103 9104 /// Get the index of the first operand. 9105 static unsigned getFirstOperandIndex(Instruction *I) { 9106 return isCmpSelMinMax(I) ? 1 : 0; 9107 } 9108 9109 /// Total number of operands in the reduction operation. 9110 static unsigned getNumberOfOperands(Instruction *I) { 9111 return isCmpSelMinMax(I) ? 3 : 2; 9112 } 9113 9114 /// Checks if the instruction is in basic block \p BB. 9115 /// For a cmp+sel min/max reduction check that both ops are in \p BB. 9116 static bool hasSameParent(Instruction *I, BasicBlock *BB) { 9117 if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) { 9118 auto *Sel = cast<SelectInst>(I); 9119 auto *Cmp = dyn_cast<Instruction>(Sel->getCondition()); 9120 return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB; 9121 } 9122 return I->getParent() == BB; 9123 } 9124 9125 /// Expected number of uses for reduction operations/reduced values. 9126 static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) { 9127 if (IsCmpSelMinMax) { 9128 // SelectInst must be used twice while the condition op must have single 9129 // use only. 9130 if (auto *Sel = dyn_cast<SelectInst>(I)) 9131 return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse(); 9132 return I->hasNUses(2); 9133 } 9134 9135 // Arithmetic reduction operation must be used once only. 9136 return I->hasOneUse(); 9137 } 9138 9139 /// Initializes the list of reduction operations. 9140 void initReductionOps(Instruction *I) { 9141 if (isCmpSelMinMax(I)) 9142 ReductionOps.assign(2, ReductionOpsType()); 9143 else 9144 ReductionOps.assign(1, ReductionOpsType()); 9145 } 9146 9147 /// Add all reduction operations for the reduction instruction \p I. 9148 void addReductionOps(Instruction *I) { 9149 if (isCmpSelMinMax(I)) { 9150 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition()); 9151 ReductionOps[1].emplace_back(I); 9152 } else { 9153 ReductionOps[0].emplace_back(I); 9154 } 9155 } 9156 9157 static Value *getLHS(RecurKind Kind, Instruction *I) { 9158 if (Kind == RecurKind::None) 9159 return nullptr; 9160 return I->getOperand(getFirstOperandIndex(I)); 9161 } 9162 static Value *getRHS(RecurKind Kind, Instruction *I) { 9163 if (Kind == RecurKind::None) 9164 return nullptr; 9165 return I->getOperand(getFirstOperandIndex(I) + 1); 9166 } 9167 9168 public: 9169 HorizontalReduction() = default; 9170 9171 /// Try to find a reduction tree. 9172 bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) { 9173 assert((!Phi || is_contained(Phi->operands(), Inst)) && 9174 "Phi needs to use the binary operator"); 9175 assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || 9176 isa<IntrinsicInst>(Inst)) && 9177 "Expected binop, select, or intrinsic for reduction matching"); 9178 RdxKind = getRdxKind(Inst); 9179 9180 // We could have a initial reductions that is not an add. 9181 // r *= v1 + v2 + v3 + v4 9182 // In such a case start looking for a tree rooted in the first '+'. 9183 if (Phi) { 9184 if (getLHS(RdxKind, Inst) == Phi) { 9185 Phi = nullptr; 9186 Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst)); 9187 if (!Inst) 9188 return false; 9189 RdxKind = getRdxKind(Inst); 9190 } else if (getRHS(RdxKind, Inst) == Phi) { 9191 Phi = nullptr; 9192 Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst)); 9193 if (!Inst) 9194 return false; 9195 RdxKind = getRdxKind(Inst); 9196 } 9197 } 9198 9199 if (!isVectorizable(RdxKind, Inst)) 9200 return false; 9201 9202 // Analyze "regular" integer/FP types for reductions - no target-specific 9203 // types or pointers. 9204 Type *Ty = Inst->getType(); 9205 if (!isValidElementType(Ty) || Ty->isPointerTy()) 9206 return false; 9207 9208 // Though the ultimate reduction may have multiple uses, its condition must 9209 // have only single use. 9210 if (auto *Sel = dyn_cast<SelectInst>(Inst)) 9211 if (!Sel->getCondition()->hasOneUse()) 9212 return false; 9213 9214 ReductionRoot = Inst; 9215 9216 // The opcode for leaf values that we perform a reduction on. 9217 // For example: load(x) + load(y) + load(z) + fptoui(w) 9218 // The leaf opcode for 'w' does not match, so we don't include it as a 9219 // potential candidate for the reduction. 9220 unsigned LeafOpcode = 0; 9221 9222 // Post-order traverse the reduction tree starting at Inst. We only handle 9223 // true trees containing binary operators or selects. 9224 SmallVector<std::pair<Instruction *, unsigned>, 32> Stack; 9225 Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst))); 9226 initReductionOps(Inst); 9227 while (!Stack.empty()) { 9228 Instruction *TreeN = Stack.back().first; 9229 unsigned EdgeToVisit = Stack.back().second++; 9230 const RecurKind TreeRdxKind = getRdxKind(TreeN); 9231 bool IsReducedValue = TreeRdxKind != RdxKind; 9232 9233 // Postorder visit. 9234 if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) { 9235 if (IsReducedValue) 9236 ReducedVals.push_back(TreeN); 9237 else { 9238 auto ExtraArgsIter = ExtraArgs.find(TreeN); 9239 if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) { 9240 // Check if TreeN is an extra argument of its parent operation. 9241 if (Stack.size() <= 1) { 9242 // TreeN can't be an extra argument as it is a root reduction 9243 // operation. 9244 return false; 9245 } 9246 // Yes, TreeN is an extra argument, do not add it to a list of 9247 // reduction operations. 9248 // Stack[Stack.size() - 2] always points to the parent operation. 9249 markExtraArg(Stack[Stack.size() - 2], TreeN); 9250 ExtraArgs.erase(TreeN); 9251 } else 9252 addReductionOps(TreeN); 9253 } 9254 // Retract. 9255 Stack.pop_back(); 9256 continue; 9257 } 9258 9259 // Visit operands. 9260 Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit); 9261 auto *EdgeInst = dyn_cast<Instruction>(EdgeVal); 9262 if (!EdgeInst) { 9263 // Edge value is not a reduction instruction or a leaf instruction. 9264 // (It may be a constant, function argument, or something else.) 9265 markExtraArg(Stack.back(), EdgeVal); 9266 continue; 9267 } 9268 RecurKind EdgeRdxKind = getRdxKind(EdgeInst); 9269 // Continue analysis if the next operand is a reduction operation or 9270 // (possibly) a leaf value. If the leaf value opcode is not set, 9271 // the first met operation != reduction operation is considered as the 9272 // leaf opcode. 9273 // Only handle trees in the current basic block. 9274 // Each tree node needs to have minimal number of users except for the 9275 // ultimate reduction. 9276 const bool IsRdxInst = EdgeRdxKind == RdxKind; 9277 if (EdgeInst != Phi && EdgeInst != Inst && 9278 hasSameParent(EdgeInst, Inst->getParent()) && 9279 hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) && 9280 (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) { 9281 if (IsRdxInst) { 9282 // We need to be able to reassociate the reduction operations. 9283 if (!isVectorizable(EdgeRdxKind, EdgeInst)) { 9284 // I is an extra argument for TreeN (its parent operation). 9285 markExtraArg(Stack.back(), EdgeInst); 9286 continue; 9287 } 9288 } else if (!LeafOpcode) { 9289 LeafOpcode = EdgeInst->getOpcode(); 9290 } 9291 Stack.push_back( 9292 std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst))); 9293 continue; 9294 } 9295 // I is an extra argument for TreeN (its parent operation). 9296 markExtraArg(Stack.back(), EdgeInst); 9297 } 9298 return true; 9299 } 9300 9301 /// Attempt to vectorize the tree found by matchAssociativeReduction. 9302 Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) { 9303 // If there are a sufficient number of reduction values, reduce 9304 // to a nearby power-of-2. We can safely generate oversized 9305 // vectors and rely on the backend to split them to legal sizes. 9306 unsigned NumReducedVals = ReducedVals.size(); 9307 if (NumReducedVals < 4) 9308 return nullptr; 9309 9310 // Intersect the fast-math-flags from all reduction operations. 9311 FastMathFlags RdxFMF; 9312 RdxFMF.set(); 9313 for (ReductionOpsType &RdxOp : ReductionOps) { 9314 for (Value *RdxVal : RdxOp) { 9315 if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal)) 9316 RdxFMF &= FPMO->getFastMathFlags(); 9317 } 9318 } 9319 9320 IRBuilder<> Builder(cast<Instruction>(ReductionRoot)); 9321 Builder.setFastMathFlags(RdxFMF); 9322 9323 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues; 9324 // The same extra argument may be used several times, so log each attempt 9325 // to use it. 9326 for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) { 9327 assert(Pair.first && "DebugLoc must be set."); 9328 ExternallyUsedValues[Pair.second].push_back(Pair.first); 9329 } 9330 9331 // The compare instruction of a min/max is the insertion point for new 9332 // instructions and may be replaced with a new compare instruction. 9333 auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) { 9334 assert(isa<SelectInst>(RdxRootInst) && 9335 "Expected min/max reduction to have select root instruction"); 9336 Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition(); 9337 assert(isa<Instruction>(ScalarCond) && 9338 "Expected min/max reduction to have compare condition"); 9339 return cast<Instruction>(ScalarCond); 9340 }; 9341 9342 // The reduction root is used as the insertion point for new instructions, 9343 // so set it as externally used to prevent it from being deleted. 9344 ExternallyUsedValues[ReductionRoot]; 9345 SmallVector<Value *, 16> IgnoreList; 9346 for (ReductionOpsType &RdxOp : ReductionOps) 9347 IgnoreList.append(RdxOp.begin(), RdxOp.end()); 9348 9349 unsigned ReduxWidth = PowerOf2Floor(NumReducedVals); 9350 if (NumReducedVals > ReduxWidth) { 9351 // In the loop below, we are building a tree based on a window of 9352 // 'ReduxWidth' values. 9353 // If the operands of those values have common traits (compare predicate, 9354 // constant operand, etc), then we want to group those together to 9355 // minimize the cost of the reduction. 9356 9357 // TODO: This should be extended to count common operands for 9358 // compares and binops. 9359 9360 // Step 1: Count the number of times each compare predicate occurs. 9361 SmallDenseMap<unsigned, unsigned> PredCountMap; 9362 for (Value *RdxVal : ReducedVals) { 9363 CmpInst::Predicate Pred; 9364 if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value()))) 9365 ++PredCountMap[Pred]; 9366 } 9367 // Step 2: Sort the values so the most common predicates come first. 9368 stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) { 9369 CmpInst::Predicate PredA, PredB; 9370 if (match(A, m_Cmp(PredA, m_Value(), m_Value())) && 9371 match(B, m_Cmp(PredB, m_Value(), m_Value()))) { 9372 return PredCountMap[PredA] > PredCountMap[PredB]; 9373 } 9374 return false; 9375 }); 9376 } 9377 9378 Value *VectorizedTree = nullptr; 9379 unsigned i = 0; 9380 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) { 9381 ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth); 9382 V.buildTree(VL, IgnoreList); 9383 if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) 9384 break; 9385 if (V.isLoadCombineReductionCandidate(RdxKind)) 9386 break; 9387 V.reorderTopToBottom(); 9388 V.reorderBottomToTop(/*IgnoreReorder=*/true); 9389 V.buildExternalUses(ExternallyUsedValues); 9390 9391 // For a poison-safe boolean logic reduction, do not replace select 9392 // instructions with logic ops. All reduced values will be frozen (see 9393 // below) to prevent leaking poison. 9394 if (isa<SelectInst>(ReductionRoot) && 9395 isBoolLogicOp(cast<Instruction>(ReductionRoot)) && 9396 NumReducedVals != ReduxWidth) 9397 break; 9398 9399 V.computeMinimumValueSizes(); 9400 9401 // Estimate cost. 9402 InstructionCost TreeCost = 9403 V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth)); 9404 InstructionCost ReductionCost = 9405 getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF); 9406 InstructionCost Cost = TreeCost + ReductionCost; 9407 if (!Cost.isValid()) { 9408 LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n"); 9409 return nullptr; 9410 } 9411 if (Cost >= -SLPCostThreshold) { 9412 V.getORE()->emit([&]() { 9413 return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial", 9414 cast<Instruction>(VL[0])) 9415 << "Vectorizing horizontal reduction is possible" 9416 << "but not beneficial with cost " << ore::NV("Cost", Cost) 9417 << " and threshold " 9418 << ore::NV("Threshold", -SLPCostThreshold); 9419 }); 9420 break; 9421 } 9422 9423 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" 9424 << Cost << ". (HorRdx)\n"); 9425 V.getORE()->emit([&]() { 9426 return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction", 9427 cast<Instruction>(VL[0])) 9428 << "Vectorized horizontal reduction with cost " 9429 << ore::NV("Cost", Cost) << " and with tree size " 9430 << ore::NV("TreeSize", V.getTreeSize()); 9431 }); 9432 9433 // Vectorize a tree. 9434 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc(); 9435 Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues); 9436 9437 // Emit a reduction. If the root is a select (min/max idiom), the insert 9438 // point is the compare condition of that select. 9439 Instruction *RdxRootInst = cast<Instruction>(ReductionRoot); 9440 if (isCmpSelMinMax(RdxRootInst)) 9441 Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst)); 9442 else 9443 Builder.SetInsertPoint(RdxRootInst); 9444 9445 // To prevent poison from leaking across what used to be sequential, safe, 9446 // scalar boolean logic operations, the reduction operand must be frozen. 9447 if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst)) 9448 VectorizedRoot = Builder.CreateFreeze(VectorizedRoot); 9449 9450 Value *ReducedSubTree = 9451 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI); 9452 9453 if (!VectorizedTree) { 9454 // Initialize the final value in the reduction. 9455 VectorizedTree = ReducedSubTree; 9456 } else { 9457 // Update the final value in the reduction. 9458 Builder.SetCurrentDebugLocation(Loc); 9459 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 9460 ReducedSubTree, "op.rdx", ReductionOps); 9461 } 9462 i += ReduxWidth; 9463 ReduxWidth = PowerOf2Floor(NumReducedVals - i); 9464 } 9465 9466 if (VectorizedTree) { 9467 // Finish the reduction. 9468 for (; i < NumReducedVals; ++i) { 9469 auto *I = cast<Instruction>(ReducedVals[i]); 9470 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 9471 VectorizedTree = 9472 createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps); 9473 } 9474 for (auto &Pair : ExternallyUsedValues) { 9475 // Add each externally used value to the final reduction. 9476 for (auto *I : Pair.second) { 9477 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 9478 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 9479 Pair.first, "op.extra", I); 9480 } 9481 } 9482 9483 ReductionRoot->replaceAllUsesWith(VectorizedTree); 9484 9485 // Mark all scalar reduction ops for deletion, they are replaced by the 9486 // vector reductions. 9487 V.eraseInstructions(IgnoreList); 9488 } 9489 return VectorizedTree; 9490 } 9491 9492 unsigned numReductionValues() const { return ReducedVals.size(); } 9493 9494 private: 9495 /// Calculate the cost of a reduction. 9496 InstructionCost getReductionCost(TargetTransformInfo *TTI, 9497 Value *FirstReducedVal, unsigned ReduxWidth, 9498 FastMathFlags FMF) { 9499 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 9500 Type *ScalarTy = FirstReducedVal->getType(); 9501 FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth); 9502 InstructionCost VectorCost, ScalarCost; 9503 switch (RdxKind) { 9504 case RecurKind::Add: 9505 case RecurKind::Mul: 9506 case RecurKind::Or: 9507 case RecurKind::And: 9508 case RecurKind::Xor: 9509 case RecurKind::FAdd: 9510 case RecurKind::FMul: { 9511 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind); 9512 VectorCost = 9513 TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind); 9514 ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind); 9515 break; 9516 } 9517 case RecurKind::FMax: 9518 case RecurKind::FMin: { 9519 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 9520 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 9521 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, 9522 /*IsUnsigned=*/false, CostKind); 9523 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 9524 ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy, 9525 SclCondTy, RdxPred, CostKind) + 9526 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 9527 SclCondTy, RdxPred, CostKind); 9528 break; 9529 } 9530 case RecurKind::SMax: 9531 case RecurKind::SMin: 9532 case RecurKind::UMax: 9533 case RecurKind::UMin: { 9534 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 9535 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 9536 bool IsUnsigned = 9537 RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin; 9538 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned, 9539 CostKind); 9540 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 9541 ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy, 9542 SclCondTy, RdxPred, CostKind) + 9543 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 9544 SclCondTy, RdxPred, CostKind); 9545 break; 9546 } 9547 default: 9548 llvm_unreachable("Expected arithmetic or min/max reduction operation"); 9549 } 9550 9551 // Scalar cost is repeated for N-1 elements. 9552 ScalarCost *= (ReduxWidth - 1); 9553 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost 9554 << " for reduction that starts with " << *FirstReducedVal 9555 << " (It is a splitting reduction)\n"); 9556 return VectorCost - ScalarCost; 9557 } 9558 9559 /// Emit a horizontal reduction of the vectorized value. 9560 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder, 9561 unsigned ReduxWidth, const TargetTransformInfo *TTI) { 9562 assert(VectorizedValue && "Need to have a vectorized tree node"); 9563 assert(isPowerOf2_32(ReduxWidth) && 9564 "We only handle power-of-two reductions for now"); 9565 assert(RdxKind != RecurKind::FMulAdd && 9566 "A call to the llvm.fmuladd intrinsic is not handled yet"); 9567 9568 ++NumVectorInstructions; 9569 return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind); 9570 } 9571 }; 9572 9573 } // end anonymous namespace 9574 9575 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) { 9576 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) 9577 return cast<FixedVectorType>(IE->getType())->getNumElements(); 9578 9579 unsigned AggregateSize = 1; 9580 auto *IV = cast<InsertValueInst>(InsertInst); 9581 Type *CurrentType = IV->getType(); 9582 do { 9583 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 9584 for (auto *Elt : ST->elements()) 9585 if (Elt != ST->getElementType(0)) // check homogeneity 9586 return None; 9587 AggregateSize *= ST->getNumElements(); 9588 CurrentType = ST->getElementType(0); 9589 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 9590 AggregateSize *= AT->getNumElements(); 9591 CurrentType = AT->getElementType(); 9592 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) { 9593 AggregateSize *= VT->getNumElements(); 9594 return AggregateSize; 9595 } else if (CurrentType->isSingleValueType()) { 9596 return AggregateSize; 9597 } else { 9598 return None; 9599 } 9600 } while (true); 9601 } 9602 9603 static bool findBuildAggregate_rec(Instruction *LastInsertInst, 9604 TargetTransformInfo *TTI, 9605 SmallVectorImpl<Value *> &BuildVectorOpds, 9606 SmallVectorImpl<Value *> &InsertElts, 9607 unsigned OperandOffset) { 9608 do { 9609 Value *InsertedOperand = LastInsertInst->getOperand(1); 9610 Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset); 9611 if (!OperandIndex) 9612 return false; 9613 if (isa<InsertElementInst>(InsertedOperand) || 9614 isa<InsertValueInst>(InsertedOperand)) { 9615 if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI, 9616 BuildVectorOpds, InsertElts, *OperandIndex)) 9617 return false; 9618 } else { 9619 BuildVectorOpds[*OperandIndex] = InsertedOperand; 9620 InsertElts[*OperandIndex] = LastInsertInst; 9621 } 9622 LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0)); 9623 } while (LastInsertInst != nullptr && 9624 (isa<InsertValueInst>(LastInsertInst) || 9625 isa<InsertElementInst>(LastInsertInst)) && 9626 LastInsertInst->hasOneUse()); 9627 return true; 9628 } 9629 9630 /// Recognize construction of vectors like 9631 /// %ra = insertelement <4 x float> poison, float %s0, i32 0 9632 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1 9633 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2 9634 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3 9635 /// starting from the last insertelement or insertvalue instruction. 9636 /// 9637 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>}, 9638 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on. 9639 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples. 9640 /// 9641 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type. 9642 /// 9643 /// \return true if it matches. 9644 static bool findBuildAggregate(Instruction *LastInsertInst, 9645 TargetTransformInfo *TTI, 9646 SmallVectorImpl<Value *> &BuildVectorOpds, 9647 SmallVectorImpl<Value *> &InsertElts) { 9648 9649 assert((isa<InsertElementInst>(LastInsertInst) || 9650 isa<InsertValueInst>(LastInsertInst)) && 9651 "Expected insertelement or insertvalue instruction!"); 9652 9653 assert((BuildVectorOpds.empty() && InsertElts.empty()) && 9654 "Expected empty result vectors!"); 9655 9656 Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst); 9657 if (!AggregateSize) 9658 return false; 9659 BuildVectorOpds.resize(*AggregateSize); 9660 InsertElts.resize(*AggregateSize); 9661 9662 if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 9663 0)) { 9664 llvm::erase_value(BuildVectorOpds, nullptr); 9665 llvm::erase_value(InsertElts, nullptr); 9666 if (BuildVectorOpds.size() >= 2) 9667 return true; 9668 } 9669 9670 return false; 9671 } 9672 9673 /// Try and get a reduction value from a phi node. 9674 /// 9675 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions 9676 /// if they come from either \p ParentBB or a containing loop latch. 9677 /// 9678 /// \returns A candidate reduction value if possible, or \code nullptr \endcode 9679 /// if not possible. 9680 static Value *getReductionValue(const DominatorTree *DT, PHINode *P, 9681 BasicBlock *ParentBB, LoopInfo *LI) { 9682 // There are situations where the reduction value is not dominated by the 9683 // reduction phi. Vectorizing such cases has been reported to cause 9684 // miscompiles. See PR25787. 9685 auto DominatedReduxValue = [&](Value *R) { 9686 return isa<Instruction>(R) && 9687 DT->dominates(P->getParent(), cast<Instruction>(R)->getParent()); 9688 }; 9689 9690 Value *Rdx = nullptr; 9691 9692 // Return the incoming value if it comes from the same BB as the phi node. 9693 if (P->getIncomingBlock(0) == ParentBB) { 9694 Rdx = P->getIncomingValue(0); 9695 } else if (P->getIncomingBlock(1) == ParentBB) { 9696 Rdx = P->getIncomingValue(1); 9697 } 9698 9699 if (Rdx && DominatedReduxValue(Rdx)) 9700 return Rdx; 9701 9702 // Otherwise, check whether we have a loop latch to look at. 9703 Loop *BBL = LI->getLoopFor(ParentBB); 9704 if (!BBL) 9705 return nullptr; 9706 BasicBlock *BBLatch = BBL->getLoopLatch(); 9707 if (!BBLatch) 9708 return nullptr; 9709 9710 // There is a loop latch, return the incoming value if it comes from 9711 // that. This reduction pattern occasionally turns up. 9712 if (P->getIncomingBlock(0) == BBLatch) { 9713 Rdx = P->getIncomingValue(0); 9714 } else if (P->getIncomingBlock(1) == BBLatch) { 9715 Rdx = P->getIncomingValue(1); 9716 } 9717 9718 if (Rdx && DominatedReduxValue(Rdx)) 9719 return Rdx; 9720 9721 return nullptr; 9722 } 9723 9724 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) { 9725 if (match(I, m_BinOp(m_Value(V0), m_Value(V1)))) 9726 return true; 9727 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1)))) 9728 return true; 9729 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1)))) 9730 return true; 9731 if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1)))) 9732 return true; 9733 if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1)))) 9734 return true; 9735 if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1)))) 9736 return true; 9737 if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1)))) 9738 return true; 9739 return false; 9740 } 9741 9742 /// Attempt to reduce a horizontal reduction. 9743 /// If it is legal to match a horizontal reduction feeding the phi node \a P 9744 /// with reduction operators \a Root (or one of its operands) in a basic block 9745 /// \a BB, then check if it can be done. If horizontal reduction is not found 9746 /// and root instruction is a binary operation, vectorization of the operands is 9747 /// attempted. 9748 /// \returns true if a horizontal reduction was matched and reduced or operands 9749 /// of one of the binary instruction were vectorized. 9750 /// \returns false if a horizontal reduction was not matched (or not possible) 9751 /// or no vectorization of any binary operation feeding \a Root instruction was 9752 /// performed. 9753 static bool tryToVectorizeHorReductionOrInstOperands( 9754 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, 9755 TargetTransformInfo *TTI, 9756 const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) { 9757 if (!ShouldVectorizeHor) 9758 return false; 9759 9760 if (!Root) 9761 return false; 9762 9763 if (Root->getParent() != BB || isa<PHINode>(Root)) 9764 return false; 9765 // Start analysis starting from Root instruction. If horizontal reduction is 9766 // found, try to vectorize it. If it is not a horizontal reduction or 9767 // vectorization is not possible or not effective, and currently analyzed 9768 // instruction is a binary operation, try to vectorize the operands, using 9769 // pre-order DFS traversal order. If the operands were not vectorized, repeat 9770 // the same procedure considering each operand as a possible root of the 9771 // horizontal reduction. 9772 // Interrupt the process if the Root instruction itself was vectorized or all 9773 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized. 9774 // Skip the analysis of CmpInsts.Compiler implements postanalysis of the 9775 // CmpInsts so we can skip extra attempts in 9776 // tryToVectorizeHorReductionOrInstOperands and save compile time. 9777 std::queue<std::pair<Instruction *, unsigned>> Stack; 9778 Stack.emplace(Root, 0); 9779 SmallPtrSet<Value *, 8> VisitedInstrs; 9780 SmallVector<WeakTrackingVH> PostponedInsts; 9781 bool Res = false; 9782 auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0, 9783 Value *&B1) -> Value * { 9784 bool IsBinop = matchRdxBop(Inst, B0, B1); 9785 bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value())); 9786 if (IsBinop || IsSelect) { 9787 HorizontalReduction HorRdx; 9788 if (HorRdx.matchAssociativeReduction(P, Inst)) 9789 return HorRdx.tryToReduce(R, TTI); 9790 } 9791 return nullptr; 9792 }; 9793 while (!Stack.empty()) { 9794 Instruction *Inst; 9795 unsigned Level; 9796 std::tie(Inst, Level) = Stack.front(); 9797 Stack.pop(); 9798 // Do not try to analyze instruction that has already been vectorized. 9799 // This may happen when we vectorize instruction operands on a previous 9800 // iteration while stack was populated before that happened. 9801 if (R.isDeleted(Inst)) 9802 continue; 9803 Value *B0 = nullptr, *B1 = nullptr; 9804 if (Value *V = TryToReduce(Inst, B0, B1)) { 9805 Res = true; 9806 // Set P to nullptr to avoid re-analysis of phi node in 9807 // matchAssociativeReduction function unless this is the root node. 9808 P = nullptr; 9809 if (auto *I = dyn_cast<Instruction>(V)) { 9810 // Try to find another reduction. 9811 Stack.emplace(I, Level); 9812 continue; 9813 } 9814 } else { 9815 bool IsBinop = B0 && B1; 9816 if (P && IsBinop) { 9817 Inst = dyn_cast<Instruction>(B0); 9818 if (Inst == P) 9819 Inst = dyn_cast<Instruction>(B1); 9820 if (!Inst) { 9821 // Set P to nullptr to avoid re-analysis of phi node in 9822 // matchAssociativeReduction function unless this is the root node. 9823 P = nullptr; 9824 continue; 9825 } 9826 } 9827 // Set P to nullptr to avoid re-analysis of phi node in 9828 // matchAssociativeReduction function unless this is the root node. 9829 P = nullptr; 9830 // Do not try to vectorize CmpInst operands, this is done separately. 9831 // Final attempt for binop args vectorization should happen after the loop 9832 // to try to find reductions. 9833 if (!isa<CmpInst>(Inst)) 9834 PostponedInsts.push_back(Inst); 9835 } 9836 9837 // Try to vectorize operands. 9838 // Continue analysis for the instruction from the same basic block only to 9839 // save compile time. 9840 if (++Level < RecursionMaxDepth) 9841 for (auto *Op : Inst->operand_values()) 9842 if (VisitedInstrs.insert(Op).second) 9843 if (auto *I = dyn_cast<Instruction>(Op)) 9844 // Do not try to vectorize CmpInst operands, this is done 9845 // separately. 9846 if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) && 9847 I->getParent() == BB) 9848 Stack.emplace(I, Level); 9849 } 9850 // Try to vectorized binops where reductions were not found. 9851 for (Value *V : PostponedInsts) 9852 if (auto *Inst = dyn_cast<Instruction>(V)) 9853 if (!R.isDeleted(Inst)) 9854 Res |= Vectorize(Inst, R); 9855 return Res; 9856 } 9857 9858 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V, 9859 BasicBlock *BB, BoUpSLP &R, 9860 TargetTransformInfo *TTI) { 9861 auto *I = dyn_cast_or_null<Instruction>(V); 9862 if (!I) 9863 return false; 9864 9865 if (!isa<BinaryOperator>(I)) 9866 P = nullptr; 9867 // Try to match and vectorize a horizontal reduction. 9868 auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool { 9869 return tryToVectorize(I, R); 9870 }; 9871 return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, 9872 ExtraVectorization); 9873 } 9874 9875 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI, 9876 BasicBlock *BB, BoUpSLP &R) { 9877 const DataLayout &DL = BB->getModule()->getDataLayout(); 9878 if (!R.canMapToVector(IVI->getType(), DL)) 9879 return false; 9880 9881 SmallVector<Value *, 16> BuildVectorOpds; 9882 SmallVector<Value *, 16> BuildVectorInsts; 9883 if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts)) 9884 return false; 9885 9886 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n"); 9887 // Aggregate value is unlikely to be processed in vector register. 9888 return tryToVectorizeList(BuildVectorOpds, R); 9889 } 9890 9891 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI, 9892 BasicBlock *BB, BoUpSLP &R) { 9893 SmallVector<Value *, 16> BuildVectorInsts; 9894 SmallVector<Value *, 16> BuildVectorOpds; 9895 SmallVector<int> Mask; 9896 if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) || 9897 (llvm::all_of( 9898 BuildVectorOpds, 9899 [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) && 9900 isFixedVectorShuffle(BuildVectorOpds, Mask))) 9901 return false; 9902 9903 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n"); 9904 return tryToVectorizeList(BuildVectorInsts, R); 9905 } 9906 9907 template <typename T> 9908 static bool 9909 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming, 9910 function_ref<unsigned(T *)> Limit, 9911 function_ref<bool(T *, T *)> Comparator, 9912 function_ref<bool(T *, T *)> AreCompatible, 9913 function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper, 9914 bool LimitForRegisterSize) { 9915 bool Changed = false; 9916 // Sort by type, parent, operands. 9917 stable_sort(Incoming, Comparator); 9918 9919 // Try to vectorize elements base on their type. 9920 SmallVector<T *> Candidates; 9921 for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) { 9922 // Look for the next elements with the same type, parent and operand 9923 // kinds. 9924 auto *SameTypeIt = IncIt; 9925 while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt)) 9926 ++SameTypeIt; 9927 9928 // Try to vectorize them. 9929 unsigned NumElts = (SameTypeIt - IncIt); 9930 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes (" 9931 << NumElts << ")\n"); 9932 // The vectorization is a 3-state attempt: 9933 // 1. Try to vectorize instructions with the same/alternate opcodes with the 9934 // size of maximal register at first. 9935 // 2. Try to vectorize remaining instructions with the same type, if 9936 // possible. This may result in the better vectorization results rather than 9937 // if we try just to vectorize instructions with the same/alternate opcodes. 9938 // 3. Final attempt to try to vectorize all instructions with the 9939 // same/alternate ops only, this may result in some extra final 9940 // vectorization. 9941 if (NumElts > 1 && 9942 TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) { 9943 // Success start over because instructions might have been changed. 9944 Changed = true; 9945 } else if (NumElts < Limit(*IncIt) && 9946 (Candidates.empty() || 9947 Candidates.front()->getType() == (*IncIt)->getType())) { 9948 Candidates.append(IncIt, std::next(IncIt, NumElts)); 9949 } 9950 // Final attempt to vectorize instructions with the same types. 9951 if (Candidates.size() > 1 && 9952 (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) { 9953 if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) { 9954 // Success start over because instructions might have been changed. 9955 Changed = true; 9956 } else if (LimitForRegisterSize) { 9957 // Try to vectorize using small vectors. 9958 for (auto *It = Candidates.begin(), *End = Candidates.end(); 9959 It != End;) { 9960 auto *SameTypeIt = It; 9961 while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It)) 9962 ++SameTypeIt; 9963 unsigned NumElts = (SameTypeIt - It); 9964 if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts), 9965 /*LimitForRegisterSize=*/false)) 9966 Changed = true; 9967 It = SameTypeIt; 9968 } 9969 } 9970 Candidates.clear(); 9971 } 9972 9973 // Start over at the next instruction of a different type (or the end). 9974 IncIt = SameTypeIt; 9975 } 9976 return Changed; 9977 } 9978 9979 /// Compare two cmp instructions. If IsCompatibility is true, function returns 9980 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding 9981 /// operands. If IsCompatibility is false, function implements strict weak 9982 /// ordering relation between two cmp instructions, returning true if the first 9983 /// instruction is "less" than the second, i.e. its predicate is less than the 9984 /// predicate of the second or the operands IDs are less than the operands IDs 9985 /// of the second cmp instruction. 9986 template <bool IsCompatibility> 9987 static bool compareCmp(Value *V, Value *V2, 9988 function_ref<bool(Instruction *)> IsDeleted) { 9989 auto *CI1 = cast<CmpInst>(V); 9990 auto *CI2 = cast<CmpInst>(V2); 9991 if (IsDeleted(CI2) || !isValidElementType(CI2->getType())) 9992 return false; 9993 if (CI1->getOperand(0)->getType()->getTypeID() < 9994 CI2->getOperand(0)->getType()->getTypeID()) 9995 return !IsCompatibility; 9996 if (CI1->getOperand(0)->getType()->getTypeID() > 9997 CI2->getOperand(0)->getType()->getTypeID()) 9998 return false; 9999 CmpInst::Predicate Pred1 = CI1->getPredicate(); 10000 CmpInst::Predicate Pred2 = CI2->getPredicate(); 10001 CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1); 10002 CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2); 10003 CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1); 10004 CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2); 10005 if (BasePred1 < BasePred2) 10006 return !IsCompatibility; 10007 if (BasePred1 > BasePred2) 10008 return false; 10009 // Compare operands. 10010 bool LEPreds = Pred1 <= Pred2; 10011 bool GEPreds = Pred1 >= Pred2; 10012 for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) { 10013 auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1); 10014 auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1); 10015 if (Op1->getValueID() < Op2->getValueID()) 10016 return !IsCompatibility; 10017 if (Op1->getValueID() > Op2->getValueID()) 10018 return false; 10019 if (auto *I1 = dyn_cast<Instruction>(Op1)) 10020 if (auto *I2 = dyn_cast<Instruction>(Op2)) { 10021 if (I1->getParent() != I2->getParent()) 10022 return false; 10023 InstructionsState S = getSameOpcode({I1, I2}); 10024 if (S.getOpcode()) 10025 continue; 10026 return false; 10027 } 10028 } 10029 return IsCompatibility; 10030 } 10031 10032 bool SLPVectorizerPass::vectorizeSimpleInstructions( 10033 SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R, 10034 bool AtTerminator) { 10035 bool OpsChanged = false; 10036 SmallVector<Instruction *, 4> PostponedCmps; 10037 for (auto *I : reverse(Instructions)) { 10038 if (R.isDeleted(I)) 10039 continue; 10040 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) 10041 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R); 10042 else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) 10043 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R); 10044 else if (isa<CmpInst>(I)) 10045 PostponedCmps.push_back(I); 10046 } 10047 if (AtTerminator) { 10048 // Try to find reductions first. 10049 for (Instruction *I : PostponedCmps) { 10050 if (R.isDeleted(I)) 10051 continue; 10052 for (Value *Op : I->operands()) 10053 OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI); 10054 } 10055 // Try to vectorize operands as vector bundles. 10056 for (Instruction *I : PostponedCmps) { 10057 if (R.isDeleted(I)) 10058 continue; 10059 OpsChanged |= tryToVectorize(I, R); 10060 } 10061 // Try to vectorize list of compares. 10062 // Sort by type, compare predicate, etc. 10063 auto &&CompareSorter = [&R](Value *V, Value *V2) { 10064 return compareCmp<false>(V, V2, 10065 [&R](Instruction *I) { return R.isDeleted(I); }); 10066 }; 10067 10068 auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) { 10069 if (V1 == V2) 10070 return true; 10071 return compareCmp<true>(V1, V2, 10072 [&R](Instruction *I) { return R.isDeleted(I); }); 10073 }; 10074 auto Limit = [&R](Value *V) { 10075 unsigned EltSize = R.getVectorElementSize(V); 10076 return std::max(2U, R.getMaxVecRegSize() / EltSize); 10077 }; 10078 10079 SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end()); 10080 OpsChanged |= tryToVectorizeSequence<Value>( 10081 Vals, Limit, CompareSorter, AreCompatibleCompares, 10082 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 10083 // Exclude possible reductions from other blocks. 10084 bool ArePossiblyReducedInOtherBlock = 10085 any_of(Candidates, [](Value *V) { 10086 return any_of(V->users(), [V](User *U) { 10087 return isa<SelectInst>(U) && 10088 cast<SelectInst>(U)->getParent() != 10089 cast<Instruction>(V)->getParent(); 10090 }); 10091 }); 10092 if (ArePossiblyReducedInOtherBlock) 10093 return false; 10094 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 10095 }, 10096 /*LimitForRegisterSize=*/true); 10097 Instructions.clear(); 10098 } else { 10099 // Insert in reverse order since the PostponedCmps vector was filled in 10100 // reverse order. 10101 Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend()); 10102 } 10103 return OpsChanged; 10104 } 10105 10106 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { 10107 bool Changed = false; 10108 SmallVector<Value *, 4> Incoming; 10109 SmallPtrSet<Value *, 16> VisitedInstrs; 10110 // Maps phi nodes to the non-phi nodes found in the use tree for each phi 10111 // node. Allows better to identify the chains that can be vectorized in the 10112 // better way. 10113 DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes; 10114 auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) { 10115 assert(isValidElementType(V1->getType()) && 10116 isValidElementType(V2->getType()) && 10117 "Expected vectorizable types only."); 10118 // It is fine to compare type IDs here, since we expect only vectorizable 10119 // types, like ints, floats and pointers, we don't care about other type. 10120 if (V1->getType()->getTypeID() < V2->getType()->getTypeID()) 10121 return true; 10122 if (V1->getType()->getTypeID() > V2->getType()->getTypeID()) 10123 return false; 10124 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 10125 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 10126 if (Opcodes1.size() < Opcodes2.size()) 10127 return true; 10128 if (Opcodes1.size() > Opcodes2.size()) 10129 return false; 10130 Optional<bool> ConstOrder; 10131 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 10132 // Undefs are compatible with any other value. 10133 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) { 10134 if (!ConstOrder) 10135 ConstOrder = 10136 !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]); 10137 continue; 10138 } 10139 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 10140 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 10141 DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent()); 10142 DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent()); 10143 if (!NodeI1) 10144 return NodeI2 != nullptr; 10145 if (!NodeI2) 10146 return false; 10147 assert((NodeI1 == NodeI2) == 10148 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 10149 "Different nodes should have different DFS numbers"); 10150 if (NodeI1 != NodeI2) 10151 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 10152 InstructionsState S = getSameOpcode({I1, I2}); 10153 if (S.getOpcode()) 10154 continue; 10155 return I1->getOpcode() < I2->getOpcode(); 10156 } 10157 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) { 10158 if (!ConstOrder) 10159 ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID(); 10160 continue; 10161 } 10162 if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID()) 10163 return true; 10164 if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID()) 10165 return false; 10166 } 10167 return ConstOrder && *ConstOrder; 10168 }; 10169 auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) { 10170 if (V1 == V2) 10171 return true; 10172 if (V1->getType() != V2->getType()) 10173 return false; 10174 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 10175 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 10176 if (Opcodes1.size() != Opcodes2.size()) 10177 return false; 10178 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 10179 // Undefs are compatible with any other value. 10180 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) 10181 continue; 10182 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 10183 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 10184 if (I1->getParent() != I2->getParent()) 10185 return false; 10186 InstructionsState S = getSameOpcode({I1, I2}); 10187 if (S.getOpcode()) 10188 continue; 10189 return false; 10190 } 10191 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) 10192 continue; 10193 if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID()) 10194 return false; 10195 } 10196 return true; 10197 }; 10198 auto Limit = [&R](Value *V) { 10199 unsigned EltSize = R.getVectorElementSize(V); 10200 return std::max(2U, R.getMaxVecRegSize() / EltSize); 10201 }; 10202 10203 bool HaveVectorizedPhiNodes = false; 10204 do { 10205 // Collect the incoming values from the PHIs. 10206 Incoming.clear(); 10207 for (Instruction &I : *BB) { 10208 PHINode *P = dyn_cast<PHINode>(&I); 10209 if (!P) 10210 break; 10211 10212 // No need to analyze deleted, vectorized and non-vectorizable 10213 // instructions. 10214 if (!VisitedInstrs.count(P) && !R.isDeleted(P) && 10215 isValidElementType(P->getType())) 10216 Incoming.push_back(P); 10217 } 10218 10219 // Find the corresponding non-phi nodes for better matching when trying to 10220 // build the tree. 10221 for (Value *V : Incoming) { 10222 SmallVectorImpl<Value *> &Opcodes = 10223 PHIToOpcodes.try_emplace(V).first->getSecond(); 10224 if (!Opcodes.empty()) 10225 continue; 10226 SmallVector<Value *, 4> Nodes(1, V); 10227 SmallPtrSet<Value *, 4> Visited; 10228 while (!Nodes.empty()) { 10229 auto *PHI = cast<PHINode>(Nodes.pop_back_val()); 10230 if (!Visited.insert(PHI).second) 10231 continue; 10232 for (Value *V : PHI->incoming_values()) { 10233 if (auto *PHI1 = dyn_cast<PHINode>((V))) { 10234 Nodes.push_back(PHI1); 10235 continue; 10236 } 10237 Opcodes.emplace_back(V); 10238 } 10239 } 10240 } 10241 10242 HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>( 10243 Incoming, Limit, PHICompare, AreCompatiblePHIs, 10244 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 10245 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 10246 }, 10247 /*LimitForRegisterSize=*/true); 10248 Changed |= HaveVectorizedPhiNodes; 10249 VisitedInstrs.insert(Incoming.begin(), Incoming.end()); 10250 } while (HaveVectorizedPhiNodes); 10251 10252 VisitedInstrs.clear(); 10253 10254 SmallVector<Instruction *, 8> PostProcessInstructions; 10255 SmallDenseSet<Instruction *, 4> KeyNodes; 10256 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 10257 // Skip instructions with scalable type. The num of elements is unknown at 10258 // compile-time for scalable type. 10259 if (isa<ScalableVectorType>(it->getType())) 10260 continue; 10261 10262 // Skip instructions marked for the deletion. 10263 if (R.isDeleted(&*it)) 10264 continue; 10265 // We may go through BB multiple times so skip the one we have checked. 10266 if (!VisitedInstrs.insert(&*it).second) { 10267 if (it->use_empty() && KeyNodes.contains(&*it) && 10268 vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 10269 it->isTerminator())) { 10270 // We would like to start over since some instructions are deleted 10271 // and the iterator may become invalid value. 10272 Changed = true; 10273 it = BB->begin(); 10274 e = BB->end(); 10275 } 10276 continue; 10277 } 10278 10279 if (isa<DbgInfoIntrinsic>(it)) 10280 continue; 10281 10282 // Try to vectorize reductions that use PHINodes. 10283 if (PHINode *P = dyn_cast<PHINode>(it)) { 10284 // Check that the PHI is a reduction PHI. 10285 if (P->getNumIncomingValues() == 2) { 10286 // Try to match and vectorize a horizontal reduction. 10287 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R, 10288 TTI)) { 10289 Changed = true; 10290 it = BB->begin(); 10291 e = BB->end(); 10292 continue; 10293 } 10294 } 10295 // Try to vectorize the incoming values of the PHI, to catch reductions 10296 // that feed into PHIs. 10297 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) { 10298 // Skip if the incoming block is the current BB for now. Also, bypass 10299 // unreachable IR for efficiency and to avoid crashing. 10300 // TODO: Collect the skipped incoming values and try to vectorize them 10301 // after processing BB. 10302 if (BB == P->getIncomingBlock(I) || 10303 !DT->isReachableFromEntry(P->getIncomingBlock(I))) 10304 continue; 10305 10306 Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I), 10307 P->getIncomingBlock(I), R, TTI); 10308 } 10309 continue; 10310 } 10311 10312 // Ran into an instruction without users, like terminator, or function call 10313 // with ignored return value, store. Ignore unused instructions (basing on 10314 // instruction type, except for CallInst and InvokeInst). 10315 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) || 10316 isa<InvokeInst>(it))) { 10317 KeyNodes.insert(&*it); 10318 bool OpsChanged = false; 10319 if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) { 10320 for (auto *V : it->operand_values()) { 10321 // Try to match and vectorize a horizontal reduction. 10322 OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI); 10323 } 10324 } 10325 // Start vectorization of post-process list of instructions from the 10326 // top-tree instructions to try to vectorize as many instructions as 10327 // possible. 10328 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 10329 it->isTerminator()); 10330 if (OpsChanged) { 10331 // We would like to start over since some instructions are deleted 10332 // and the iterator may become invalid value. 10333 Changed = true; 10334 it = BB->begin(); 10335 e = BB->end(); 10336 continue; 10337 } 10338 } 10339 10340 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) || 10341 isa<InsertValueInst>(it)) 10342 PostProcessInstructions.push_back(&*it); 10343 } 10344 10345 return Changed; 10346 } 10347 10348 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) { 10349 auto Changed = false; 10350 for (auto &Entry : GEPs) { 10351 // If the getelementptr list has fewer than two elements, there's nothing 10352 // to do. 10353 if (Entry.second.size() < 2) 10354 continue; 10355 10356 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length " 10357 << Entry.second.size() << ".\n"); 10358 10359 // Process the GEP list in chunks suitable for the target's supported 10360 // vector size. If a vector register can't hold 1 element, we are done. We 10361 // are trying to vectorize the index computations, so the maximum number of 10362 // elements is based on the size of the index expression, rather than the 10363 // size of the GEP itself (the target's pointer size). 10364 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 10365 unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin()); 10366 if (MaxVecRegSize < EltSize) 10367 continue; 10368 10369 unsigned MaxElts = MaxVecRegSize / EltSize; 10370 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) { 10371 auto Len = std::min<unsigned>(BE - BI, MaxElts); 10372 ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len); 10373 10374 // Initialize a set a candidate getelementptrs. Note that we use a 10375 // SetVector here to preserve program order. If the index computations 10376 // are vectorizable and begin with loads, we want to minimize the chance 10377 // of having to reorder them later. 10378 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end()); 10379 10380 // Some of the candidates may have already been vectorized after we 10381 // initially collected them. If so, they are marked as deleted, so remove 10382 // them from the set of candidates. 10383 Candidates.remove_if( 10384 [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); }); 10385 10386 // Remove from the set of candidates all pairs of getelementptrs with 10387 // constant differences. Such getelementptrs are likely not good 10388 // candidates for vectorization in a bottom-up phase since one can be 10389 // computed from the other. We also ensure all candidate getelementptr 10390 // indices are unique. 10391 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) { 10392 auto *GEPI = GEPList[I]; 10393 if (!Candidates.count(GEPI)) 10394 continue; 10395 auto *SCEVI = SE->getSCEV(GEPList[I]); 10396 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) { 10397 auto *GEPJ = GEPList[J]; 10398 auto *SCEVJ = SE->getSCEV(GEPList[J]); 10399 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) { 10400 Candidates.remove(GEPI); 10401 Candidates.remove(GEPJ); 10402 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) { 10403 Candidates.remove(GEPJ); 10404 } 10405 } 10406 } 10407 10408 // We break out of the above computation as soon as we know there are 10409 // fewer than two candidates remaining. 10410 if (Candidates.size() < 2) 10411 continue; 10412 10413 // Add the single, non-constant index of each candidate to the bundle. We 10414 // ensured the indices met these constraints when we originally collected 10415 // the getelementptrs. 10416 SmallVector<Value *, 16> Bundle(Candidates.size()); 10417 auto BundleIndex = 0u; 10418 for (auto *V : Candidates) { 10419 auto *GEP = cast<GetElementPtrInst>(V); 10420 auto *GEPIdx = GEP->idx_begin()->get(); 10421 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)); 10422 Bundle[BundleIndex++] = GEPIdx; 10423 } 10424 10425 // Try and vectorize the indices. We are currently only interested in 10426 // gather-like cases of the form: 10427 // 10428 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ... 10429 // 10430 // where the loads of "a", the loads of "b", and the subtractions can be 10431 // performed in parallel. It's likely that detecting this pattern in a 10432 // bottom-up phase will be simpler and less costly than building a 10433 // full-blown top-down phase beginning at the consecutive loads. 10434 Changed |= tryToVectorizeList(Bundle, R); 10435 } 10436 } 10437 return Changed; 10438 } 10439 10440 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) { 10441 bool Changed = false; 10442 // Sort by type, base pointers and values operand. Value operands must be 10443 // compatible (have the same opcode, same parent), otherwise it is 10444 // definitely not profitable to try to vectorize them. 10445 auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) { 10446 if (V->getPointerOperandType()->getTypeID() < 10447 V2->getPointerOperandType()->getTypeID()) 10448 return true; 10449 if (V->getPointerOperandType()->getTypeID() > 10450 V2->getPointerOperandType()->getTypeID()) 10451 return false; 10452 // UndefValues are compatible with all other values. 10453 if (isa<UndefValue>(V->getValueOperand()) || 10454 isa<UndefValue>(V2->getValueOperand())) 10455 return false; 10456 if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand())) 10457 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 10458 DomTreeNodeBase<llvm::BasicBlock> *NodeI1 = 10459 DT->getNode(I1->getParent()); 10460 DomTreeNodeBase<llvm::BasicBlock> *NodeI2 = 10461 DT->getNode(I2->getParent()); 10462 assert(NodeI1 && "Should only process reachable instructions"); 10463 assert(NodeI1 && "Should only process reachable instructions"); 10464 assert((NodeI1 == NodeI2) == 10465 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 10466 "Different nodes should have different DFS numbers"); 10467 if (NodeI1 != NodeI2) 10468 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 10469 InstructionsState S = getSameOpcode({I1, I2}); 10470 if (S.getOpcode()) 10471 return false; 10472 return I1->getOpcode() < I2->getOpcode(); 10473 } 10474 if (isa<Constant>(V->getValueOperand()) && 10475 isa<Constant>(V2->getValueOperand())) 10476 return false; 10477 return V->getValueOperand()->getValueID() < 10478 V2->getValueOperand()->getValueID(); 10479 }; 10480 10481 auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) { 10482 if (V1 == V2) 10483 return true; 10484 if (V1->getPointerOperandType() != V2->getPointerOperandType()) 10485 return false; 10486 // Undefs are compatible with any other value. 10487 if (isa<UndefValue>(V1->getValueOperand()) || 10488 isa<UndefValue>(V2->getValueOperand())) 10489 return true; 10490 if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand())) 10491 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 10492 if (I1->getParent() != I2->getParent()) 10493 return false; 10494 InstructionsState S = getSameOpcode({I1, I2}); 10495 return S.getOpcode() > 0; 10496 } 10497 if (isa<Constant>(V1->getValueOperand()) && 10498 isa<Constant>(V2->getValueOperand())) 10499 return true; 10500 return V1->getValueOperand()->getValueID() == 10501 V2->getValueOperand()->getValueID(); 10502 }; 10503 auto Limit = [&R, this](StoreInst *SI) { 10504 unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType()); 10505 return R.getMinVF(EltSize); 10506 }; 10507 10508 // Attempt to sort and vectorize each of the store-groups. 10509 for (auto &Pair : Stores) { 10510 if (Pair.second.size() < 2) 10511 continue; 10512 10513 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " 10514 << Pair.second.size() << ".\n"); 10515 10516 if (!isValidElementType(Pair.second.front()->getValueOperand()->getType())) 10517 continue; 10518 10519 Changed |= tryToVectorizeSequence<StoreInst>( 10520 Pair.second, Limit, StoreSorter, AreCompatibleStores, 10521 [this, &R](ArrayRef<StoreInst *> Candidates, bool) { 10522 return vectorizeStores(Candidates, R); 10523 }, 10524 /*LimitForRegisterSize=*/false); 10525 } 10526 return Changed; 10527 } 10528 10529 char SLPVectorizer::ID = 0; 10530 10531 static const char lv_name[] = "SLP Vectorizer"; 10532 10533 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false) 10534 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 10535 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 10536 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10537 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 10538 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 10539 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) 10540 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 10541 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy) 10542 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) 10543 10544 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); } 10545