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() && 2475 "unexpected scheduled state"); 2476 for (const ScheduleData *BundleMember = this; BundleMember; 2477 BundleMember = BundleMember->NextInBundle) { 2478 assert(BundleMember->hasValidDependencies() && 2479 BundleMember->UnscheduledDeps == 0 && 2480 "unexpected scheduled state"); 2481 assert((BundleMember == this || !BundleMember->IsScheduled) && 2482 "only bundle is marked scheduled"); 2483 } 2484 } 2485 } 2486 2487 /// Returns true if the dependency information has been calculated. 2488 /// Note that depenendency validity can vary between instructions within 2489 /// a single bundle. 2490 bool hasValidDependencies() const { return Dependencies != InvalidDeps; } 2491 2492 /// Returns true for single instructions and for bundle representatives 2493 /// (= the head of a bundle). 2494 bool isSchedulingEntity() const { return FirstInBundle == this; } 2495 2496 /// Returns true if it represents an instruction bundle and not only a 2497 /// single instruction. 2498 bool isPartOfBundle() const { 2499 return NextInBundle != nullptr || FirstInBundle != this; 2500 } 2501 2502 /// Returns true if it is ready for scheduling, i.e. it has no more 2503 /// unscheduled depending instructions/bundles. 2504 bool isReady() const { 2505 assert(isSchedulingEntity() && 2506 "can't consider non-scheduling entity for ready list"); 2507 return unscheduledDepsInBundle() == 0 && !IsScheduled; 2508 } 2509 2510 /// Modifies the number of unscheduled dependencies for this instruction, 2511 /// and returns the number of remaining dependencies for the containing 2512 /// bundle. 2513 int incrementUnscheduledDeps(int Incr) { 2514 assert(hasValidDependencies() && 2515 "increment of unscheduled deps would be meaningless"); 2516 UnscheduledDeps += Incr; 2517 return FirstInBundle->unscheduledDepsInBundle(); 2518 } 2519 2520 /// Sets the number of unscheduled dependencies to the number of 2521 /// dependencies. 2522 void resetUnscheduledDeps() { 2523 UnscheduledDeps = Dependencies; 2524 } 2525 2526 /// Clears all dependency information. 2527 void clearDependencies() { 2528 Dependencies = InvalidDeps; 2529 resetUnscheduledDeps(); 2530 MemoryDependencies.clear(); 2531 } 2532 2533 int unscheduledDepsInBundle() const { 2534 assert(isSchedulingEntity() && "only meaningful on the bundle"); 2535 int Sum = 0; 2536 for (const ScheduleData *BundleMember = this; BundleMember; 2537 BundleMember = BundleMember->NextInBundle) { 2538 if (BundleMember->UnscheduledDeps == InvalidDeps) 2539 return InvalidDeps; 2540 Sum += BundleMember->UnscheduledDeps; 2541 } 2542 return Sum; 2543 } 2544 2545 void dump(raw_ostream &os) const { 2546 if (!isSchedulingEntity()) { 2547 os << "/ " << *Inst; 2548 } else if (NextInBundle) { 2549 os << '[' << *Inst; 2550 ScheduleData *SD = NextInBundle; 2551 while (SD) { 2552 os << ';' << *SD->Inst; 2553 SD = SD->NextInBundle; 2554 } 2555 os << ']'; 2556 } else { 2557 os << *Inst; 2558 } 2559 } 2560 2561 Instruction *Inst = nullptr; 2562 2563 /// Points to the head in an instruction bundle (and always to this for 2564 /// single instructions). 2565 ScheduleData *FirstInBundle = nullptr; 2566 2567 /// Single linked list of all instructions in a bundle. Null if it is a 2568 /// single instruction. 2569 ScheduleData *NextInBundle = nullptr; 2570 2571 /// Single linked list of all memory instructions (e.g. load, store, call) 2572 /// in the block - until the end of the scheduling region. 2573 ScheduleData *NextLoadStore = nullptr; 2574 2575 /// The dependent memory instructions. 2576 /// This list is derived on demand in calculateDependencies(). 2577 SmallVector<ScheduleData *, 4> MemoryDependencies; 2578 2579 /// This ScheduleData is in the current scheduling region if this matches 2580 /// the current SchedulingRegionID of BlockScheduling. 2581 int SchedulingRegionID = 0; 2582 2583 /// Used for getting a "good" final ordering of instructions. 2584 int SchedulingPriority = 0; 2585 2586 /// The number of dependencies. Constitutes of the number of users of the 2587 /// instruction plus the number of dependent memory instructions (if any). 2588 /// This value is calculated on demand. 2589 /// If InvalidDeps, the number of dependencies is not calculated yet. 2590 int Dependencies = InvalidDeps; 2591 2592 /// The number of dependencies minus the number of dependencies of scheduled 2593 /// instructions. As soon as this is zero, the instruction/bundle gets ready 2594 /// for scheduling. 2595 /// Note that this is negative as long as Dependencies is not calculated. 2596 int UnscheduledDeps = InvalidDeps; 2597 2598 /// True if this instruction is scheduled (or considered as scheduled in the 2599 /// dry-run). 2600 bool IsScheduled = false; 2601 2602 /// Opcode of the current instruction in the schedule data. 2603 Value *OpValue = nullptr; 2604 2605 /// The TreeEntry that this instruction corresponds to. 2606 TreeEntry *TE = nullptr; 2607 2608 /// The lane of this node in the TreeEntry. 2609 int Lane = -1; 2610 }; 2611 2612 #ifndef NDEBUG 2613 friend inline raw_ostream &operator<<(raw_ostream &os, 2614 const BoUpSLP::ScheduleData &SD) { 2615 SD.dump(os); 2616 return os; 2617 } 2618 #endif 2619 2620 friend struct GraphTraits<BoUpSLP *>; 2621 friend struct DOTGraphTraits<BoUpSLP *>; 2622 2623 /// Contains all scheduling data for a basic block. 2624 struct BlockScheduling { 2625 BlockScheduling(BasicBlock *BB) 2626 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {} 2627 2628 void clear() { 2629 ReadyInsts.clear(); 2630 ScheduleStart = nullptr; 2631 ScheduleEnd = nullptr; 2632 FirstLoadStoreInRegion = nullptr; 2633 LastLoadStoreInRegion = nullptr; 2634 2635 // Reduce the maximum schedule region size by the size of the 2636 // previous scheduling run. 2637 ScheduleRegionSizeLimit -= ScheduleRegionSize; 2638 if (ScheduleRegionSizeLimit < MinScheduleRegionSize) 2639 ScheduleRegionSizeLimit = MinScheduleRegionSize; 2640 ScheduleRegionSize = 0; 2641 2642 // Make a new scheduling region, i.e. all existing ScheduleData is not 2643 // in the new region yet. 2644 ++SchedulingRegionID; 2645 } 2646 2647 ScheduleData *getScheduleData(Value *V) { 2648 ScheduleData *SD = ScheduleDataMap[V]; 2649 if (SD && SD->SchedulingRegionID == SchedulingRegionID) 2650 return SD; 2651 return nullptr; 2652 } 2653 2654 ScheduleData *getScheduleData(Value *V, Value *Key) { 2655 if (V == Key) 2656 return getScheduleData(V); 2657 auto I = ExtraScheduleDataMap.find(V); 2658 if (I != ExtraScheduleDataMap.end()) { 2659 ScheduleData *SD = I->second[Key]; 2660 if (SD && SD->SchedulingRegionID == SchedulingRegionID) 2661 return SD; 2662 } 2663 return nullptr; 2664 } 2665 2666 bool isInSchedulingRegion(ScheduleData *SD) const { 2667 return SD->SchedulingRegionID == SchedulingRegionID; 2668 } 2669 2670 /// Marks an instruction as scheduled and puts all dependent ready 2671 /// instructions into the ready-list. 2672 template <typename ReadyListType> 2673 void schedule(ScheduleData *SD, ReadyListType &ReadyList) { 2674 SD->IsScheduled = true; 2675 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n"); 2676 2677 for (ScheduleData *BundleMember = SD; BundleMember; 2678 BundleMember = BundleMember->NextInBundle) { 2679 if (BundleMember->Inst != BundleMember->OpValue) 2680 continue; 2681 2682 // Handle the def-use chain dependencies. 2683 2684 // Decrement the unscheduled counter and insert to ready list if ready. 2685 auto &&DecrUnsched = [this, &ReadyList](Instruction *I) { 2686 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) { 2687 if (OpDef && OpDef->hasValidDependencies() && 2688 OpDef->incrementUnscheduledDeps(-1) == 0) { 2689 // There are no more unscheduled dependencies after 2690 // decrementing, so we can put the dependent instruction 2691 // into the ready list. 2692 ScheduleData *DepBundle = OpDef->FirstInBundle; 2693 assert(!DepBundle->IsScheduled && 2694 "already scheduled bundle gets ready"); 2695 ReadyList.insert(DepBundle); 2696 LLVM_DEBUG(dbgs() 2697 << "SLP: gets ready (def): " << *DepBundle << "\n"); 2698 } 2699 }); 2700 }; 2701 2702 // If BundleMember is a vector bundle, its operands may have been 2703 // reordered during buildTree(). We therefore need to get its operands 2704 // through the TreeEntry. 2705 if (TreeEntry *TE = BundleMember->TE) { 2706 int Lane = BundleMember->Lane; 2707 assert(Lane >= 0 && "Lane not set"); 2708 2709 // Since vectorization tree is being built recursively this assertion 2710 // ensures that the tree entry has all operands set before reaching 2711 // this code. Couple of exceptions known at the moment are extracts 2712 // where their second (immediate) operand is not added. Since 2713 // immediates do not affect scheduler behavior this is considered 2714 // okay. 2715 auto *In = TE->getMainOp(); 2716 assert(In && 2717 (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) || 2718 In->getNumOperands() == TE->getNumOperands()) && 2719 "Missed TreeEntry operands?"); 2720 (void)In; // fake use to avoid build failure when assertions disabled 2721 2722 for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands(); 2723 OpIdx != NumOperands; ++OpIdx) 2724 if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane])) 2725 DecrUnsched(I); 2726 } else { 2727 // If BundleMember is a stand-alone instruction, no operand reordering 2728 // has taken place, so we directly access its operands. 2729 for (Use &U : BundleMember->Inst->operands()) 2730 if (auto *I = dyn_cast<Instruction>(U.get())) 2731 DecrUnsched(I); 2732 } 2733 // Handle the memory dependencies. 2734 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) { 2735 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) { 2736 // There are no more unscheduled dependencies after decrementing, 2737 // so we can put the dependent instruction into the ready list. 2738 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle; 2739 assert(!DepBundle->IsScheduled && 2740 "already scheduled bundle gets ready"); 2741 ReadyList.insert(DepBundle); 2742 LLVM_DEBUG(dbgs() 2743 << "SLP: gets ready (mem): " << *DepBundle << "\n"); 2744 } 2745 } 2746 } 2747 } 2748 2749 /// Verify basic self consistency properties of the data structure. 2750 void verify() { 2751 if (!ScheduleStart) 2752 return; 2753 2754 assert(ScheduleStart->getParent() == ScheduleEnd->getParent() && 2755 ScheduleStart->comesBefore(ScheduleEnd) && 2756 "Not a valid scheduling region?"); 2757 2758 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 2759 auto *SD = getScheduleData(I); 2760 assert(SD && "primary scheduledata must exist in window"); 2761 assert(isInSchedulingRegion(SD) && 2762 "primary schedule data not in window?"); 2763 doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); }); 2764 } 2765 2766 for (auto *SD : ReadyInsts) { 2767 assert(SD->isSchedulingEntity() && SD->isReady() && 2768 "item in ready list not ready?"); 2769 } 2770 } 2771 2772 void doForAllOpcodes(Value *V, 2773 function_ref<void(ScheduleData *SD)> Action) { 2774 if (ScheduleData *SD = getScheduleData(V)) 2775 Action(SD); 2776 auto I = ExtraScheduleDataMap.find(V); 2777 if (I != ExtraScheduleDataMap.end()) 2778 for (auto &P : I->second) 2779 if (P.second->SchedulingRegionID == SchedulingRegionID) 2780 Action(P.second); 2781 } 2782 2783 /// Put all instructions into the ReadyList which are ready for scheduling. 2784 template <typename ReadyListType> 2785 void initialFillReadyList(ReadyListType &ReadyList) { 2786 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 2787 doForAllOpcodes(I, [&](ScheduleData *SD) { 2788 if (SD->isSchedulingEntity() && SD->isReady()) { 2789 ReadyList.insert(SD); 2790 LLVM_DEBUG(dbgs() 2791 << "SLP: initially in ready list: " << *SD << "\n"); 2792 } 2793 }); 2794 } 2795 } 2796 2797 /// Build a bundle from the ScheduleData nodes corresponding to the 2798 /// scalar instruction for each lane. 2799 ScheduleData *buildBundle(ArrayRef<Value *> VL); 2800 2801 /// Checks if a bundle of instructions can be scheduled, i.e. has no 2802 /// cyclic dependencies. This is only a dry-run, no instructions are 2803 /// actually moved at this stage. 2804 /// \returns the scheduling bundle. The returned Optional value is non-None 2805 /// if \p VL is allowed to be scheduled. 2806 Optional<ScheduleData *> 2807 tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 2808 const InstructionsState &S); 2809 2810 /// Un-bundles a group of instructions. 2811 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue); 2812 2813 /// Allocates schedule data chunk. 2814 ScheduleData *allocateScheduleDataChunks(); 2815 2816 /// Extends the scheduling region so that V is inside the region. 2817 /// \returns true if the region size is within the limit. 2818 bool extendSchedulingRegion(Value *V, const InstructionsState &S); 2819 2820 /// Initialize the ScheduleData structures for new instructions in the 2821 /// scheduling region. 2822 void initScheduleData(Instruction *FromI, Instruction *ToI, 2823 ScheduleData *PrevLoadStore, 2824 ScheduleData *NextLoadStore); 2825 2826 /// Updates the dependency information of a bundle and of all instructions/ 2827 /// bundles which depend on the original bundle. 2828 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList, 2829 BoUpSLP *SLP); 2830 2831 /// Sets all instruction in the scheduling region to un-scheduled. 2832 void resetSchedule(); 2833 2834 BasicBlock *BB; 2835 2836 /// Simple memory allocation for ScheduleData. 2837 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks; 2838 2839 /// The size of a ScheduleData array in ScheduleDataChunks. 2840 int ChunkSize; 2841 2842 /// The allocator position in the current chunk, which is the last entry 2843 /// of ScheduleDataChunks. 2844 int ChunkPos; 2845 2846 /// Attaches ScheduleData to Instruction. 2847 /// Note that the mapping survives during all vectorization iterations, i.e. 2848 /// ScheduleData structures are recycled. 2849 DenseMap<Value *, ScheduleData *> ScheduleDataMap; 2850 2851 /// Attaches ScheduleData to Instruction with the leading key. 2852 DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>> 2853 ExtraScheduleDataMap; 2854 2855 /// The ready-list for scheduling (only used for the dry-run). 2856 SetVector<ScheduleData *> ReadyInsts; 2857 2858 /// The first instruction of the scheduling region. 2859 Instruction *ScheduleStart = nullptr; 2860 2861 /// The first instruction _after_ the scheduling region. 2862 Instruction *ScheduleEnd = nullptr; 2863 2864 /// The first memory accessing instruction in the scheduling region 2865 /// (can be null). 2866 ScheduleData *FirstLoadStoreInRegion = nullptr; 2867 2868 /// The last memory accessing instruction in the scheduling region 2869 /// (can be null). 2870 ScheduleData *LastLoadStoreInRegion = nullptr; 2871 2872 /// The current size of the scheduling region. 2873 int ScheduleRegionSize = 0; 2874 2875 /// The maximum size allowed for the scheduling region. 2876 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget; 2877 2878 /// The ID of the scheduling region. For a new vectorization iteration this 2879 /// is incremented which "removes" all ScheduleData from the region. 2880 // Make sure that the initial SchedulingRegionID is greater than the 2881 // initial SchedulingRegionID in ScheduleData (which is 0). 2882 int SchedulingRegionID = 1; 2883 }; 2884 2885 /// Attaches the BlockScheduling structures to basic blocks. 2886 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules; 2887 2888 /// Performs the "real" scheduling. Done before vectorization is actually 2889 /// performed in a basic block. 2890 void scheduleBlock(BlockScheduling *BS); 2891 2892 /// List of users to ignore during scheduling and that don't need extracting. 2893 ArrayRef<Value *> UserIgnoreList; 2894 2895 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of 2896 /// sorted SmallVectors of unsigned. 2897 struct OrdersTypeDenseMapInfo { 2898 static OrdersType getEmptyKey() { 2899 OrdersType V; 2900 V.push_back(~1U); 2901 return V; 2902 } 2903 2904 static OrdersType getTombstoneKey() { 2905 OrdersType V; 2906 V.push_back(~2U); 2907 return V; 2908 } 2909 2910 static unsigned getHashValue(const OrdersType &V) { 2911 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 2912 } 2913 2914 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) { 2915 return LHS == RHS; 2916 } 2917 }; 2918 2919 // Analysis and block reference. 2920 Function *F; 2921 ScalarEvolution *SE; 2922 TargetTransformInfo *TTI; 2923 TargetLibraryInfo *TLI; 2924 AAResults *AA; 2925 LoopInfo *LI; 2926 DominatorTree *DT; 2927 AssumptionCache *AC; 2928 DemandedBits *DB; 2929 const DataLayout *DL; 2930 OptimizationRemarkEmitter *ORE; 2931 2932 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt. 2933 unsigned MinVecRegSize; // Set by cl::opt (default: 128). 2934 2935 /// Instruction builder to construct the vectorized tree. 2936 IRBuilder<> Builder; 2937 2938 /// A map of scalar integer values to the smallest bit width with which they 2939 /// can legally be represented. The values map to (width, signed) pairs, 2940 /// where "width" indicates the minimum bit width and "signed" is True if the 2941 /// value must be signed-extended, rather than zero-extended, back to its 2942 /// original width. 2943 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs; 2944 }; 2945 2946 } // end namespace slpvectorizer 2947 2948 template <> struct GraphTraits<BoUpSLP *> { 2949 using TreeEntry = BoUpSLP::TreeEntry; 2950 2951 /// NodeRef has to be a pointer per the GraphWriter. 2952 using NodeRef = TreeEntry *; 2953 2954 using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy; 2955 2956 /// Add the VectorizableTree to the index iterator to be able to return 2957 /// TreeEntry pointers. 2958 struct ChildIteratorType 2959 : public iterator_adaptor_base< 2960 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> { 2961 ContainerTy &VectorizableTree; 2962 2963 ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W, 2964 ContainerTy &VT) 2965 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {} 2966 2967 NodeRef operator*() { return I->UserTE; } 2968 }; 2969 2970 static NodeRef getEntryNode(BoUpSLP &R) { 2971 return R.VectorizableTree[0].get(); 2972 } 2973 2974 static ChildIteratorType child_begin(NodeRef N) { 2975 return {N->UserTreeIndices.begin(), N->Container}; 2976 } 2977 2978 static ChildIteratorType child_end(NodeRef N) { 2979 return {N->UserTreeIndices.end(), N->Container}; 2980 } 2981 2982 /// For the node iterator we just need to turn the TreeEntry iterator into a 2983 /// TreeEntry* iterator so that it dereferences to NodeRef. 2984 class nodes_iterator { 2985 using ItTy = ContainerTy::iterator; 2986 ItTy It; 2987 2988 public: 2989 nodes_iterator(const ItTy &It2) : It(It2) {} 2990 NodeRef operator*() { return It->get(); } 2991 nodes_iterator operator++() { 2992 ++It; 2993 return *this; 2994 } 2995 bool operator!=(const nodes_iterator &N2) const { return N2.It != It; } 2996 }; 2997 2998 static nodes_iterator nodes_begin(BoUpSLP *R) { 2999 return nodes_iterator(R->VectorizableTree.begin()); 3000 } 3001 3002 static nodes_iterator nodes_end(BoUpSLP *R) { 3003 return nodes_iterator(R->VectorizableTree.end()); 3004 } 3005 3006 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); } 3007 }; 3008 3009 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits { 3010 using TreeEntry = BoUpSLP::TreeEntry; 3011 3012 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 3013 3014 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) { 3015 std::string Str; 3016 raw_string_ostream OS(Str); 3017 if (isSplat(Entry->Scalars)) 3018 OS << "<splat> "; 3019 for (auto V : Entry->Scalars) { 3020 OS << *V; 3021 if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) { 3022 return EU.Scalar == V; 3023 })) 3024 OS << " <extract>"; 3025 OS << "\n"; 3026 } 3027 return Str; 3028 } 3029 3030 static std::string getNodeAttributes(const TreeEntry *Entry, 3031 const BoUpSLP *) { 3032 if (Entry->State == TreeEntry::NeedToGather) 3033 return "color=red"; 3034 return ""; 3035 } 3036 }; 3037 3038 } // end namespace llvm 3039 3040 BoUpSLP::~BoUpSLP() { 3041 for (const auto &Pair : DeletedInstructions) { 3042 // Replace operands of ignored instructions with Undefs in case if they were 3043 // marked for deletion. 3044 if (Pair.getSecond()) { 3045 Value *Undef = UndefValue::get(Pair.getFirst()->getType()); 3046 Pair.getFirst()->replaceAllUsesWith(Undef); 3047 } 3048 Pair.getFirst()->dropAllReferences(); 3049 } 3050 for (const auto &Pair : DeletedInstructions) { 3051 assert(Pair.getFirst()->use_empty() && 3052 "trying to erase instruction with users."); 3053 Pair.getFirst()->eraseFromParent(); 3054 } 3055 #ifdef EXPENSIVE_CHECKS 3056 // If we could guarantee that this call is not extremely slow, we could 3057 // remove the ifdef limitation (see PR47712). 3058 assert(!verifyFunction(*F, &dbgs())); 3059 #endif 3060 } 3061 3062 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) { 3063 for (auto *V : AV) { 3064 if (auto *I = dyn_cast<Instruction>(V)) 3065 eraseInstruction(I, /*ReplaceOpsWithUndef=*/true); 3066 }; 3067 } 3068 3069 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses 3070 /// contains original mask for the scalars reused in the node. Procedure 3071 /// transform this mask in accordance with the given \p Mask. 3072 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) { 3073 assert(!Mask.empty() && Reuses.size() == Mask.size() && 3074 "Expected non-empty mask."); 3075 SmallVector<int> Prev(Reuses.begin(), Reuses.end()); 3076 Prev.swap(Reuses); 3077 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 3078 if (Mask[I] != UndefMaskElem) 3079 Reuses[Mask[I]] = Prev[I]; 3080 } 3081 3082 /// Reorders the given \p Order according to the given \p Mask. \p Order - is 3083 /// the original order of the scalars. Procedure transforms the provided order 3084 /// in accordance with the given \p Mask. If the resulting \p Order is just an 3085 /// identity order, \p Order is cleared. 3086 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) { 3087 assert(!Mask.empty() && "Expected non-empty mask."); 3088 SmallVector<int> MaskOrder; 3089 if (Order.empty()) { 3090 MaskOrder.resize(Mask.size()); 3091 std::iota(MaskOrder.begin(), MaskOrder.end(), 0); 3092 } else { 3093 inversePermutation(Order, MaskOrder); 3094 } 3095 reorderReuses(MaskOrder, Mask); 3096 if (ShuffleVectorInst::isIdentityMask(MaskOrder)) { 3097 Order.clear(); 3098 return; 3099 } 3100 Order.assign(Mask.size(), Mask.size()); 3101 for (unsigned I = 0, E = Mask.size(); I < E; ++I) 3102 if (MaskOrder[I] != UndefMaskElem) 3103 Order[MaskOrder[I]] = I; 3104 fixupOrderingIndices(Order); 3105 } 3106 3107 Optional<BoUpSLP::OrdersType> 3108 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) { 3109 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only."); 3110 unsigned NumScalars = TE.Scalars.size(); 3111 OrdersType CurrentOrder(NumScalars, NumScalars); 3112 SmallVector<int> Positions; 3113 SmallBitVector UsedPositions(NumScalars); 3114 const TreeEntry *STE = nullptr; 3115 // Try to find all gathered scalars that are gets vectorized in other 3116 // vectorize node. Here we can have only one single tree vector node to 3117 // correctly identify order of the gathered scalars. 3118 for (unsigned I = 0; I < NumScalars; ++I) { 3119 Value *V = TE.Scalars[I]; 3120 if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V)) 3121 continue; 3122 if (const auto *LocalSTE = getTreeEntry(V)) { 3123 if (!STE) 3124 STE = LocalSTE; 3125 else if (STE != LocalSTE) 3126 // Take the order only from the single vector node. 3127 return None; 3128 unsigned Lane = 3129 std::distance(STE->Scalars.begin(), find(STE->Scalars, V)); 3130 if (Lane >= NumScalars) 3131 return None; 3132 if (CurrentOrder[Lane] != NumScalars) { 3133 if (Lane != I) 3134 continue; 3135 UsedPositions.reset(CurrentOrder[Lane]); 3136 } 3137 // The partial identity (where only some elements of the gather node are 3138 // in the identity order) is good. 3139 CurrentOrder[Lane] = I; 3140 UsedPositions.set(I); 3141 } 3142 } 3143 // Need to keep the order if we have a vector entry and at least 2 scalars or 3144 // the vectorized entry has just 2 scalars. 3145 if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) { 3146 auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) { 3147 for (unsigned I = 0; I < NumScalars; ++I) 3148 if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars) 3149 return false; 3150 return true; 3151 }; 3152 if (IsIdentityOrder(CurrentOrder)) { 3153 CurrentOrder.clear(); 3154 return CurrentOrder; 3155 } 3156 auto *It = CurrentOrder.begin(); 3157 for (unsigned I = 0; I < NumScalars;) { 3158 if (UsedPositions.test(I)) { 3159 ++I; 3160 continue; 3161 } 3162 if (*It == NumScalars) { 3163 *It = I; 3164 ++I; 3165 } 3166 ++It; 3167 } 3168 return CurrentOrder; 3169 } 3170 return None; 3171 } 3172 3173 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE, 3174 bool TopToBottom) { 3175 // No need to reorder if need to shuffle reuses, still need to shuffle the 3176 // node. 3177 if (!TE.ReuseShuffleIndices.empty()) 3178 return None; 3179 if (TE.State == TreeEntry::Vectorize && 3180 (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) || 3181 (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) && 3182 !TE.isAltShuffle()) 3183 return TE.ReorderIndices; 3184 if (TE.State == TreeEntry::NeedToGather) { 3185 // TODO: add analysis of other gather nodes with extractelement 3186 // instructions and other values/instructions, not only undefs. 3187 if (((TE.getOpcode() == Instruction::ExtractElement && 3188 !TE.isAltShuffle()) || 3189 (all_of(TE.Scalars, 3190 [](Value *V) { 3191 return isa<UndefValue, ExtractElementInst>(V); 3192 }) && 3193 any_of(TE.Scalars, 3194 [](Value *V) { return isa<ExtractElementInst>(V); }))) && 3195 all_of(TE.Scalars, 3196 [](Value *V) { 3197 auto *EE = dyn_cast<ExtractElementInst>(V); 3198 return !EE || isa<FixedVectorType>(EE->getVectorOperandType()); 3199 }) && 3200 allSameType(TE.Scalars)) { 3201 // Check that gather of extractelements can be represented as 3202 // just a shuffle of a single vector. 3203 OrdersType CurrentOrder; 3204 bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder); 3205 if (Reuse || !CurrentOrder.empty()) { 3206 if (!CurrentOrder.empty()) 3207 fixupOrderingIndices(CurrentOrder); 3208 return CurrentOrder; 3209 } 3210 } 3211 if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE)) 3212 return CurrentOrder; 3213 } 3214 return None; 3215 } 3216 3217 void BoUpSLP::reorderTopToBottom() { 3218 // Maps VF to the graph nodes. 3219 DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries; 3220 // ExtractElement gather nodes which can be vectorized and need to handle 3221 // their ordering. 3222 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3223 // Find all reorderable nodes with the given VF. 3224 // Currently the are vectorized stores,loads,extracts + some gathering of 3225 // extracts. 3226 for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders]( 3227 const std::unique_ptr<TreeEntry> &TE) { 3228 if (Optional<OrdersType> CurrentOrder = 3229 getReorderingData(*TE.get(), /*TopToBottom=*/true)) { 3230 // Do not include ordering for nodes used in the alt opcode vectorization, 3231 // better to reorder them during bottom-to-top stage. If follow the order 3232 // here, it causes reordering of the whole graph though actually it is 3233 // profitable just to reorder the subgraph that starts from the alternate 3234 // opcode vectorization node. Such nodes already end-up with the shuffle 3235 // instruction and it is just enough to change this shuffle rather than 3236 // rotate the scalars for the whole graph. 3237 unsigned Cnt = 0; 3238 const TreeEntry *UserTE = TE.get(); 3239 while (UserTE && Cnt < RecursionMaxDepth) { 3240 if (UserTE->UserTreeIndices.size() != 1) 3241 break; 3242 if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) { 3243 return EI.UserTE->State == TreeEntry::Vectorize && 3244 EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0; 3245 })) 3246 return; 3247 if (UserTE->UserTreeIndices.empty()) 3248 UserTE = nullptr; 3249 else 3250 UserTE = UserTE->UserTreeIndices.back().UserTE; 3251 ++Cnt; 3252 } 3253 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 3254 if (TE->State != TreeEntry::Vectorize) 3255 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3256 } 3257 }); 3258 3259 // Reorder the graph nodes according to their vectorization factor. 3260 for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1; 3261 VF /= 2) { 3262 auto It = VFToOrderedEntries.find(VF); 3263 if (It == VFToOrderedEntries.end()) 3264 continue; 3265 // Try to find the most profitable order. We just are looking for the most 3266 // used order and reorder scalar elements in the nodes according to this 3267 // mostly used order. 3268 ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef(); 3269 // All operands are reordered and used only in this node - propagate the 3270 // most used order to the user node. 3271 MapVector<OrdersType, unsigned, 3272 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3273 OrdersUses; 3274 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3275 for (const TreeEntry *OpTE : OrderedEntries) { 3276 // No need to reorder this nodes, still need to extend and to use shuffle, 3277 // just need to merge reordering shuffle and the reuse shuffle. 3278 if (!OpTE->ReuseShuffleIndices.empty()) 3279 continue; 3280 // Count number of orders uses. 3281 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3282 if (OpTE->State == TreeEntry::NeedToGather) 3283 return GathersToOrders.find(OpTE)->second; 3284 return OpTE->ReorderIndices; 3285 }(); 3286 // Stores actually store the mask, not the order, need to invert. 3287 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3288 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3289 SmallVector<int> Mask; 3290 inversePermutation(Order, Mask); 3291 unsigned E = Order.size(); 3292 OrdersType CurrentOrder(E, E); 3293 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3294 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3295 }); 3296 fixupOrderingIndices(CurrentOrder); 3297 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 3298 } else { 3299 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 3300 } 3301 } 3302 // Set order of the user node. 3303 if (OrdersUses.empty()) 3304 continue; 3305 // Choose the most used order. 3306 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3307 unsigned Cnt = OrdersUses.front().second; 3308 for (const auto &Pair : drop_begin(OrdersUses)) { 3309 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3310 BestOrder = Pair.first; 3311 Cnt = Pair.second; 3312 } 3313 } 3314 // Set order of the user node. 3315 if (BestOrder.empty()) 3316 continue; 3317 SmallVector<int> Mask; 3318 inversePermutation(BestOrder, Mask); 3319 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3320 unsigned E = BestOrder.size(); 3321 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3322 return I < E ? static_cast<int>(I) : UndefMaskElem; 3323 }); 3324 // Do an actual reordering, if profitable. 3325 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 3326 // Just do the reordering for the nodes with the given VF. 3327 if (TE->Scalars.size() != VF) { 3328 if (TE->ReuseShuffleIndices.size() == VF) { 3329 // Need to reorder the reuses masks of the operands with smaller VF to 3330 // be able to find the match between the graph nodes and scalar 3331 // operands of the given node during vectorization/cost estimation. 3332 assert(all_of(TE->UserTreeIndices, 3333 [VF, &TE](const EdgeInfo &EI) { 3334 return EI.UserTE->Scalars.size() == VF || 3335 EI.UserTE->Scalars.size() == 3336 TE->Scalars.size(); 3337 }) && 3338 "All users must be of VF size."); 3339 // Update ordering of the operands with the smaller VF than the given 3340 // one. 3341 reorderReuses(TE->ReuseShuffleIndices, Mask); 3342 } 3343 continue; 3344 } 3345 if (TE->State == TreeEntry::Vectorize && 3346 isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst, 3347 InsertElementInst>(TE->getMainOp()) && 3348 !TE->isAltShuffle()) { 3349 // Build correct orders for extract{element,value}, loads and 3350 // stores. 3351 reorderOrder(TE->ReorderIndices, Mask); 3352 if (isa<InsertElementInst, StoreInst>(TE->getMainOp())) 3353 TE->reorderOperands(Mask); 3354 } else { 3355 // Reorder the node and its operands. 3356 TE->reorderOperands(Mask); 3357 assert(TE->ReorderIndices.empty() && 3358 "Expected empty reorder sequence."); 3359 reorderScalars(TE->Scalars, Mask); 3360 } 3361 if (!TE->ReuseShuffleIndices.empty()) { 3362 // Apply reversed order to keep the original ordering of the reused 3363 // elements to avoid extra reorder indices shuffling. 3364 OrdersType CurrentOrder; 3365 reorderOrder(CurrentOrder, MaskOrder); 3366 SmallVector<int> NewReuses; 3367 inversePermutation(CurrentOrder, NewReuses); 3368 addMask(NewReuses, TE->ReuseShuffleIndices); 3369 TE->ReuseShuffleIndices.swap(NewReuses); 3370 } 3371 } 3372 } 3373 } 3374 3375 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) { 3376 SetVector<TreeEntry *> OrderedEntries; 3377 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3378 // Find all reorderable leaf nodes with the given VF. 3379 // Currently the are vectorized loads,extracts without alternate operands + 3380 // some gathering of extracts. 3381 SmallVector<TreeEntry *> NonVectorized; 3382 for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders, 3383 &NonVectorized]( 3384 const std::unique_ptr<TreeEntry> &TE) { 3385 if (TE->State != TreeEntry::Vectorize) 3386 NonVectorized.push_back(TE.get()); 3387 if (Optional<OrdersType> CurrentOrder = 3388 getReorderingData(*TE.get(), /*TopToBottom=*/false)) { 3389 OrderedEntries.insert(TE.get()); 3390 if (TE->State != TreeEntry::Vectorize) 3391 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3392 } 3393 }); 3394 3395 // Checks if the operands of the users are reordarable and have only single 3396 // use. 3397 auto &&CheckOperands = 3398 [this, &NonVectorized](const auto &Data, 3399 SmallVectorImpl<TreeEntry *> &GatherOps) { 3400 for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) { 3401 if (any_of(Data.second, 3402 [I](const std::pair<unsigned, TreeEntry *> &OpData) { 3403 return OpData.first == I && 3404 OpData.second->State == TreeEntry::Vectorize; 3405 })) 3406 continue; 3407 ArrayRef<Value *> VL = Data.first->getOperand(I); 3408 const TreeEntry *TE = nullptr; 3409 const auto *It = find_if(VL, [this, &TE](Value *V) { 3410 TE = getTreeEntry(V); 3411 return TE; 3412 }); 3413 if (It != VL.end() && TE->isSame(VL)) 3414 return false; 3415 TreeEntry *Gather = nullptr; 3416 if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) { 3417 assert(TE->State != TreeEntry::Vectorize && 3418 "Only non-vectorized nodes are expected."); 3419 if (TE->isSame(VL)) { 3420 Gather = TE; 3421 return true; 3422 } 3423 return false; 3424 }) > 1) 3425 return false; 3426 if (Gather) 3427 GatherOps.push_back(Gather); 3428 } 3429 return true; 3430 }; 3431 // 1. Propagate order to the graph nodes, which use only reordered nodes. 3432 // I.e., if the node has operands, that are reordered, try to make at least 3433 // one operand order in the natural order and reorder others + reorder the 3434 // user node itself. 3435 SmallPtrSet<const TreeEntry *, 4> Visited; 3436 while (!OrderedEntries.empty()) { 3437 // 1. Filter out only reordered nodes. 3438 // 2. If the entry has multiple uses - skip it and jump to the next node. 3439 MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users; 3440 SmallVector<TreeEntry *> Filtered; 3441 for (TreeEntry *TE : OrderedEntries) { 3442 if (!(TE->State == TreeEntry::Vectorize || 3443 (TE->State == TreeEntry::NeedToGather && 3444 GathersToOrders.count(TE))) || 3445 TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() || 3446 !all_of(drop_begin(TE->UserTreeIndices), 3447 [TE](const EdgeInfo &EI) { 3448 return EI.UserTE == TE->UserTreeIndices.front().UserTE; 3449 }) || 3450 !Visited.insert(TE).second) { 3451 Filtered.push_back(TE); 3452 continue; 3453 } 3454 // Build a map between user nodes and their operands order to speedup 3455 // search. The graph currently does not provide this dependency directly. 3456 for (EdgeInfo &EI : TE->UserTreeIndices) { 3457 TreeEntry *UserTE = EI.UserTE; 3458 auto It = Users.find(UserTE); 3459 if (It == Users.end()) 3460 It = Users.insert({UserTE, {}}).first; 3461 It->second.emplace_back(EI.EdgeIdx, TE); 3462 } 3463 } 3464 // Erase filtered entries. 3465 for_each(Filtered, 3466 [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); }); 3467 for (const auto &Data : Users) { 3468 // Check that operands are used only in the User node. 3469 SmallVector<TreeEntry *> GatherOps; 3470 if (!CheckOperands(Data, GatherOps)) { 3471 for_each(Data.second, 3472 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3473 OrderedEntries.remove(Op.second); 3474 }); 3475 continue; 3476 } 3477 // All operands are reordered and used only in this node - propagate the 3478 // most used order to the user node. 3479 MapVector<OrdersType, unsigned, 3480 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3481 OrdersUses; 3482 // Do the analysis for each tree entry only once, otherwise the order of 3483 // the same node my be considered several times, though might be not 3484 // profitable. 3485 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3486 for (const auto &Op : Data.second) { 3487 TreeEntry *OpTE = Op.second; 3488 if (!VisitedOps.insert(OpTE).second) 3489 continue; 3490 if (!OpTE->ReuseShuffleIndices.empty() || 3491 (IgnoreReorder && OpTE == VectorizableTree.front().get())) 3492 continue; 3493 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3494 if (OpTE->State == TreeEntry::NeedToGather) 3495 return GathersToOrders.find(OpTE)->second; 3496 return OpTE->ReorderIndices; 3497 }(); 3498 // Stores actually store the mask, not the order, need to invert. 3499 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3500 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3501 SmallVector<int> Mask; 3502 inversePermutation(Order, Mask); 3503 unsigned E = Order.size(); 3504 OrdersType CurrentOrder(E, E); 3505 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3506 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3507 }); 3508 fixupOrderingIndices(CurrentOrder); 3509 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 3510 } else { 3511 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 3512 } 3513 OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second += 3514 OpTE->UserTreeIndices.size(); 3515 assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0."); 3516 --OrdersUses[{}]; 3517 } 3518 // If no orders - skip current nodes and jump to the next one, if any. 3519 if (OrdersUses.empty()) { 3520 for_each(Data.second, 3521 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3522 OrderedEntries.remove(Op.second); 3523 }); 3524 continue; 3525 } 3526 // Choose the best order. 3527 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3528 unsigned Cnt = OrdersUses.front().second; 3529 for (const auto &Pair : drop_begin(OrdersUses)) { 3530 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3531 BestOrder = Pair.first; 3532 Cnt = Pair.second; 3533 } 3534 } 3535 // Set order of the user node (reordering of operands and user nodes). 3536 if (BestOrder.empty()) { 3537 for_each(Data.second, 3538 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3539 OrderedEntries.remove(Op.second); 3540 }); 3541 continue; 3542 } 3543 // Erase operands from OrderedEntries list and adjust their orders. 3544 VisitedOps.clear(); 3545 SmallVector<int> Mask; 3546 inversePermutation(BestOrder, Mask); 3547 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3548 unsigned E = BestOrder.size(); 3549 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3550 return I < E ? static_cast<int>(I) : UndefMaskElem; 3551 }); 3552 for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) { 3553 TreeEntry *TE = Op.second; 3554 OrderedEntries.remove(TE); 3555 if (!VisitedOps.insert(TE).second) 3556 continue; 3557 if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) { 3558 // Just reorder reuses indices. 3559 reorderReuses(TE->ReuseShuffleIndices, Mask); 3560 continue; 3561 } 3562 // Gathers are processed separately. 3563 if (TE->State != TreeEntry::Vectorize) 3564 continue; 3565 assert((BestOrder.size() == TE->ReorderIndices.size() || 3566 TE->ReorderIndices.empty()) && 3567 "Non-matching sizes of user/operand entries."); 3568 reorderOrder(TE->ReorderIndices, Mask); 3569 } 3570 // For gathers just need to reorder its scalars. 3571 for (TreeEntry *Gather : GatherOps) { 3572 assert(Gather->ReorderIndices.empty() && 3573 "Unexpected reordering of gathers."); 3574 if (!Gather->ReuseShuffleIndices.empty()) { 3575 // Just reorder reuses indices. 3576 reorderReuses(Gather->ReuseShuffleIndices, Mask); 3577 continue; 3578 } 3579 reorderScalars(Gather->Scalars, Mask); 3580 OrderedEntries.remove(Gather); 3581 } 3582 // Reorder operands of the user node and set the ordering for the user 3583 // node itself. 3584 if (Data.first->State != TreeEntry::Vectorize || 3585 !isa<ExtractElementInst, ExtractValueInst, LoadInst>( 3586 Data.first->getMainOp()) || 3587 Data.first->isAltShuffle()) 3588 Data.first->reorderOperands(Mask); 3589 if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) || 3590 Data.first->isAltShuffle()) { 3591 reorderScalars(Data.first->Scalars, Mask); 3592 reorderOrder(Data.first->ReorderIndices, MaskOrder); 3593 if (Data.first->ReuseShuffleIndices.empty() && 3594 !Data.first->ReorderIndices.empty() && 3595 !Data.first->isAltShuffle()) { 3596 // Insert user node to the list to try to sink reordering deeper in 3597 // the graph. 3598 OrderedEntries.insert(Data.first); 3599 } 3600 } else { 3601 reorderOrder(Data.first->ReorderIndices, Mask); 3602 } 3603 } 3604 } 3605 // If the reordering is unnecessary, just remove the reorder. 3606 if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() && 3607 VectorizableTree.front()->ReuseShuffleIndices.empty()) 3608 VectorizableTree.front()->ReorderIndices.clear(); 3609 } 3610 3611 void BoUpSLP::buildExternalUses( 3612 const ExtraValueToDebugLocsMap &ExternallyUsedValues) { 3613 // Collect the values that we need to extract from the tree. 3614 for (auto &TEPtr : VectorizableTree) { 3615 TreeEntry *Entry = TEPtr.get(); 3616 3617 // No need to handle users of gathered values. 3618 if (Entry->State == TreeEntry::NeedToGather) 3619 continue; 3620 3621 // For each lane: 3622 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 3623 Value *Scalar = Entry->Scalars[Lane]; 3624 int FoundLane = Entry->findLaneForValue(Scalar); 3625 3626 // Check if the scalar is externally used as an extra arg. 3627 auto ExtI = ExternallyUsedValues.find(Scalar); 3628 if (ExtI != ExternallyUsedValues.end()) { 3629 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " 3630 << Lane << " from " << *Scalar << ".\n"); 3631 ExternalUses.emplace_back(Scalar, nullptr, FoundLane); 3632 } 3633 for (User *U : Scalar->users()) { 3634 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n"); 3635 3636 Instruction *UserInst = dyn_cast<Instruction>(U); 3637 if (!UserInst) 3638 continue; 3639 3640 if (isDeleted(UserInst)) 3641 continue; 3642 3643 // Skip in-tree scalars that become vectors 3644 if (TreeEntry *UseEntry = getTreeEntry(U)) { 3645 Value *UseScalar = UseEntry->Scalars[0]; 3646 // Some in-tree scalars will remain as scalar in vectorized 3647 // instructions. If that is the case, the one in Lane 0 will 3648 // be used. 3649 if (UseScalar != U || 3650 UseEntry->State == TreeEntry::ScatterVectorize || 3651 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) { 3652 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U 3653 << ".\n"); 3654 assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state"); 3655 continue; 3656 } 3657 } 3658 3659 // Ignore users in the user ignore list. 3660 if (is_contained(UserIgnoreList, UserInst)) 3661 continue; 3662 3663 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " 3664 << Lane << " from " << *Scalar << ".\n"); 3665 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane)); 3666 } 3667 } 3668 } 3669 } 3670 3671 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, 3672 ArrayRef<Value *> UserIgnoreLst) { 3673 deleteTree(); 3674 UserIgnoreList = UserIgnoreLst; 3675 if (!allSameType(Roots)) 3676 return; 3677 buildTree_rec(Roots, 0, EdgeInfo()); 3678 } 3679 3680 namespace { 3681 /// Tracks the state we can represent the loads in the given sequence. 3682 enum class LoadsState { Gather, Vectorize, ScatterVectorize }; 3683 } // anonymous namespace 3684 3685 /// Checks if the given array of loads can be represented as a vectorized, 3686 /// scatter or just simple gather. 3687 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0, 3688 const TargetTransformInfo &TTI, 3689 const DataLayout &DL, ScalarEvolution &SE, 3690 SmallVectorImpl<unsigned> &Order, 3691 SmallVectorImpl<Value *> &PointerOps) { 3692 // Check that a vectorized load would load the same memory as a scalar 3693 // load. For example, we don't want to vectorize loads that are smaller 3694 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 3695 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 3696 // from such a struct, we read/write packed bits disagreeing with the 3697 // unvectorized version. 3698 Type *ScalarTy = VL0->getType(); 3699 3700 if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy)) 3701 return LoadsState::Gather; 3702 3703 // Make sure all loads in the bundle are simple - we can't vectorize 3704 // atomic or volatile loads. 3705 PointerOps.clear(); 3706 PointerOps.resize(VL.size()); 3707 auto *POIter = PointerOps.begin(); 3708 for (Value *V : VL) { 3709 auto *L = cast<LoadInst>(V); 3710 if (!L->isSimple()) 3711 return LoadsState::Gather; 3712 *POIter = L->getPointerOperand(); 3713 ++POIter; 3714 } 3715 3716 Order.clear(); 3717 // Check the order of pointer operands. 3718 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) { 3719 Value *Ptr0; 3720 Value *PtrN; 3721 if (Order.empty()) { 3722 Ptr0 = PointerOps.front(); 3723 PtrN = PointerOps.back(); 3724 } else { 3725 Ptr0 = PointerOps[Order.front()]; 3726 PtrN = PointerOps[Order.back()]; 3727 } 3728 Optional<int> Diff = 3729 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE); 3730 // Check that the sorted loads are consecutive. 3731 if (static_cast<unsigned>(*Diff) == VL.size() - 1) 3732 return LoadsState::Vectorize; 3733 Align CommonAlignment = cast<LoadInst>(VL0)->getAlign(); 3734 for (Value *V : VL) 3735 CommonAlignment = 3736 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 3737 if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()), 3738 CommonAlignment)) 3739 return LoadsState::ScatterVectorize; 3740 } 3741 3742 return LoadsState::Gather; 3743 } 3744 3745 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth, 3746 const EdgeInfo &UserTreeIdx) { 3747 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!"); 3748 3749 SmallVector<int> ReuseShuffleIndicies; 3750 SmallVector<Value *> UniqueValues; 3751 auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues, 3752 &UserTreeIdx, 3753 this](const InstructionsState &S) { 3754 // Check that every instruction appears once in this bundle. 3755 DenseMap<Value *, unsigned> UniquePositions; 3756 for (Value *V : VL) { 3757 if (isConstant(V)) { 3758 ReuseShuffleIndicies.emplace_back( 3759 isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size()); 3760 UniqueValues.emplace_back(V); 3761 continue; 3762 } 3763 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 3764 ReuseShuffleIndicies.emplace_back(Res.first->second); 3765 if (Res.second) 3766 UniqueValues.emplace_back(V); 3767 } 3768 size_t NumUniqueScalarValues = UniqueValues.size(); 3769 if (NumUniqueScalarValues == VL.size()) { 3770 ReuseShuffleIndicies.clear(); 3771 } else { 3772 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n"); 3773 if (NumUniqueScalarValues <= 1 || 3774 (UniquePositions.size() == 1 && all_of(UniqueValues, 3775 [](Value *V) { 3776 return isa<UndefValue>(V) || 3777 !isConstant(V); 3778 })) || 3779 !llvm::isPowerOf2_32(NumUniqueScalarValues)) { 3780 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); 3781 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3782 return false; 3783 } 3784 VL = UniqueValues; 3785 } 3786 return true; 3787 }; 3788 3789 InstructionsState S = getSameOpcode(VL); 3790 if (Depth == RecursionMaxDepth) { 3791 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); 3792 if (TryToFindDuplicates(S)) 3793 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3794 ReuseShuffleIndicies); 3795 return; 3796 } 3797 3798 // Don't handle scalable vectors 3799 if (S.getOpcode() == Instruction::ExtractElement && 3800 isa<ScalableVectorType>( 3801 cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) { 3802 LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n"); 3803 if (TryToFindDuplicates(S)) 3804 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3805 ReuseShuffleIndicies); 3806 return; 3807 } 3808 3809 // Don't handle vectors. 3810 if (S.OpValue->getType()->isVectorTy() && 3811 !isa<InsertElementInst>(S.OpValue)) { 3812 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); 3813 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3814 return; 3815 } 3816 3817 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue)) 3818 if (SI->getValueOperand()->getType()->isVectorTy()) { 3819 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); 3820 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3821 return; 3822 } 3823 3824 // If all of the operands are identical or constant we have a simple solution. 3825 // If we deal with insert/extract instructions, they all must have constant 3826 // indices, otherwise we should gather them, not try to vectorize. 3827 if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() || 3828 (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) && 3829 !all_of(VL, isVectorLikeInstWithConstOps))) { 3830 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n"); 3831 if (TryToFindDuplicates(S)) 3832 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3833 ReuseShuffleIndicies); 3834 return; 3835 } 3836 3837 // We now know that this is a vector of instructions of the same type from 3838 // the same block. 3839 3840 // Don't vectorize ephemeral values. 3841 for (Value *V : VL) { 3842 if (EphValues.count(V)) { 3843 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 3844 << ") is ephemeral.\n"); 3845 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3846 return; 3847 } 3848 } 3849 3850 // Check if this is a duplicate of another entry. 3851 if (TreeEntry *E = getTreeEntry(S.OpValue)) { 3852 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n"); 3853 if (!E->isSame(VL)) { 3854 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); 3855 if (TryToFindDuplicates(S)) 3856 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3857 ReuseShuffleIndicies); 3858 return; 3859 } 3860 // Record the reuse of the tree node. FIXME, currently this is only used to 3861 // properly draw the graph rather than for the actual vectorization. 3862 E->UserTreeIndices.push_back(UserTreeIdx); 3863 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue 3864 << ".\n"); 3865 return; 3866 } 3867 3868 // Check that none of the instructions in the bundle are already in the tree. 3869 for (Value *V : VL) { 3870 auto *I = dyn_cast<Instruction>(V); 3871 if (!I) 3872 continue; 3873 if (getTreeEntry(I)) { 3874 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 3875 << ") is already in tree.\n"); 3876 if (TryToFindDuplicates(S)) 3877 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3878 ReuseShuffleIndicies); 3879 return; 3880 } 3881 } 3882 3883 // The reduction nodes (stored in UserIgnoreList) also should stay scalar. 3884 for (Value *V : VL) { 3885 if (is_contained(UserIgnoreList, V)) { 3886 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n"); 3887 if (TryToFindDuplicates(S)) 3888 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3889 ReuseShuffleIndicies); 3890 return; 3891 } 3892 } 3893 3894 // Check that all of the users of the scalars that we want to vectorize are 3895 // schedulable. 3896 auto *VL0 = cast<Instruction>(S.OpValue); 3897 BasicBlock *BB = VL0->getParent(); 3898 3899 if (!DT->isReachableFromEntry(BB)) { 3900 // Don't go into unreachable blocks. They may contain instructions with 3901 // dependency cycles which confuse the final scheduling. 3902 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n"); 3903 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3904 return; 3905 } 3906 3907 // Check that every instruction appears once in this bundle. 3908 if (!TryToFindDuplicates(S)) 3909 return; 3910 3911 auto &BSRef = BlocksSchedules[BB]; 3912 if (!BSRef) 3913 BSRef = std::make_unique<BlockScheduling>(BB); 3914 3915 BlockScheduling &BS = *BSRef.get(); 3916 3917 Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S); 3918 #ifdef EXPENSIVE_CHECKS 3919 // Make sure we didn't break any internal invariants 3920 BS.verify(); 3921 #endif 3922 if (!Bundle) { 3923 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n"); 3924 assert((!BS.getScheduleData(VL0) || 3925 !BS.getScheduleData(VL0)->isPartOfBundle()) && 3926 "tryScheduleBundle should cancelScheduling on failure"); 3927 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3928 ReuseShuffleIndicies); 3929 return; 3930 } 3931 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); 3932 3933 unsigned ShuffleOrOp = S.isAltShuffle() ? 3934 (unsigned) Instruction::ShuffleVector : S.getOpcode(); 3935 switch (ShuffleOrOp) { 3936 case Instruction::PHI: { 3937 auto *PH = cast<PHINode>(VL0); 3938 3939 // Check for terminator values (e.g. invoke). 3940 for (Value *V : VL) 3941 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 3942 Instruction *Term = dyn_cast<Instruction>( 3943 cast<PHINode>(V)->getIncomingValueForBlock( 3944 PH->getIncomingBlock(I))); 3945 if (Term && Term->isTerminator()) { 3946 LLVM_DEBUG(dbgs() 3947 << "SLP: Need to swizzle PHINodes (terminator use).\n"); 3948 BS.cancelScheduling(VL, VL0); 3949 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 3950 ReuseShuffleIndicies); 3951 return; 3952 } 3953 } 3954 3955 TreeEntry *TE = 3956 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies); 3957 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); 3958 3959 // Keeps the reordered operands to avoid code duplication. 3960 SmallVector<ValueList, 2> OperandsVec; 3961 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 3962 if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) { 3963 ValueList Operands(VL.size(), PoisonValue::get(PH->getType())); 3964 TE->setOperand(I, Operands); 3965 OperandsVec.push_back(Operands); 3966 continue; 3967 } 3968 ValueList Operands; 3969 // Prepare the operand vector. 3970 for (Value *V : VL) 3971 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock( 3972 PH->getIncomingBlock(I))); 3973 TE->setOperand(I, Operands); 3974 OperandsVec.push_back(Operands); 3975 } 3976 for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx) 3977 buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx}); 3978 return; 3979 } 3980 case Instruction::ExtractValue: 3981 case Instruction::ExtractElement: { 3982 OrdersType CurrentOrder; 3983 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder); 3984 if (Reuse) { 3985 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n"); 3986 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 3987 ReuseShuffleIndicies); 3988 // This is a special case, as it does not gather, but at the same time 3989 // we are not extending buildTree_rec() towards the operands. 3990 ValueList Op0; 3991 Op0.assign(VL.size(), VL0->getOperand(0)); 3992 VectorizableTree.back()->setOperand(0, Op0); 3993 return; 3994 } 3995 if (!CurrentOrder.empty()) { 3996 LLVM_DEBUG({ 3997 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " 3998 "with order"; 3999 for (unsigned Idx : CurrentOrder) 4000 dbgs() << " " << Idx; 4001 dbgs() << "\n"; 4002 }); 4003 fixupOrderingIndices(CurrentOrder); 4004 // Insert new order with initial value 0, if it does not exist, 4005 // otherwise return the iterator to the existing one. 4006 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4007 ReuseShuffleIndicies, CurrentOrder); 4008 // This is a special case, as it does not gather, but at the same time 4009 // we are not extending buildTree_rec() towards the operands. 4010 ValueList Op0; 4011 Op0.assign(VL.size(), VL0->getOperand(0)); 4012 VectorizableTree.back()->setOperand(0, Op0); 4013 return; 4014 } 4015 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n"); 4016 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4017 ReuseShuffleIndicies); 4018 BS.cancelScheduling(VL, VL0); 4019 return; 4020 } 4021 case Instruction::InsertElement: { 4022 assert(ReuseShuffleIndicies.empty() && "All inserts should be unique"); 4023 4024 // Check that we have a buildvector and not a shuffle of 2 or more 4025 // different vectors. 4026 ValueSet SourceVectors; 4027 int MinIdx = std::numeric_limits<int>::max(); 4028 for (Value *V : VL) { 4029 SourceVectors.insert(cast<Instruction>(V)->getOperand(0)); 4030 Optional<int> Idx = *getInsertIndex(V, 0); 4031 if (!Idx || *Idx == UndefMaskElem) 4032 continue; 4033 MinIdx = std::min(MinIdx, *Idx); 4034 } 4035 4036 if (count_if(VL, [&SourceVectors](Value *V) { 4037 return !SourceVectors.contains(V); 4038 }) >= 2) { 4039 // Found 2nd source vector - cancel. 4040 LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with " 4041 "different source vectors.\n"); 4042 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4043 BS.cancelScheduling(VL, VL0); 4044 return; 4045 } 4046 4047 auto OrdCompare = [](const std::pair<int, int> &P1, 4048 const std::pair<int, int> &P2) { 4049 return P1.first > P2.first; 4050 }; 4051 PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>, 4052 decltype(OrdCompare)> 4053 Indices(OrdCompare); 4054 for (int I = 0, E = VL.size(); I < E; ++I) { 4055 Optional<int> Idx = *getInsertIndex(VL[I], 0); 4056 if (!Idx || *Idx == UndefMaskElem) 4057 continue; 4058 Indices.emplace(*Idx, I); 4059 } 4060 OrdersType CurrentOrder(VL.size(), VL.size()); 4061 bool IsIdentity = true; 4062 for (int I = 0, E = VL.size(); I < E; ++I) { 4063 CurrentOrder[Indices.top().second] = I; 4064 IsIdentity &= Indices.top().second == I; 4065 Indices.pop(); 4066 } 4067 if (IsIdentity) 4068 CurrentOrder.clear(); 4069 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4070 None, CurrentOrder); 4071 LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n"); 4072 4073 constexpr int NumOps = 2; 4074 ValueList VectorOperands[NumOps]; 4075 for (int I = 0; I < NumOps; ++I) { 4076 for (Value *V : VL) 4077 VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I)); 4078 4079 TE->setOperand(I, VectorOperands[I]); 4080 } 4081 buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1}); 4082 return; 4083 } 4084 case Instruction::Load: { 4085 // Check that a vectorized load would load the same memory as a scalar 4086 // load. For example, we don't want to vectorize loads that are smaller 4087 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 4088 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 4089 // from such a struct, we read/write packed bits disagreeing with the 4090 // unvectorized version. 4091 SmallVector<Value *> PointerOps; 4092 OrdersType CurrentOrder; 4093 TreeEntry *TE = nullptr; 4094 switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder, 4095 PointerOps)) { 4096 case LoadsState::Vectorize: 4097 if (CurrentOrder.empty()) { 4098 // Original loads are consecutive and does not require reordering. 4099 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4100 ReuseShuffleIndicies); 4101 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n"); 4102 } else { 4103 fixupOrderingIndices(CurrentOrder); 4104 // Need to reorder. 4105 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4106 ReuseShuffleIndicies, CurrentOrder); 4107 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n"); 4108 } 4109 TE->setOperandsInOrder(); 4110 break; 4111 case LoadsState::ScatterVectorize: 4112 // Vectorizing non-consecutive loads with `llvm.masked.gather`. 4113 TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S, 4114 UserTreeIdx, ReuseShuffleIndicies); 4115 TE->setOperandsInOrder(); 4116 buildTree_rec(PointerOps, Depth + 1, {TE, 0}); 4117 LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n"); 4118 break; 4119 case LoadsState::Gather: 4120 BS.cancelScheduling(VL, VL0); 4121 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4122 ReuseShuffleIndicies); 4123 #ifndef NDEBUG 4124 Type *ScalarTy = VL0->getType(); 4125 if (DL->getTypeSizeInBits(ScalarTy) != 4126 DL->getTypeAllocSizeInBits(ScalarTy)) 4127 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n"); 4128 else if (any_of(VL, [](Value *V) { 4129 return !cast<LoadInst>(V)->isSimple(); 4130 })) 4131 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n"); 4132 else 4133 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n"); 4134 #endif // NDEBUG 4135 break; 4136 } 4137 return; 4138 } 4139 case Instruction::ZExt: 4140 case Instruction::SExt: 4141 case Instruction::FPToUI: 4142 case Instruction::FPToSI: 4143 case Instruction::FPExt: 4144 case Instruction::PtrToInt: 4145 case Instruction::IntToPtr: 4146 case Instruction::SIToFP: 4147 case Instruction::UIToFP: 4148 case Instruction::Trunc: 4149 case Instruction::FPTrunc: 4150 case Instruction::BitCast: { 4151 Type *SrcTy = VL0->getOperand(0)->getType(); 4152 for (Value *V : VL) { 4153 Type *Ty = cast<Instruction>(V)->getOperand(0)->getType(); 4154 if (Ty != SrcTy || !isValidElementType(Ty)) { 4155 BS.cancelScheduling(VL, VL0); 4156 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4157 ReuseShuffleIndicies); 4158 LLVM_DEBUG(dbgs() 4159 << "SLP: Gathering casts with different src types.\n"); 4160 return; 4161 } 4162 } 4163 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4164 ReuseShuffleIndicies); 4165 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n"); 4166 4167 TE->setOperandsInOrder(); 4168 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4169 ValueList Operands; 4170 // Prepare the operand vector. 4171 for (Value *V : VL) 4172 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4173 4174 buildTree_rec(Operands, Depth + 1, {TE, i}); 4175 } 4176 return; 4177 } 4178 case Instruction::ICmp: 4179 case Instruction::FCmp: { 4180 // Check that all of the compares have the same predicate. 4181 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 4182 CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0); 4183 Type *ComparedTy = VL0->getOperand(0)->getType(); 4184 for (Value *V : VL) { 4185 CmpInst *Cmp = cast<CmpInst>(V); 4186 if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) || 4187 Cmp->getOperand(0)->getType() != ComparedTy) { 4188 BS.cancelScheduling(VL, VL0); 4189 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4190 ReuseShuffleIndicies); 4191 LLVM_DEBUG(dbgs() 4192 << "SLP: Gathering cmp with different predicate.\n"); 4193 return; 4194 } 4195 } 4196 4197 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4198 ReuseShuffleIndicies); 4199 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n"); 4200 4201 ValueList Left, Right; 4202 if (cast<CmpInst>(VL0)->isCommutative()) { 4203 // Commutative predicate - collect + sort operands of the instructions 4204 // so that each side is more likely to have the same opcode. 4205 assert(P0 == SwapP0 && "Commutative Predicate mismatch"); 4206 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4207 } else { 4208 // Collect operands - commute if it uses the swapped predicate. 4209 for (Value *V : VL) { 4210 auto *Cmp = cast<CmpInst>(V); 4211 Value *LHS = Cmp->getOperand(0); 4212 Value *RHS = Cmp->getOperand(1); 4213 if (Cmp->getPredicate() != P0) 4214 std::swap(LHS, RHS); 4215 Left.push_back(LHS); 4216 Right.push_back(RHS); 4217 } 4218 } 4219 TE->setOperand(0, Left); 4220 TE->setOperand(1, Right); 4221 buildTree_rec(Left, Depth + 1, {TE, 0}); 4222 buildTree_rec(Right, Depth + 1, {TE, 1}); 4223 return; 4224 } 4225 case Instruction::Select: 4226 case Instruction::FNeg: 4227 case Instruction::Add: 4228 case Instruction::FAdd: 4229 case Instruction::Sub: 4230 case Instruction::FSub: 4231 case Instruction::Mul: 4232 case Instruction::FMul: 4233 case Instruction::UDiv: 4234 case Instruction::SDiv: 4235 case Instruction::FDiv: 4236 case Instruction::URem: 4237 case Instruction::SRem: 4238 case Instruction::FRem: 4239 case Instruction::Shl: 4240 case Instruction::LShr: 4241 case Instruction::AShr: 4242 case Instruction::And: 4243 case Instruction::Or: 4244 case Instruction::Xor: { 4245 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4246 ReuseShuffleIndicies); 4247 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n"); 4248 4249 // Sort operands of the instructions so that each side is more likely to 4250 // have the same opcode. 4251 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) { 4252 ValueList Left, Right; 4253 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4254 TE->setOperand(0, Left); 4255 TE->setOperand(1, Right); 4256 buildTree_rec(Left, Depth + 1, {TE, 0}); 4257 buildTree_rec(Right, Depth + 1, {TE, 1}); 4258 return; 4259 } 4260 4261 TE->setOperandsInOrder(); 4262 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4263 ValueList Operands; 4264 // Prepare the operand vector. 4265 for (Value *V : VL) 4266 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4267 4268 buildTree_rec(Operands, Depth + 1, {TE, i}); 4269 } 4270 return; 4271 } 4272 case Instruction::GetElementPtr: { 4273 // We don't combine GEPs with complicated (nested) indexing. 4274 for (Value *V : VL) { 4275 if (cast<Instruction>(V)->getNumOperands() != 2) { 4276 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"); 4277 BS.cancelScheduling(VL, VL0); 4278 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4279 ReuseShuffleIndicies); 4280 return; 4281 } 4282 } 4283 4284 // We can't combine several GEPs into one vector if they operate on 4285 // different types. 4286 Type *Ty0 = VL0->getOperand(0)->getType(); 4287 for (Value *V : VL) { 4288 Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType(); 4289 if (Ty0 != CurTy) { 4290 LLVM_DEBUG(dbgs() 4291 << "SLP: not-vectorizable GEP (different types).\n"); 4292 BS.cancelScheduling(VL, VL0); 4293 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4294 ReuseShuffleIndicies); 4295 return; 4296 } 4297 } 4298 4299 // We don't combine GEPs with non-constant indexes. 4300 Type *Ty1 = VL0->getOperand(1)->getType(); 4301 for (Value *V : VL) { 4302 auto Op = cast<Instruction>(V)->getOperand(1); 4303 if (!isa<ConstantInt>(Op) || 4304 (Op->getType() != Ty1 && 4305 Op->getType()->getScalarSizeInBits() > 4306 DL->getIndexSizeInBits( 4307 V->getType()->getPointerAddressSpace()))) { 4308 LLVM_DEBUG(dbgs() 4309 << "SLP: not-vectorizable GEP (non-constant indexes).\n"); 4310 BS.cancelScheduling(VL, VL0); 4311 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4312 ReuseShuffleIndicies); 4313 return; 4314 } 4315 } 4316 4317 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4318 ReuseShuffleIndicies); 4319 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n"); 4320 SmallVector<ValueList, 2> Operands(2); 4321 // Prepare the operand vector for pointer operands. 4322 for (Value *V : VL) 4323 Operands.front().push_back( 4324 cast<GetElementPtrInst>(V)->getPointerOperand()); 4325 TE->setOperand(0, Operands.front()); 4326 // Need to cast all indices to the same type before vectorization to 4327 // avoid crash. 4328 // Required to be able to find correct matches between different gather 4329 // nodes and reuse the vectorized values rather than trying to gather them 4330 // again. 4331 int IndexIdx = 1; 4332 Type *VL0Ty = VL0->getOperand(IndexIdx)->getType(); 4333 Type *Ty = all_of(VL, 4334 [VL0Ty, IndexIdx](Value *V) { 4335 return VL0Ty == cast<GetElementPtrInst>(V) 4336 ->getOperand(IndexIdx) 4337 ->getType(); 4338 }) 4339 ? VL0Ty 4340 : DL->getIndexType(cast<GetElementPtrInst>(VL0) 4341 ->getPointerOperandType() 4342 ->getScalarType()); 4343 // Prepare the operand vector. 4344 for (Value *V : VL) { 4345 auto *Op = cast<Instruction>(V)->getOperand(IndexIdx); 4346 auto *CI = cast<ConstantInt>(Op); 4347 Operands.back().push_back(ConstantExpr::getIntegerCast( 4348 CI, Ty, CI->getValue().isSignBitSet())); 4349 } 4350 TE->setOperand(IndexIdx, Operands.back()); 4351 4352 for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I) 4353 buildTree_rec(Operands[I], Depth + 1, {TE, I}); 4354 return; 4355 } 4356 case Instruction::Store: { 4357 // Check if the stores are consecutive or if we need to swizzle them. 4358 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType(); 4359 // Avoid types that are padded when being allocated as scalars, while 4360 // being packed together in a vector (such as i1). 4361 if (DL->getTypeSizeInBits(ScalarTy) != 4362 DL->getTypeAllocSizeInBits(ScalarTy)) { 4363 BS.cancelScheduling(VL, VL0); 4364 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4365 ReuseShuffleIndicies); 4366 LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n"); 4367 return; 4368 } 4369 // Make sure all stores in the bundle are simple - we can't vectorize 4370 // atomic or volatile stores. 4371 SmallVector<Value *, 4> PointerOps(VL.size()); 4372 ValueList Operands(VL.size()); 4373 auto POIter = PointerOps.begin(); 4374 auto OIter = Operands.begin(); 4375 for (Value *V : VL) { 4376 auto *SI = cast<StoreInst>(V); 4377 if (!SI->isSimple()) { 4378 BS.cancelScheduling(VL, VL0); 4379 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4380 ReuseShuffleIndicies); 4381 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n"); 4382 return; 4383 } 4384 *POIter = SI->getPointerOperand(); 4385 *OIter = SI->getValueOperand(); 4386 ++POIter; 4387 ++OIter; 4388 } 4389 4390 OrdersType CurrentOrder; 4391 // Check the order of pointer operands. 4392 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) { 4393 Value *Ptr0; 4394 Value *PtrN; 4395 if (CurrentOrder.empty()) { 4396 Ptr0 = PointerOps.front(); 4397 PtrN = PointerOps.back(); 4398 } else { 4399 Ptr0 = PointerOps[CurrentOrder.front()]; 4400 PtrN = PointerOps[CurrentOrder.back()]; 4401 } 4402 Optional<int> Dist = 4403 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE); 4404 // Check that the sorted pointer operands are consecutive. 4405 if (static_cast<unsigned>(*Dist) == VL.size() - 1) { 4406 if (CurrentOrder.empty()) { 4407 // Original stores are consecutive and does not require reordering. 4408 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, 4409 UserTreeIdx, ReuseShuffleIndicies); 4410 TE->setOperandsInOrder(); 4411 buildTree_rec(Operands, Depth + 1, {TE, 0}); 4412 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n"); 4413 } else { 4414 fixupOrderingIndices(CurrentOrder); 4415 TreeEntry *TE = 4416 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4417 ReuseShuffleIndicies, CurrentOrder); 4418 TE->setOperandsInOrder(); 4419 buildTree_rec(Operands, Depth + 1, {TE, 0}); 4420 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n"); 4421 } 4422 return; 4423 } 4424 } 4425 4426 BS.cancelScheduling(VL, VL0); 4427 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4428 ReuseShuffleIndicies); 4429 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n"); 4430 return; 4431 } 4432 case Instruction::Call: { 4433 // Check if the calls are all to the same vectorizable intrinsic or 4434 // library function. 4435 CallInst *CI = cast<CallInst>(VL0); 4436 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4437 4438 VFShape Shape = VFShape::get( 4439 *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())), 4440 false /*HasGlobalPred*/); 4441 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 4442 4443 if (!VecFunc && !isTriviallyVectorizable(ID)) { 4444 BS.cancelScheduling(VL, VL0); 4445 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4446 ReuseShuffleIndicies); 4447 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n"); 4448 return; 4449 } 4450 Function *F = CI->getCalledFunction(); 4451 unsigned NumArgs = CI->arg_size(); 4452 SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr); 4453 for (unsigned j = 0; j != NumArgs; ++j) 4454 if (hasVectorInstrinsicScalarOpd(ID, j)) 4455 ScalarArgs[j] = CI->getArgOperand(j); 4456 for (Value *V : VL) { 4457 CallInst *CI2 = dyn_cast<CallInst>(V); 4458 if (!CI2 || CI2->getCalledFunction() != F || 4459 getVectorIntrinsicIDForCall(CI2, TLI) != ID || 4460 (VecFunc && 4461 VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) || 4462 !CI->hasIdenticalOperandBundleSchema(*CI2)) { 4463 BS.cancelScheduling(VL, VL0); 4464 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4465 ReuseShuffleIndicies); 4466 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V 4467 << "\n"); 4468 return; 4469 } 4470 // Some intrinsics have scalar arguments and should be same in order for 4471 // them to be vectorized. 4472 for (unsigned j = 0; j != NumArgs; ++j) { 4473 if (hasVectorInstrinsicScalarOpd(ID, j)) { 4474 Value *A1J = CI2->getArgOperand(j); 4475 if (ScalarArgs[j] != A1J) { 4476 BS.cancelScheduling(VL, VL0); 4477 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4478 ReuseShuffleIndicies); 4479 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI 4480 << " argument " << ScalarArgs[j] << "!=" << A1J 4481 << "\n"); 4482 return; 4483 } 4484 } 4485 } 4486 // Verify that the bundle operands are identical between the two calls. 4487 if (CI->hasOperandBundles() && 4488 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(), 4489 CI->op_begin() + CI->getBundleOperandsEndIndex(), 4490 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) { 4491 BS.cancelScheduling(VL, VL0); 4492 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4493 ReuseShuffleIndicies); 4494 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" 4495 << *CI << "!=" << *V << '\n'); 4496 return; 4497 } 4498 } 4499 4500 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4501 ReuseShuffleIndicies); 4502 TE->setOperandsInOrder(); 4503 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 4504 // For scalar operands no need to to create an entry since no need to 4505 // vectorize it. 4506 if (hasVectorInstrinsicScalarOpd(ID, i)) 4507 continue; 4508 ValueList Operands; 4509 // Prepare the operand vector. 4510 for (Value *V : VL) { 4511 auto *CI2 = cast<CallInst>(V); 4512 Operands.push_back(CI2->getArgOperand(i)); 4513 } 4514 buildTree_rec(Operands, Depth + 1, {TE, i}); 4515 } 4516 return; 4517 } 4518 case Instruction::ShuffleVector: { 4519 // If this is not an alternate sequence of opcode like add-sub 4520 // then do not vectorize this instruction. 4521 if (!S.isAltShuffle()) { 4522 BS.cancelScheduling(VL, VL0); 4523 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4524 ReuseShuffleIndicies); 4525 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n"); 4526 return; 4527 } 4528 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4529 ReuseShuffleIndicies); 4530 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n"); 4531 4532 // Reorder operands if reordering would enable vectorization. 4533 auto *CI = dyn_cast<CmpInst>(VL0); 4534 if (isa<BinaryOperator>(VL0) || CI) { 4535 ValueList Left, Right; 4536 if (!CI || all_of(VL, [](Value *V) { 4537 return cast<CmpInst>(V)->isCommutative(); 4538 })) { 4539 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4540 } else { 4541 CmpInst::Predicate P0 = CI->getPredicate(); 4542 CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate(); 4543 assert(P0 != AltP0 && 4544 "Expected different main/alternate predicates."); 4545 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 4546 Value *BaseOp0 = VL0->getOperand(0); 4547 Value *BaseOp1 = VL0->getOperand(1); 4548 // Collect operands - commute if it uses the swapped predicate or 4549 // alternate operation. 4550 for (Value *V : VL) { 4551 auto *Cmp = cast<CmpInst>(V); 4552 Value *LHS = Cmp->getOperand(0); 4553 Value *RHS = Cmp->getOperand(1); 4554 CmpInst::Predicate CurrentPred = Cmp->getPredicate(); 4555 if (P0 == AltP0Swapped) { 4556 if ((P0 == CurrentPred && 4557 !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) || 4558 (AltP0 == CurrentPred && 4559 areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))) 4560 std::swap(LHS, RHS); 4561 } else if (P0 != CurrentPred && AltP0 != CurrentPred) { 4562 std::swap(LHS, RHS); 4563 } 4564 Left.push_back(LHS); 4565 Right.push_back(RHS); 4566 } 4567 } 4568 TE->setOperand(0, Left); 4569 TE->setOperand(1, Right); 4570 buildTree_rec(Left, Depth + 1, {TE, 0}); 4571 buildTree_rec(Right, Depth + 1, {TE, 1}); 4572 return; 4573 } 4574 4575 TE->setOperandsInOrder(); 4576 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4577 ValueList Operands; 4578 // Prepare the operand vector. 4579 for (Value *V : VL) 4580 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4581 4582 buildTree_rec(Operands, Depth + 1, {TE, i}); 4583 } 4584 return; 4585 } 4586 default: 4587 BS.cancelScheduling(VL, VL0); 4588 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4589 ReuseShuffleIndicies); 4590 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); 4591 return; 4592 } 4593 } 4594 4595 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const { 4596 unsigned N = 1; 4597 Type *EltTy = T; 4598 4599 while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) || 4600 isa<VectorType>(EltTy)) { 4601 if (auto *ST = dyn_cast<StructType>(EltTy)) { 4602 // Check that struct is homogeneous. 4603 for (const auto *Ty : ST->elements()) 4604 if (Ty != *ST->element_begin()) 4605 return 0; 4606 N *= ST->getNumElements(); 4607 EltTy = *ST->element_begin(); 4608 } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) { 4609 N *= AT->getNumElements(); 4610 EltTy = AT->getElementType(); 4611 } else { 4612 auto *VT = cast<FixedVectorType>(EltTy); 4613 N *= VT->getNumElements(); 4614 EltTy = VT->getElementType(); 4615 } 4616 } 4617 4618 if (!isValidElementType(EltTy)) 4619 return 0; 4620 uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N)); 4621 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T)) 4622 return 0; 4623 return N; 4624 } 4625 4626 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 4627 SmallVectorImpl<unsigned> &CurrentOrder) const { 4628 const auto *It = find_if(VL, [](Value *V) { 4629 return isa<ExtractElementInst, ExtractValueInst>(V); 4630 }); 4631 assert(It != VL.end() && "Expected at least one extract instruction."); 4632 auto *E0 = cast<Instruction>(*It); 4633 assert(all_of(VL, 4634 [](Value *V) { 4635 return isa<UndefValue, ExtractElementInst, ExtractValueInst>( 4636 V); 4637 }) && 4638 "Invalid opcode"); 4639 // Check if all of the extracts come from the same vector and from the 4640 // correct offset. 4641 Value *Vec = E0->getOperand(0); 4642 4643 CurrentOrder.clear(); 4644 4645 // We have to extract from a vector/aggregate with the same number of elements. 4646 unsigned NElts; 4647 if (E0->getOpcode() == Instruction::ExtractValue) { 4648 const DataLayout &DL = E0->getModule()->getDataLayout(); 4649 NElts = canMapToVector(Vec->getType(), DL); 4650 if (!NElts) 4651 return false; 4652 // Check if load can be rewritten as load of vector. 4653 LoadInst *LI = dyn_cast<LoadInst>(Vec); 4654 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size())) 4655 return false; 4656 } else { 4657 NElts = cast<FixedVectorType>(Vec->getType())->getNumElements(); 4658 } 4659 4660 if (NElts != VL.size()) 4661 return false; 4662 4663 // Check that all of the indices extract from the correct offset. 4664 bool ShouldKeepOrder = true; 4665 unsigned E = VL.size(); 4666 // Assign to all items the initial value E + 1 so we can check if the extract 4667 // instruction index was used already. 4668 // Also, later we can check that all the indices are used and we have a 4669 // consecutive access in the extract instructions, by checking that no 4670 // element of CurrentOrder still has value E + 1. 4671 CurrentOrder.assign(E, E); 4672 unsigned I = 0; 4673 for (; I < E; ++I) { 4674 auto *Inst = dyn_cast<Instruction>(VL[I]); 4675 if (!Inst) 4676 continue; 4677 if (Inst->getOperand(0) != Vec) 4678 break; 4679 if (auto *EE = dyn_cast<ExtractElementInst>(Inst)) 4680 if (isa<UndefValue>(EE->getIndexOperand())) 4681 continue; 4682 Optional<unsigned> Idx = getExtractIndex(Inst); 4683 if (!Idx) 4684 break; 4685 const unsigned ExtIdx = *Idx; 4686 if (ExtIdx != I) { 4687 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E) 4688 break; 4689 ShouldKeepOrder = false; 4690 CurrentOrder[ExtIdx] = I; 4691 } else { 4692 if (CurrentOrder[I] != E) 4693 break; 4694 CurrentOrder[I] = I; 4695 } 4696 } 4697 if (I < E) { 4698 CurrentOrder.clear(); 4699 return false; 4700 } 4701 if (ShouldKeepOrder) 4702 CurrentOrder.clear(); 4703 4704 return ShouldKeepOrder; 4705 } 4706 4707 bool BoUpSLP::areAllUsersVectorized(Instruction *I, 4708 ArrayRef<Value *> VectorizedVals) const { 4709 return (I->hasOneUse() && is_contained(VectorizedVals, I)) || 4710 all_of(I->users(), [this](User *U) { 4711 return ScalarToTreeEntry.count(U) > 0 || 4712 isVectorLikeInstWithConstOps(U) || 4713 (isa<ExtractElementInst>(U) && MustGather.contains(U)); 4714 }); 4715 } 4716 4717 static std::pair<InstructionCost, InstructionCost> 4718 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy, 4719 TargetTransformInfo *TTI, TargetLibraryInfo *TLI) { 4720 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4721 4722 // Calculate the cost of the scalar and vector calls. 4723 SmallVector<Type *, 4> VecTys; 4724 for (Use &Arg : CI->args()) 4725 VecTys.push_back( 4726 FixedVectorType::get(Arg->getType(), VecTy->getNumElements())); 4727 FastMathFlags FMF; 4728 if (auto *FPCI = dyn_cast<FPMathOperator>(CI)) 4729 FMF = FPCI->getFastMathFlags(); 4730 SmallVector<const Value *> Arguments(CI->args()); 4731 IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF, 4732 dyn_cast<IntrinsicInst>(CI)); 4733 auto IntrinsicCost = 4734 TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput); 4735 4736 auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 4737 VecTy->getNumElements())), 4738 false /*HasGlobalPred*/); 4739 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 4740 auto LibCost = IntrinsicCost; 4741 if (!CI->isNoBuiltin() && VecFunc) { 4742 // Calculate the cost of the vector library call. 4743 // If the corresponding vector call is cheaper, return its cost. 4744 LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys, 4745 TTI::TCK_RecipThroughput); 4746 } 4747 return {IntrinsicCost, LibCost}; 4748 } 4749 4750 /// Compute the cost of creating a vector of type \p VecTy containing the 4751 /// extracted values from \p VL. 4752 static InstructionCost 4753 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy, 4754 TargetTransformInfo::ShuffleKind ShuffleKind, 4755 ArrayRef<int> Mask, TargetTransformInfo &TTI) { 4756 unsigned NumOfParts = TTI.getNumberOfParts(VecTy); 4757 4758 if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts || 4759 VecTy->getNumElements() < NumOfParts) 4760 return TTI.getShuffleCost(ShuffleKind, VecTy, Mask); 4761 4762 bool AllConsecutive = true; 4763 unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts; 4764 unsigned Idx = -1; 4765 InstructionCost Cost = 0; 4766 4767 // Process extracts in blocks of EltsPerVector to check if the source vector 4768 // operand can be re-used directly. If not, add the cost of creating a shuffle 4769 // to extract the values into a vector register. 4770 for (auto *V : VL) { 4771 ++Idx; 4772 4773 // Need to exclude undefs from analysis. 4774 if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem) 4775 continue; 4776 4777 // Reached the start of a new vector registers. 4778 if (Idx % EltsPerVector == 0) { 4779 AllConsecutive = true; 4780 continue; 4781 } 4782 4783 // Check all extracts for a vector register on the target directly 4784 // extract values in order. 4785 unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V)); 4786 if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) { 4787 unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1])); 4788 AllConsecutive &= PrevIdx + 1 == CurrentIdx && 4789 CurrentIdx % EltsPerVector == Idx % EltsPerVector; 4790 } 4791 4792 if (AllConsecutive) 4793 continue; 4794 4795 // Skip all indices, except for the last index per vector block. 4796 if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size()) 4797 continue; 4798 4799 // If we have a series of extracts which are not consecutive and hence 4800 // cannot re-use the source vector register directly, compute the shuffle 4801 // cost to extract the a vector with EltsPerVector elements. 4802 Cost += TTI.getShuffleCost( 4803 TargetTransformInfo::SK_PermuteSingleSrc, 4804 FixedVectorType::get(VecTy->getElementType(), EltsPerVector)); 4805 } 4806 return Cost; 4807 } 4808 4809 /// Build shuffle mask for shuffle graph entries and lists of main and alternate 4810 /// operations operands. 4811 static void 4812 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices, 4813 ArrayRef<int> ReusesIndices, 4814 const function_ref<bool(Instruction *)> IsAltOp, 4815 SmallVectorImpl<int> &Mask, 4816 SmallVectorImpl<Value *> *OpScalars = nullptr, 4817 SmallVectorImpl<Value *> *AltScalars = nullptr) { 4818 unsigned Sz = VL.size(); 4819 Mask.assign(Sz, UndefMaskElem); 4820 SmallVector<int> OrderMask; 4821 if (!ReorderIndices.empty()) 4822 inversePermutation(ReorderIndices, OrderMask); 4823 for (unsigned I = 0; I < Sz; ++I) { 4824 unsigned Idx = I; 4825 if (!ReorderIndices.empty()) 4826 Idx = OrderMask[I]; 4827 auto *OpInst = cast<Instruction>(VL[Idx]); 4828 if (IsAltOp(OpInst)) { 4829 Mask[I] = Sz + Idx; 4830 if (AltScalars) 4831 AltScalars->push_back(OpInst); 4832 } else { 4833 Mask[I] = Idx; 4834 if (OpScalars) 4835 OpScalars->push_back(OpInst); 4836 } 4837 } 4838 if (!ReusesIndices.empty()) { 4839 SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem); 4840 transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) { 4841 return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem; 4842 }); 4843 Mask.swap(NewMask); 4844 } 4845 } 4846 4847 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E, 4848 ArrayRef<Value *> VectorizedVals) { 4849 ArrayRef<Value*> VL = E->Scalars; 4850 4851 Type *ScalarTy = VL[0]->getType(); 4852 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 4853 ScalarTy = SI->getValueOperand()->getType(); 4854 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0])) 4855 ScalarTy = CI->getOperand(0)->getType(); 4856 else if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 4857 ScalarTy = IE->getOperand(1)->getType(); 4858 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 4859 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 4860 4861 // If we have computed a smaller type for the expression, update VecTy so 4862 // that the costs will be accurate. 4863 if (MinBWs.count(VL[0])) 4864 VecTy = FixedVectorType::get( 4865 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size()); 4866 unsigned EntryVF = E->getVectorFactor(); 4867 auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF); 4868 4869 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 4870 // FIXME: it tries to fix a problem with MSVC buildbots. 4871 TargetTransformInfo &TTIRef = *TTI; 4872 auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy, 4873 VectorizedVals, E](InstructionCost &Cost) { 4874 DenseMap<Value *, int> ExtractVectorsTys; 4875 SmallPtrSet<Value *, 4> CheckedExtracts; 4876 for (auto *V : VL) { 4877 if (isa<UndefValue>(V)) 4878 continue; 4879 // If all users of instruction are going to be vectorized and this 4880 // instruction itself is not going to be vectorized, consider this 4881 // instruction as dead and remove its cost from the final cost of the 4882 // vectorized tree. 4883 // Also, avoid adjusting the cost for extractelements with multiple uses 4884 // in different graph entries. 4885 const TreeEntry *VE = getTreeEntry(V); 4886 if (!CheckedExtracts.insert(V).second || 4887 !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) || 4888 (VE && VE != E)) 4889 continue; 4890 auto *EE = cast<ExtractElementInst>(V); 4891 Optional<unsigned> EEIdx = getExtractIndex(EE); 4892 if (!EEIdx) 4893 continue; 4894 unsigned Idx = *EEIdx; 4895 if (TTIRef.getNumberOfParts(VecTy) != 4896 TTIRef.getNumberOfParts(EE->getVectorOperandType())) { 4897 auto It = 4898 ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first; 4899 It->getSecond() = std::min<int>(It->second, Idx); 4900 } 4901 // Take credit for instruction that will become dead. 4902 if (EE->hasOneUse()) { 4903 Instruction *Ext = EE->user_back(); 4904 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 4905 all_of(Ext->users(), 4906 [](User *U) { return isa<GetElementPtrInst>(U); })) { 4907 // Use getExtractWithExtendCost() to calculate the cost of 4908 // extractelement/ext pair. 4909 Cost -= 4910 TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(), 4911 EE->getVectorOperandType(), Idx); 4912 // Add back the cost of s|zext which is subtracted separately. 4913 Cost += TTIRef.getCastInstrCost( 4914 Ext->getOpcode(), Ext->getType(), EE->getType(), 4915 TTI::getCastContextHint(Ext), CostKind, Ext); 4916 continue; 4917 } 4918 } 4919 Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement, 4920 EE->getVectorOperandType(), Idx); 4921 } 4922 // Add a cost for subvector extracts/inserts if required. 4923 for (const auto &Data : ExtractVectorsTys) { 4924 auto *EEVTy = cast<FixedVectorType>(Data.first->getType()); 4925 unsigned NumElts = VecTy->getNumElements(); 4926 if (Data.second % NumElts == 0) 4927 continue; 4928 if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) { 4929 unsigned Idx = (Data.second / NumElts) * NumElts; 4930 unsigned EENumElts = EEVTy->getNumElements(); 4931 if (Idx + NumElts <= EENumElts) { 4932 Cost += 4933 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 4934 EEVTy, None, Idx, VecTy); 4935 } else { 4936 // Need to round up the subvector type vectorization factor to avoid a 4937 // crash in cost model functions. Make SubVT so that Idx + VF of SubVT 4938 // <= EENumElts. 4939 auto *SubVT = 4940 FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx); 4941 Cost += 4942 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 4943 EEVTy, None, Idx, SubVT); 4944 } 4945 } else { 4946 Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector, 4947 VecTy, None, 0, EEVTy); 4948 } 4949 } 4950 }; 4951 if (E->State == TreeEntry::NeedToGather) { 4952 if (allConstant(VL)) 4953 return 0; 4954 if (isa<InsertElementInst>(VL[0])) 4955 return InstructionCost::getInvalid(); 4956 SmallVector<int> Mask; 4957 SmallVector<const TreeEntry *> Entries; 4958 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 4959 isGatherShuffledEntry(E, Mask, Entries); 4960 if (Shuffle.hasValue()) { 4961 InstructionCost GatherCost = 0; 4962 if (ShuffleVectorInst::isIdentityMask(Mask)) { 4963 // Perfect match in the graph, will reuse the previously vectorized 4964 // node. Cost is 0. 4965 LLVM_DEBUG( 4966 dbgs() 4967 << "SLP: perfect diamond match for gather bundle that starts with " 4968 << *VL.front() << ".\n"); 4969 if (NeedToShuffleReuses) 4970 GatherCost = 4971 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 4972 FinalVecTy, E->ReuseShuffleIndices); 4973 } else { 4974 LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size() 4975 << " entries for bundle that starts with " 4976 << *VL.front() << ".\n"); 4977 // Detected that instead of gather we can emit a shuffle of single/two 4978 // previously vectorized nodes. Add the cost of the permutation rather 4979 // than gather. 4980 ::addMask(Mask, E->ReuseShuffleIndices); 4981 GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask); 4982 } 4983 return GatherCost; 4984 } 4985 if ((E->getOpcode() == Instruction::ExtractElement || 4986 all_of(E->Scalars, 4987 [](Value *V) { 4988 return isa<ExtractElementInst, UndefValue>(V); 4989 })) && 4990 allSameType(VL)) { 4991 // Check that gather of extractelements can be represented as just a 4992 // shuffle of a single/two vectors the scalars are extracted from. 4993 SmallVector<int> Mask; 4994 Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = 4995 isFixedVectorShuffle(VL, Mask); 4996 if (ShuffleKind.hasValue()) { 4997 // Found the bunch of extractelement instructions that must be gathered 4998 // into a vector and can be represented as a permutation elements in a 4999 // single input vector or of 2 input vectors. 5000 InstructionCost Cost = 5001 computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI); 5002 AdjustExtractsCost(Cost); 5003 if (NeedToShuffleReuses) 5004 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 5005 FinalVecTy, E->ReuseShuffleIndices); 5006 return Cost; 5007 } 5008 } 5009 if (isSplat(VL)) { 5010 // Found the broadcasting of the single scalar, calculate the cost as the 5011 // broadcast. 5012 assert(VecTy == FinalVecTy && 5013 "No reused scalars expected for broadcast."); 5014 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy); 5015 } 5016 InstructionCost ReuseShuffleCost = 0; 5017 if (NeedToShuffleReuses) 5018 ReuseShuffleCost = TTI->getShuffleCost( 5019 TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices); 5020 // Improve gather cost for gather of loads, if we can group some of the 5021 // loads into vector loads. 5022 if (VL.size() > 2 && E->getOpcode() == Instruction::Load && 5023 !E->isAltShuffle()) { 5024 BoUpSLP::ValueSet VectorizedLoads; 5025 unsigned StartIdx = 0; 5026 unsigned VF = VL.size() / 2; 5027 unsigned VectorizedCnt = 0; 5028 unsigned ScatterVectorizeCnt = 0; 5029 const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType()); 5030 for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) { 5031 for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End; 5032 Cnt += VF) { 5033 ArrayRef<Value *> Slice = VL.slice(Cnt, VF); 5034 if (!VectorizedLoads.count(Slice.front()) && 5035 !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) { 5036 SmallVector<Value *> PointerOps; 5037 OrdersType CurrentOrder; 5038 LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL, 5039 *SE, CurrentOrder, PointerOps); 5040 switch (LS) { 5041 case LoadsState::Vectorize: 5042 case LoadsState::ScatterVectorize: 5043 // Mark the vectorized loads so that we don't vectorize them 5044 // again. 5045 if (LS == LoadsState::Vectorize) 5046 ++VectorizedCnt; 5047 else 5048 ++ScatterVectorizeCnt; 5049 VectorizedLoads.insert(Slice.begin(), Slice.end()); 5050 // If we vectorized initial block, no need to try to vectorize it 5051 // again. 5052 if (Cnt == StartIdx) 5053 StartIdx += VF; 5054 break; 5055 case LoadsState::Gather: 5056 break; 5057 } 5058 } 5059 } 5060 // Check if the whole array was vectorized already - exit. 5061 if (StartIdx >= VL.size()) 5062 break; 5063 // Found vectorizable parts - exit. 5064 if (!VectorizedLoads.empty()) 5065 break; 5066 } 5067 if (!VectorizedLoads.empty()) { 5068 InstructionCost GatherCost = 0; 5069 unsigned NumParts = TTI->getNumberOfParts(VecTy); 5070 bool NeedInsertSubvectorAnalysis = 5071 !NumParts || (VL.size() / VF) > NumParts; 5072 // Get the cost for gathered loads. 5073 for (unsigned I = 0, End = VL.size(); I < End; I += VF) { 5074 if (VectorizedLoads.contains(VL[I])) 5075 continue; 5076 GatherCost += getGatherCost(VL.slice(I, VF)); 5077 } 5078 // The cost for vectorized loads. 5079 InstructionCost ScalarsCost = 0; 5080 for (Value *V : VectorizedLoads) { 5081 auto *LI = cast<LoadInst>(V); 5082 ScalarsCost += TTI->getMemoryOpCost( 5083 Instruction::Load, LI->getType(), LI->getAlign(), 5084 LI->getPointerAddressSpace(), CostKind, LI); 5085 } 5086 auto *LI = cast<LoadInst>(E->getMainOp()); 5087 auto *LoadTy = FixedVectorType::get(LI->getType(), VF); 5088 Align Alignment = LI->getAlign(); 5089 GatherCost += 5090 VectorizedCnt * 5091 TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment, 5092 LI->getPointerAddressSpace(), CostKind, LI); 5093 GatherCost += ScatterVectorizeCnt * 5094 TTI->getGatherScatterOpCost( 5095 Instruction::Load, LoadTy, LI->getPointerOperand(), 5096 /*VariableMask=*/false, Alignment, CostKind, LI); 5097 if (NeedInsertSubvectorAnalysis) { 5098 // Add the cost for the subvectors insert. 5099 for (int I = VF, E = VL.size(); I < E; I += VF) 5100 GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy, 5101 None, I, LoadTy); 5102 } 5103 return ReuseShuffleCost + GatherCost - ScalarsCost; 5104 } 5105 } 5106 return ReuseShuffleCost + getGatherCost(VL); 5107 } 5108 InstructionCost CommonCost = 0; 5109 SmallVector<int> Mask; 5110 if (!E->ReorderIndices.empty()) { 5111 SmallVector<int> NewMask; 5112 if (E->getOpcode() == Instruction::Store) { 5113 // For stores the order is actually a mask. 5114 NewMask.resize(E->ReorderIndices.size()); 5115 copy(E->ReorderIndices, NewMask.begin()); 5116 } else { 5117 inversePermutation(E->ReorderIndices, NewMask); 5118 } 5119 ::addMask(Mask, NewMask); 5120 } 5121 if (NeedToShuffleReuses) 5122 ::addMask(Mask, E->ReuseShuffleIndices); 5123 if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask)) 5124 CommonCost = 5125 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask); 5126 assert((E->State == TreeEntry::Vectorize || 5127 E->State == TreeEntry::ScatterVectorize) && 5128 "Unhandled state"); 5129 assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL"); 5130 Instruction *VL0 = E->getMainOp(); 5131 unsigned ShuffleOrOp = 5132 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 5133 switch (ShuffleOrOp) { 5134 case Instruction::PHI: 5135 return 0; 5136 5137 case Instruction::ExtractValue: 5138 case Instruction::ExtractElement: { 5139 // The common cost of removal ExtractElement/ExtractValue instructions + 5140 // the cost of shuffles, if required to resuffle the original vector. 5141 if (NeedToShuffleReuses) { 5142 unsigned Idx = 0; 5143 for (unsigned I : E->ReuseShuffleIndices) { 5144 if (ShuffleOrOp == Instruction::ExtractElement) { 5145 auto *EE = cast<ExtractElementInst>(VL[I]); 5146 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 5147 EE->getVectorOperandType(), 5148 *getExtractIndex(EE)); 5149 } else { 5150 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 5151 VecTy, Idx); 5152 ++Idx; 5153 } 5154 } 5155 Idx = EntryVF; 5156 for (Value *V : VL) { 5157 if (ShuffleOrOp == Instruction::ExtractElement) { 5158 auto *EE = cast<ExtractElementInst>(V); 5159 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 5160 EE->getVectorOperandType(), 5161 *getExtractIndex(EE)); 5162 } else { 5163 --Idx; 5164 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 5165 VecTy, Idx); 5166 } 5167 } 5168 } 5169 if (ShuffleOrOp == Instruction::ExtractValue) { 5170 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 5171 auto *EI = cast<Instruction>(VL[I]); 5172 // Take credit for instruction that will become dead. 5173 if (EI->hasOneUse()) { 5174 Instruction *Ext = EI->user_back(); 5175 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 5176 all_of(Ext->users(), 5177 [](User *U) { return isa<GetElementPtrInst>(U); })) { 5178 // Use getExtractWithExtendCost() to calculate the cost of 5179 // extractelement/ext pair. 5180 CommonCost -= TTI->getExtractWithExtendCost( 5181 Ext->getOpcode(), Ext->getType(), VecTy, I); 5182 // Add back the cost of s|zext which is subtracted separately. 5183 CommonCost += TTI->getCastInstrCost( 5184 Ext->getOpcode(), Ext->getType(), EI->getType(), 5185 TTI::getCastContextHint(Ext), CostKind, Ext); 5186 continue; 5187 } 5188 } 5189 CommonCost -= 5190 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I); 5191 } 5192 } else { 5193 AdjustExtractsCost(CommonCost); 5194 } 5195 return CommonCost; 5196 } 5197 case Instruction::InsertElement: { 5198 assert(E->ReuseShuffleIndices.empty() && 5199 "Unique insertelements only are expected."); 5200 auto *SrcVecTy = cast<FixedVectorType>(VL0->getType()); 5201 5202 unsigned const NumElts = SrcVecTy->getNumElements(); 5203 unsigned const NumScalars = VL.size(); 5204 APInt DemandedElts = APInt::getZero(NumElts); 5205 // TODO: Add support for Instruction::InsertValue. 5206 SmallVector<int> Mask; 5207 if (!E->ReorderIndices.empty()) { 5208 inversePermutation(E->ReorderIndices, Mask); 5209 Mask.append(NumElts - NumScalars, UndefMaskElem); 5210 } else { 5211 Mask.assign(NumElts, UndefMaskElem); 5212 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 5213 } 5214 unsigned Offset = *getInsertIndex(VL0, 0); 5215 bool IsIdentity = true; 5216 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 5217 Mask.swap(PrevMask); 5218 for (unsigned I = 0; I < NumScalars; ++I) { 5219 Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0); 5220 if (!InsertIdx || *InsertIdx == UndefMaskElem) 5221 continue; 5222 DemandedElts.setBit(*InsertIdx); 5223 IsIdentity &= *InsertIdx - Offset == I; 5224 Mask[*InsertIdx - Offset] = I; 5225 } 5226 assert(Offset < NumElts && "Failed to find vector index offset"); 5227 5228 InstructionCost Cost = 0; 5229 Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts, 5230 /*Insert*/ true, /*Extract*/ false); 5231 5232 if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) { 5233 // FIXME: Replace with SK_InsertSubvector once it is properly supported. 5234 unsigned Sz = PowerOf2Ceil(Offset + NumScalars); 5235 Cost += TTI->getShuffleCost( 5236 TargetTransformInfo::SK_PermuteSingleSrc, 5237 FixedVectorType::get(SrcVecTy->getElementType(), Sz)); 5238 } else if (!IsIdentity) { 5239 auto *FirstInsert = 5240 cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 5241 return !is_contained(E->Scalars, 5242 cast<Instruction>(V)->getOperand(0)); 5243 })); 5244 if (isUndefVector(FirstInsert->getOperand(0))) { 5245 Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask); 5246 } else { 5247 SmallVector<int> InsertMask(NumElts); 5248 std::iota(InsertMask.begin(), InsertMask.end(), 0); 5249 for (unsigned I = 0; I < NumElts; I++) { 5250 if (Mask[I] != UndefMaskElem) 5251 InsertMask[Offset + I] = NumElts + I; 5252 } 5253 Cost += 5254 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask); 5255 } 5256 } 5257 5258 return Cost; 5259 } 5260 case Instruction::ZExt: 5261 case Instruction::SExt: 5262 case Instruction::FPToUI: 5263 case Instruction::FPToSI: 5264 case Instruction::FPExt: 5265 case Instruction::PtrToInt: 5266 case Instruction::IntToPtr: 5267 case Instruction::SIToFP: 5268 case Instruction::UIToFP: 5269 case Instruction::Trunc: 5270 case Instruction::FPTrunc: 5271 case Instruction::BitCast: { 5272 Type *SrcTy = VL0->getOperand(0)->getType(); 5273 InstructionCost ScalarEltCost = 5274 TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy, 5275 TTI::getCastContextHint(VL0), CostKind, VL0); 5276 if (NeedToShuffleReuses) { 5277 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5278 } 5279 5280 // Calculate the cost of this instruction. 5281 InstructionCost ScalarCost = VL.size() * ScalarEltCost; 5282 5283 auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size()); 5284 InstructionCost VecCost = 0; 5285 // Check if the values are candidates to demote. 5286 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) { 5287 VecCost = CommonCost + TTI->getCastInstrCost( 5288 E->getOpcode(), VecTy, SrcVecTy, 5289 TTI::getCastContextHint(VL0), CostKind, VL0); 5290 } 5291 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5292 return VecCost - ScalarCost; 5293 } 5294 case Instruction::FCmp: 5295 case Instruction::ICmp: 5296 case Instruction::Select: { 5297 // Calculate the cost of this instruction. 5298 InstructionCost ScalarEltCost = 5299 TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 5300 CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0); 5301 if (NeedToShuffleReuses) { 5302 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5303 } 5304 auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size()); 5305 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5306 5307 // Check if all entries in VL are either compares or selects with compares 5308 // as condition that have the same predicates. 5309 CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE; 5310 bool First = true; 5311 for (auto *V : VL) { 5312 CmpInst::Predicate CurrentPred; 5313 auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value()); 5314 if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) && 5315 !match(V, MatchCmp)) || 5316 (!First && VecPred != CurrentPred)) { 5317 VecPred = CmpInst::BAD_ICMP_PREDICATE; 5318 break; 5319 } 5320 First = false; 5321 VecPred = CurrentPred; 5322 } 5323 5324 InstructionCost VecCost = TTI->getCmpSelInstrCost( 5325 E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0); 5326 // Check if it is possible and profitable to use min/max for selects in 5327 // VL. 5328 // 5329 auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL); 5330 if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) { 5331 IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy, 5332 {VecTy, VecTy}); 5333 InstructionCost IntrinsicCost = 5334 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 5335 // If the selects are the only uses of the compares, they will be dead 5336 // and we can adjust the cost by removing their cost. 5337 if (IntrinsicAndUse.second) 5338 IntrinsicCost -= 5339 TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy, 5340 CmpInst::BAD_ICMP_PREDICATE, CostKind); 5341 VecCost = std::min(VecCost, IntrinsicCost); 5342 } 5343 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5344 return CommonCost + VecCost - ScalarCost; 5345 } 5346 case Instruction::FNeg: 5347 case Instruction::Add: 5348 case Instruction::FAdd: 5349 case Instruction::Sub: 5350 case Instruction::FSub: 5351 case Instruction::Mul: 5352 case Instruction::FMul: 5353 case Instruction::UDiv: 5354 case Instruction::SDiv: 5355 case Instruction::FDiv: 5356 case Instruction::URem: 5357 case Instruction::SRem: 5358 case Instruction::FRem: 5359 case Instruction::Shl: 5360 case Instruction::LShr: 5361 case Instruction::AShr: 5362 case Instruction::And: 5363 case Instruction::Or: 5364 case Instruction::Xor: { 5365 // Certain instructions can be cheaper to vectorize if they have a 5366 // constant second vector operand. 5367 TargetTransformInfo::OperandValueKind Op1VK = 5368 TargetTransformInfo::OK_AnyValue; 5369 TargetTransformInfo::OperandValueKind Op2VK = 5370 TargetTransformInfo::OK_UniformConstantValue; 5371 TargetTransformInfo::OperandValueProperties Op1VP = 5372 TargetTransformInfo::OP_None; 5373 TargetTransformInfo::OperandValueProperties Op2VP = 5374 TargetTransformInfo::OP_PowerOf2; 5375 5376 // If all operands are exactly the same ConstantInt then set the 5377 // operand kind to OK_UniformConstantValue. 5378 // If instead not all operands are constants, then set the operand kind 5379 // to OK_AnyValue. If all operands are constants but not the same, 5380 // then set the operand kind to OK_NonUniformConstantValue. 5381 ConstantInt *CInt0 = nullptr; 5382 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 5383 const Instruction *I = cast<Instruction>(VL[i]); 5384 unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0; 5385 ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx)); 5386 if (!CInt) { 5387 Op2VK = TargetTransformInfo::OK_AnyValue; 5388 Op2VP = TargetTransformInfo::OP_None; 5389 break; 5390 } 5391 if (Op2VP == TargetTransformInfo::OP_PowerOf2 && 5392 !CInt->getValue().isPowerOf2()) 5393 Op2VP = TargetTransformInfo::OP_None; 5394 if (i == 0) { 5395 CInt0 = CInt; 5396 continue; 5397 } 5398 if (CInt0 != CInt) 5399 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 5400 } 5401 5402 SmallVector<const Value *, 4> Operands(VL0->operand_values()); 5403 InstructionCost ScalarEltCost = 5404 TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK, 5405 Op2VK, Op1VP, Op2VP, Operands, VL0); 5406 if (NeedToShuffleReuses) { 5407 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5408 } 5409 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5410 InstructionCost VecCost = 5411 TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK, 5412 Op2VK, Op1VP, Op2VP, Operands, VL0); 5413 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5414 return CommonCost + VecCost - ScalarCost; 5415 } 5416 case Instruction::GetElementPtr: { 5417 TargetTransformInfo::OperandValueKind Op1VK = 5418 TargetTransformInfo::OK_AnyValue; 5419 TargetTransformInfo::OperandValueKind Op2VK = 5420 TargetTransformInfo::OK_UniformConstantValue; 5421 5422 InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost( 5423 Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK); 5424 if (NeedToShuffleReuses) { 5425 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5426 } 5427 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5428 InstructionCost VecCost = TTI->getArithmeticInstrCost( 5429 Instruction::Add, VecTy, CostKind, Op1VK, Op2VK); 5430 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5431 return CommonCost + VecCost - ScalarCost; 5432 } 5433 case Instruction::Load: { 5434 // Cost of wide load - cost of scalar loads. 5435 Align Alignment = cast<LoadInst>(VL0)->getAlign(); 5436 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 5437 Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0); 5438 if (NeedToShuffleReuses) { 5439 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5440 } 5441 InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost; 5442 InstructionCost VecLdCost; 5443 if (E->State == TreeEntry::Vectorize) { 5444 VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0, 5445 CostKind, VL0); 5446 } else { 5447 assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState"); 5448 Align CommonAlignment = Alignment; 5449 for (Value *V : VL) 5450 CommonAlignment = 5451 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 5452 VecLdCost = TTI->getGatherScatterOpCost( 5453 Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(), 5454 /*VariableMask=*/false, CommonAlignment, CostKind, VL0); 5455 } 5456 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost)); 5457 return CommonCost + VecLdCost - ScalarLdCost; 5458 } 5459 case Instruction::Store: { 5460 // We know that we can merge the stores. Calculate the cost. 5461 bool IsReorder = !E->ReorderIndices.empty(); 5462 auto *SI = 5463 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0); 5464 Align Alignment = SI->getAlign(); 5465 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 5466 Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0); 5467 InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost; 5468 InstructionCost VecStCost = TTI->getMemoryOpCost( 5469 Instruction::Store, VecTy, Alignment, 0, CostKind, VL0); 5470 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost)); 5471 return CommonCost + VecStCost - ScalarStCost; 5472 } 5473 case Instruction::Call: { 5474 CallInst *CI = cast<CallInst>(VL0); 5475 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 5476 5477 // Calculate the cost of the scalar and vector calls. 5478 IntrinsicCostAttributes CostAttrs(ID, *CI, 1); 5479 InstructionCost ScalarEltCost = 5480 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 5481 if (NeedToShuffleReuses) { 5482 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5483 } 5484 InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost; 5485 5486 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 5487 InstructionCost VecCallCost = 5488 std::min(VecCallCosts.first, VecCallCosts.second); 5489 5490 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost 5491 << " (" << VecCallCost << "-" << ScalarCallCost << ")" 5492 << " for " << *CI << "\n"); 5493 5494 return CommonCost + VecCallCost - ScalarCallCost; 5495 } 5496 case Instruction::ShuffleVector: { 5497 assert(E->isAltShuffle() && 5498 ((Instruction::isBinaryOp(E->getOpcode()) && 5499 Instruction::isBinaryOp(E->getAltOpcode())) || 5500 (Instruction::isCast(E->getOpcode()) && 5501 Instruction::isCast(E->getAltOpcode())) || 5502 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 5503 "Invalid Shuffle Vector Operand"); 5504 InstructionCost ScalarCost = 0; 5505 if (NeedToShuffleReuses) { 5506 for (unsigned Idx : E->ReuseShuffleIndices) { 5507 Instruction *I = cast<Instruction>(VL[Idx]); 5508 CommonCost -= TTI->getInstructionCost(I, CostKind); 5509 } 5510 for (Value *V : VL) { 5511 Instruction *I = cast<Instruction>(V); 5512 CommonCost += TTI->getInstructionCost(I, CostKind); 5513 } 5514 } 5515 for (Value *V : VL) { 5516 Instruction *I = cast<Instruction>(V); 5517 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 5518 ScalarCost += TTI->getInstructionCost(I, CostKind); 5519 } 5520 // VecCost is equal to sum of the cost of creating 2 vectors 5521 // and the cost of creating shuffle. 5522 InstructionCost VecCost = 0; 5523 // Try to find the previous shuffle node with the same operands and same 5524 // main/alternate ops. 5525 auto &&TryFindNodeWithEqualOperands = [this, E]() { 5526 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 5527 if (TE.get() == E) 5528 break; 5529 if (TE->isAltShuffle() && 5530 ((TE->getOpcode() == E->getOpcode() && 5531 TE->getAltOpcode() == E->getAltOpcode()) || 5532 (TE->getOpcode() == E->getAltOpcode() && 5533 TE->getAltOpcode() == E->getOpcode())) && 5534 TE->hasEqualOperands(*E)) 5535 return true; 5536 } 5537 return false; 5538 }; 5539 if (TryFindNodeWithEqualOperands()) { 5540 LLVM_DEBUG({ 5541 dbgs() << "SLP: diamond match for alternate node found.\n"; 5542 E->dump(); 5543 }); 5544 // No need to add new vector costs here since we're going to reuse 5545 // same main/alternate vector ops, just do different shuffling. 5546 } else if (Instruction::isBinaryOp(E->getOpcode())) { 5547 VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind); 5548 VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy, 5549 CostKind); 5550 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 5551 VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, 5552 Builder.getInt1Ty(), 5553 CI0->getPredicate(), CostKind, VL0); 5554 VecCost += TTI->getCmpSelInstrCost( 5555 E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 5556 cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind, 5557 E->getAltOp()); 5558 } else { 5559 Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType(); 5560 Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType(); 5561 auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size()); 5562 auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size()); 5563 VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty, 5564 TTI::CastContextHint::None, CostKind); 5565 VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty, 5566 TTI::CastContextHint::None, CostKind); 5567 } 5568 5569 SmallVector<int> Mask; 5570 buildSuffleEntryMask( 5571 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 5572 [E](Instruction *I) { 5573 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 5574 if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) { 5575 auto *AltCI0 = cast<CmpInst>(E->getAltOp()); 5576 auto *CI = cast<CmpInst>(I); 5577 CmpInst::Predicate P0 = CI0->getPredicate(); 5578 CmpInst::Predicate AltP0 = AltCI0->getPredicate(); 5579 assert(P0 != AltP0 && 5580 "Expected different main/alternate predicates."); 5581 CmpInst::Predicate AltP0Swapped = 5582 CmpInst::getSwappedPredicate(AltP0); 5583 CmpInst::Predicate CurrentPred = CI->getPredicate(); 5584 if (P0 == AltP0Swapped) 5585 return (P0 == CurrentPred && 5586 !areCompatibleCmpOps( 5587 CI0->getOperand(0), CI0->getOperand(1), 5588 CI->getOperand(0), CI->getOperand(1))) || 5589 (AltP0 == CurrentPred && 5590 !areCompatibleCmpOps( 5591 CI0->getOperand(0), CI0->getOperand(1), 5592 CI->getOperand(1), CI->getOperand(0))); 5593 return AltP0 == CurrentPred || AltP0Swapped == CurrentPred; 5594 } 5595 return I->getOpcode() == E->getAltOpcode(); 5596 }, 5597 Mask); 5598 CommonCost = 5599 TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask); 5600 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5601 return CommonCost + VecCost - ScalarCost; 5602 } 5603 default: 5604 llvm_unreachable("Unknown instruction"); 5605 } 5606 } 5607 5608 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const { 5609 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height " 5610 << VectorizableTree.size() << " is fully vectorizable .\n"); 5611 5612 auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) { 5613 SmallVector<int> Mask; 5614 return TE->State == TreeEntry::NeedToGather && 5615 !any_of(TE->Scalars, 5616 [this](Value *V) { return EphValues.contains(V); }) && 5617 (allConstant(TE->Scalars) || isSplat(TE->Scalars) || 5618 TE->Scalars.size() < Limit || 5619 ((TE->getOpcode() == Instruction::ExtractElement || 5620 all_of(TE->Scalars, 5621 [](Value *V) { 5622 return isa<ExtractElementInst, UndefValue>(V); 5623 })) && 5624 isFixedVectorShuffle(TE->Scalars, Mask)) || 5625 (TE->State == TreeEntry::NeedToGather && 5626 TE->getOpcode() == Instruction::Load && !TE->isAltShuffle())); 5627 }; 5628 5629 // We only handle trees of heights 1 and 2. 5630 if (VectorizableTree.size() == 1 && 5631 (VectorizableTree[0]->State == TreeEntry::Vectorize || 5632 (ForReduction && 5633 AreVectorizableGathers(VectorizableTree[0].get(), 5634 VectorizableTree[0]->Scalars.size()) && 5635 VectorizableTree[0]->getVectorFactor() > 2))) 5636 return true; 5637 5638 if (VectorizableTree.size() != 2) 5639 return false; 5640 5641 // Handle splat and all-constants stores. Also try to vectorize tiny trees 5642 // with the second gather nodes if they have less scalar operands rather than 5643 // the initial tree element (may be profitable to shuffle the second gather) 5644 // or they are extractelements, which form shuffle. 5645 SmallVector<int> Mask; 5646 if (VectorizableTree[0]->State == TreeEntry::Vectorize && 5647 AreVectorizableGathers(VectorizableTree[1].get(), 5648 VectorizableTree[0]->Scalars.size())) 5649 return true; 5650 5651 // Gathering cost would be too much for tiny trees. 5652 if (VectorizableTree[0]->State == TreeEntry::NeedToGather || 5653 (VectorizableTree[1]->State == TreeEntry::NeedToGather && 5654 VectorizableTree[0]->State != TreeEntry::ScatterVectorize)) 5655 return false; 5656 5657 return true; 5658 } 5659 5660 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts, 5661 TargetTransformInfo *TTI, 5662 bool MustMatchOrInst) { 5663 // Look past the root to find a source value. Arbitrarily follow the 5664 // path through operand 0 of any 'or'. Also, peek through optional 5665 // shift-left-by-multiple-of-8-bits. 5666 Value *ZextLoad = Root; 5667 const APInt *ShAmtC; 5668 bool FoundOr = false; 5669 while (!isa<ConstantExpr>(ZextLoad) && 5670 (match(ZextLoad, m_Or(m_Value(), m_Value())) || 5671 (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) && 5672 ShAmtC->urem(8) == 0))) { 5673 auto *BinOp = cast<BinaryOperator>(ZextLoad); 5674 ZextLoad = BinOp->getOperand(0); 5675 if (BinOp->getOpcode() == Instruction::Or) 5676 FoundOr = true; 5677 } 5678 // Check if the input is an extended load of the required or/shift expression. 5679 Value *Load; 5680 if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root || 5681 !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load)) 5682 return false; 5683 5684 // Require that the total load bit width is a legal integer type. 5685 // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target. 5686 // But <16 x i8> --> i128 is not, so the backend probably can't reduce it. 5687 Type *SrcTy = Load->getType(); 5688 unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts; 5689 if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth))) 5690 return false; 5691 5692 // Everything matched - assume that we can fold the whole sequence using 5693 // load combining. 5694 LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at " 5695 << *(cast<Instruction>(Root)) << "\n"); 5696 5697 return true; 5698 } 5699 5700 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const { 5701 if (RdxKind != RecurKind::Or) 5702 return false; 5703 5704 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 5705 Value *FirstReduced = VectorizableTree[0]->Scalars[0]; 5706 return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI, 5707 /* MatchOr */ false); 5708 } 5709 5710 bool BoUpSLP::isLoadCombineCandidate() const { 5711 // Peek through a final sequence of stores and check if all operations are 5712 // likely to be load-combined. 5713 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 5714 for (Value *Scalar : VectorizableTree[0]->Scalars) { 5715 Value *X; 5716 if (!match(Scalar, m_Store(m_Value(X), m_Value())) || 5717 !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true)) 5718 return false; 5719 } 5720 return true; 5721 } 5722 5723 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const { 5724 // No need to vectorize inserts of gathered values. 5725 if (VectorizableTree.size() == 2 && 5726 isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) && 5727 VectorizableTree[1]->State == TreeEntry::NeedToGather) 5728 return true; 5729 5730 // We can vectorize the tree if its size is greater than or equal to the 5731 // minimum size specified by the MinTreeSize command line option. 5732 if (VectorizableTree.size() >= MinTreeSize) 5733 return false; 5734 5735 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we 5736 // can vectorize it if we can prove it fully vectorizable. 5737 if (isFullyVectorizableTinyTree(ForReduction)) 5738 return false; 5739 5740 assert(VectorizableTree.empty() 5741 ? ExternalUses.empty() 5742 : true && "We shouldn't have any external users"); 5743 5744 // Otherwise, we can't vectorize the tree. It is both tiny and not fully 5745 // vectorizable. 5746 return true; 5747 } 5748 5749 InstructionCost BoUpSLP::getSpillCost() const { 5750 // Walk from the bottom of the tree to the top, tracking which values are 5751 // live. When we see a call instruction that is not part of our tree, 5752 // query TTI to see if there is a cost to keeping values live over it 5753 // (for example, if spills and fills are required). 5754 unsigned BundleWidth = VectorizableTree.front()->Scalars.size(); 5755 InstructionCost Cost = 0; 5756 5757 SmallPtrSet<Instruction*, 4> LiveValues; 5758 Instruction *PrevInst = nullptr; 5759 5760 // The entries in VectorizableTree are not necessarily ordered by their 5761 // position in basic blocks. Collect them and order them by dominance so later 5762 // instructions are guaranteed to be visited first. For instructions in 5763 // different basic blocks, we only scan to the beginning of the block, so 5764 // their order does not matter, as long as all instructions in a basic block 5765 // are grouped together. Using dominance ensures a deterministic order. 5766 SmallVector<Instruction *, 16> OrderedScalars; 5767 for (const auto &TEPtr : VectorizableTree) { 5768 Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]); 5769 if (!Inst) 5770 continue; 5771 OrderedScalars.push_back(Inst); 5772 } 5773 llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) { 5774 auto *NodeA = DT->getNode(A->getParent()); 5775 auto *NodeB = DT->getNode(B->getParent()); 5776 assert(NodeA && "Should only process reachable instructions"); 5777 assert(NodeB && "Should only process reachable instructions"); 5778 assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && 5779 "Different nodes should have different DFS numbers"); 5780 if (NodeA != NodeB) 5781 return NodeA->getDFSNumIn() < NodeB->getDFSNumIn(); 5782 return B->comesBefore(A); 5783 }); 5784 5785 for (Instruction *Inst : OrderedScalars) { 5786 if (!PrevInst) { 5787 PrevInst = Inst; 5788 continue; 5789 } 5790 5791 // Update LiveValues. 5792 LiveValues.erase(PrevInst); 5793 for (auto &J : PrevInst->operands()) { 5794 if (isa<Instruction>(&*J) && getTreeEntry(&*J)) 5795 LiveValues.insert(cast<Instruction>(&*J)); 5796 } 5797 5798 LLVM_DEBUG({ 5799 dbgs() << "SLP: #LV: " << LiveValues.size(); 5800 for (auto *X : LiveValues) 5801 dbgs() << " " << X->getName(); 5802 dbgs() << ", Looking at "; 5803 Inst->dump(); 5804 }); 5805 5806 // Now find the sequence of instructions between PrevInst and Inst. 5807 unsigned NumCalls = 0; 5808 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(), 5809 PrevInstIt = 5810 PrevInst->getIterator().getReverse(); 5811 while (InstIt != PrevInstIt) { 5812 if (PrevInstIt == PrevInst->getParent()->rend()) { 5813 PrevInstIt = Inst->getParent()->rbegin(); 5814 continue; 5815 } 5816 5817 // Debug information does not impact spill cost. 5818 if ((isa<CallInst>(&*PrevInstIt) && 5819 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) && 5820 &*PrevInstIt != PrevInst) 5821 NumCalls++; 5822 5823 ++PrevInstIt; 5824 } 5825 5826 if (NumCalls) { 5827 SmallVector<Type*, 4> V; 5828 for (auto *II : LiveValues) { 5829 auto *ScalarTy = II->getType(); 5830 if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy)) 5831 ScalarTy = VectorTy->getElementType(); 5832 V.push_back(FixedVectorType::get(ScalarTy, BundleWidth)); 5833 } 5834 Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V); 5835 } 5836 5837 PrevInst = Inst; 5838 } 5839 5840 return Cost; 5841 } 5842 5843 /// Check if two insertelement instructions are from the same buildvector. 5844 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU, 5845 InsertElementInst *V) { 5846 // Instructions must be from the same basic blocks. 5847 if (VU->getParent() != V->getParent()) 5848 return false; 5849 // Checks if 2 insertelements are from the same buildvector. 5850 if (VU->getType() != V->getType()) 5851 return false; 5852 // Multiple used inserts are separate nodes. 5853 if (!VU->hasOneUse() && !V->hasOneUse()) 5854 return false; 5855 auto *IE1 = VU; 5856 auto *IE2 = V; 5857 // Go through the vector operand of insertelement instructions trying to find 5858 // either VU as the original vector for IE2 or V as the original vector for 5859 // IE1. 5860 do { 5861 if (IE2 == VU || IE1 == V) 5862 return true; 5863 if (IE1) { 5864 if (IE1 != VU && !IE1->hasOneUse()) 5865 IE1 = nullptr; 5866 else 5867 IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0)); 5868 } 5869 if (IE2) { 5870 if (IE2 != V && !IE2->hasOneUse()) 5871 IE2 = nullptr; 5872 else 5873 IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0)); 5874 } 5875 } while (IE1 || IE2); 5876 return false; 5877 } 5878 5879 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) { 5880 InstructionCost Cost = 0; 5881 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size " 5882 << VectorizableTree.size() << ".\n"); 5883 5884 unsigned BundleWidth = VectorizableTree[0]->Scalars.size(); 5885 5886 for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) { 5887 TreeEntry &TE = *VectorizableTree[I].get(); 5888 5889 InstructionCost C = getEntryCost(&TE, VectorizedVals); 5890 Cost += C; 5891 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 5892 << " for bundle that starts with " << *TE.Scalars[0] 5893 << ".\n" 5894 << "SLP: Current total cost = " << Cost << "\n"); 5895 } 5896 5897 SmallPtrSet<Value *, 16> ExtractCostCalculated; 5898 InstructionCost ExtractCost = 0; 5899 SmallVector<unsigned> VF; 5900 SmallVector<SmallVector<int>> ShuffleMask; 5901 SmallVector<Value *> FirstUsers; 5902 SmallVector<APInt> DemandedElts; 5903 for (ExternalUser &EU : ExternalUses) { 5904 // We only add extract cost once for the same scalar. 5905 if (!isa_and_nonnull<InsertElementInst>(EU.User) && 5906 !ExtractCostCalculated.insert(EU.Scalar).second) 5907 continue; 5908 5909 // Uses by ephemeral values are free (because the ephemeral value will be 5910 // removed prior to code generation, and so the extraction will be 5911 // removed as well). 5912 if (EphValues.count(EU.User)) 5913 continue; 5914 5915 // No extract cost for vector "scalar" 5916 if (isa<FixedVectorType>(EU.Scalar->getType())) 5917 continue; 5918 5919 // Already counted the cost for external uses when tried to adjust the cost 5920 // for extractelements, no need to add it again. 5921 if (isa<ExtractElementInst>(EU.Scalar)) 5922 continue; 5923 5924 // If found user is an insertelement, do not calculate extract cost but try 5925 // to detect it as a final shuffled/identity match. 5926 if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) { 5927 if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) { 5928 Optional<int> InsertIdx = getInsertIndex(VU, 0); 5929 if (!InsertIdx || *InsertIdx == UndefMaskElem) 5930 continue; 5931 auto *It = find_if(FirstUsers, [VU](Value *V) { 5932 return areTwoInsertFromSameBuildVector(VU, 5933 cast<InsertElementInst>(V)); 5934 }); 5935 int VecId = -1; 5936 if (It == FirstUsers.end()) { 5937 VF.push_back(FTy->getNumElements()); 5938 ShuffleMask.emplace_back(VF.back(), UndefMaskElem); 5939 // Find the insertvector, vectorized in tree, if any. 5940 Value *Base = VU; 5941 while (isa<InsertElementInst>(Base)) { 5942 // Build the mask for the vectorized insertelement instructions. 5943 if (const TreeEntry *E = getTreeEntry(Base)) { 5944 VU = cast<InsertElementInst>(Base); 5945 do { 5946 int Idx = E->findLaneForValue(Base); 5947 ShuffleMask.back()[Idx] = Idx; 5948 Base = cast<InsertElementInst>(Base)->getOperand(0); 5949 } while (E == getTreeEntry(Base)); 5950 break; 5951 } 5952 Base = cast<InsertElementInst>(Base)->getOperand(0); 5953 } 5954 FirstUsers.push_back(VU); 5955 DemandedElts.push_back(APInt::getZero(VF.back())); 5956 VecId = FirstUsers.size() - 1; 5957 } else { 5958 VecId = std::distance(FirstUsers.begin(), It); 5959 } 5960 int Idx = *InsertIdx; 5961 ShuffleMask[VecId][Idx] = EU.Lane; 5962 DemandedElts[VecId].setBit(Idx); 5963 continue; 5964 } 5965 } 5966 5967 // If we plan to rewrite the tree in a smaller type, we will need to sign 5968 // extend the extracted value back to the original type. Here, we account 5969 // for the extract and the added cost of the sign extend if needed. 5970 auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth); 5971 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 5972 if (MinBWs.count(ScalarRoot)) { 5973 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 5974 auto Extend = 5975 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt; 5976 VecTy = FixedVectorType::get(MinTy, BundleWidth); 5977 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(), 5978 VecTy, EU.Lane); 5979 } else { 5980 ExtractCost += 5981 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane); 5982 } 5983 } 5984 5985 InstructionCost SpillCost = getSpillCost(); 5986 Cost += SpillCost + ExtractCost; 5987 if (FirstUsers.size() == 1) { 5988 int Limit = ShuffleMask.front().size() * 2; 5989 if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) && 5990 !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) { 5991 InstructionCost C = TTI->getShuffleCost( 5992 TTI::SK_PermuteSingleSrc, 5993 cast<FixedVectorType>(FirstUsers.front()->getType()), 5994 ShuffleMask.front()); 5995 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 5996 << " for final shuffle of insertelement external users " 5997 << *VectorizableTree.front()->Scalars.front() << ".\n" 5998 << "SLP: Current total cost = " << Cost << "\n"); 5999 Cost += C; 6000 } 6001 InstructionCost InsertCost = TTI->getScalarizationOverhead( 6002 cast<FixedVectorType>(FirstUsers.front()->getType()), 6003 DemandedElts.front(), /*Insert*/ true, /*Extract*/ false); 6004 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 6005 << " for insertelements gather.\n" 6006 << "SLP: Current total cost = " << Cost << "\n"); 6007 Cost -= InsertCost; 6008 } else if (FirstUsers.size() >= 2) { 6009 unsigned MaxVF = *std::max_element(VF.begin(), VF.end()); 6010 // Combined masks of the first 2 vectors. 6011 SmallVector<int> CombinedMask(MaxVF, UndefMaskElem); 6012 copy(ShuffleMask.front(), CombinedMask.begin()); 6013 APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF); 6014 auto *VecTy = FixedVectorType::get( 6015 cast<VectorType>(FirstUsers.front()->getType())->getElementType(), 6016 MaxVF); 6017 for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) { 6018 if (ShuffleMask[1][I] != UndefMaskElem) { 6019 CombinedMask[I] = ShuffleMask[1][I] + MaxVF; 6020 CombinedDemandedElts.setBit(I); 6021 } 6022 } 6023 InstructionCost C = 6024 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask); 6025 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6026 << " for final shuffle of vector node and external " 6027 "insertelement users " 6028 << *VectorizableTree.front()->Scalars.front() << ".\n" 6029 << "SLP: Current total cost = " << Cost << "\n"); 6030 Cost += C; 6031 InstructionCost InsertCost = TTI->getScalarizationOverhead( 6032 VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false); 6033 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 6034 << " for insertelements gather.\n" 6035 << "SLP: Current total cost = " << Cost << "\n"); 6036 Cost -= InsertCost; 6037 for (int I = 2, E = FirstUsers.size(); I < E; ++I) { 6038 // Other elements - permutation of 2 vectors (the initial one and the 6039 // next Ith incoming vector). 6040 unsigned VF = ShuffleMask[I].size(); 6041 for (unsigned Idx = 0; Idx < VF; ++Idx) { 6042 int Mask = ShuffleMask[I][Idx]; 6043 if (Mask != UndefMaskElem) 6044 CombinedMask[Idx] = MaxVF + Mask; 6045 else if (CombinedMask[Idx] != UndefMaskElem) 6046 CombinedMask[Idx] = Idx; 6047 } 6048 for (unsigned Idx = VF; Idx < MaxVF; ++Idx) 6049 if (CombinedMask[Idx] != UndefMaskElem) 6050 CombinedMask[Idx] = Idx; 6051 InstructionCost C = 6052 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask); 6053 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6054 << " for final shuffle of vector node and external " 6055 "insertelement users " 6056 << *VectorizableTree.front()->Scalars.front() << ".\n" 6057 << "SLP: Current total cost = " << Cost << "\n"); 6058 Cost += C; 6059 InstructionCost InsertCost = TTI->getScalarizationOverhead( 6060 cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I], 6061 /*Insert*/ true, /*Extract*/ false); 6062 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 6063 << " for insertelements gather.\n" 6064 << "SLP: Current total cost = " << Cost << "\n"); 6065 Cost -= InsertCost; 6066 } 6067 } 6068 6069 #ifndef NDEBUG 6070 SmallString<256> Str; 6071 { 6072 raw_svector_ostream OS(Str); 6073 OS << "SLP: Spill Cost = " << SpillCost << ".\n" 6074 << "SLP: Extract Cost = " << ExtractCost << ".\n" 6075 << "SLP: Total Cost = " << Cost << ".\n"; 6076 } 6077 LLVM_DEBUG(dbgs() << Str); 6078 if (ViewSLPTree) 6079 ViewGraph(this, "SLP" + F->getName(), false, Str); 6080 #endif 6081 6082 return Cost; 6083 } 6084 6085 Optional<TargetTransformInfo::ShuffleKind> 6086 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 6087 SmallVectorImpl<const TreeEntry *> &Entries) { 6088 // TODO: currently checking only for Scalars in the tree entry, need to count 6089 // reused elements too for better cost estimation. 6090 Mask.assign(TE->Scalars.size(), UndefMaskElem); 6091 Entries.clear(); 6092 // Build a lists of values to tree entries. 6093 DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs; 6094 for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) { 6095 if (EntryPtr.get() == TE) 6096 break; 6097 if (EntryPtr->State != TreeEntry::NeedToGather) 6098 continue; 6099 for (Value *V : EntryPtr->Scalars) 6100 ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get()); 6101 } 6102 // Find all tree entries used by the gathered values. If no common entries 6103 // found - not a shuffle. 6104 // Here we build a set of tree nodes for each gathered value and trying to 6105 // find the intersection between these sets. If we have at least one common 6106 // tree node for each gathered value - we have just a permutation of the 6107 // single vector. If we have 2 different sets, we're in situation where we 6108 // have a permutation of 2 input vectors. 6109 SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs; 6110 DenseMap<Value *, int> UsedValuesEntry; 6111 for (Value *V : TE->Scalars) { 6112 if (isa<UndefValue>(V)) 6113 continue; 6114 // Build a list of tree entries where V is used. 6115 SmallPtrSet<const TreeEntry *, 4> VToTEs; 6116 auto It = ValueToTEs.find(V); 6117 if (It != ValueToTEs.end()) 6118 VToTEs = It->second; 6119 if (const TreeEntry *VTE = getTreeEntry(V)) 6120 VToTEs.insert(VTE); 6121 if (VToTEs.empty()) 6122 return None; 6123 if (UsedTEs.empty()) { 6124 // The first iteration, just insert the list of nodes to vector. 6125 UsedTEs.push_back(VToTEs); 6126 } else { 6127 // Need to check if there are any previously used tree nodes which use V. 6128 // If there are no such nodes, consider that we have another one input 6129 // vector. 6130 SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs); 6131 unsigned Idx = 0; 6132 for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) { 6133 // Do we have a non-empty intersection of previously listed tree entries 6134 // and tree entries using current V? 6135 set_intersect(VToTEs, Set); 6136 if (!VToTEs.empty()) { 6137 // Yes, write the new subset and continue analysis for the next 6138 // scalar. 6139 Set.swap(VToTEs); 6140 break; 6141 } 6142 VToTEs = SavedVToTEs; 6143 ++Idx; 6144 } 6145 // No non-empty intersection found - need to add a second set of possible 6146 // source vectors. 6147 if (Idx == UsedTEs.size()) { 6148 // If the number of input vectors is greater than 2 - not a permutation, 6149 // fallback to the regular gather. 6150 if (UsedTEs.size() == 2) 6151 return None; 6152 UsedTEs.push_back(SavedVToTEs); 6153 Idx = UsedTEs.size() - 1; 6154 } 6155 UsedValuesEntry.try_emplace(V, Idx); 6156 } 6157 } 6158 6159 unsigned VF = 0; 6160 if (UsedTEs.size() == 1) { 6161 // Try to find the perfect match in another gather node at first. 6162 auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) { 6163 return EntryPtr->isSame(TE->Scalars); 6164 }); 6165 if (It != UsedTEs.front().end()) { 6166 Entries.push_back(*It); 6167 std::iota(Mask.begin(), Mask.end(), 0); 6168 return TargetTransformInfo::SK_PermuteSingleSrc; 6169 } 6170 // No perfect match, just shuffle, so choose the first tree node. 6171 Entries.push_back(*UsedTEs.front().begin()); 6172 } else { 6173 // Try to find nodes with the same vector factor. 6174 assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries."); 6175 DenseMap<int, const TreeEntry *> VFToTE; 6176 for (const TreeEntry *TE : UsedTEs.front()) 6177 VFToTE.try_emplace(TE->getVectorFactor(), TE); 6178 for (const TreeEntry *TE : UsedTEs.back()) { 6179 auto It = VFToTE.find(TE->getVectorFactor()); 6180 if (It != VFToTE.end()) { 6181 VF = It->first; 6182 Entries.push_back(It->second); 6183 Entries.push_back(TE); 6184 break; 6185 } 6186 } 6187 // No 2 source vectors with the same vector factor - give up and do regular 6188 // gather. 6189 if (Entries.empty()) 6190 return None; 6191 } 6192 6193 // Build a shuffle mask for better cost estimation and vector emission. 6194 for (int I = 0, E = TE->Scalars.size(); I < E; ++I) { 6195 Value *V = TE->Scalars[I]; 6196 if (isa<UndefValue>(V)) 6197 continue; 6198 unsigned Idx = UsedValuesEntry.lookup(V); 6199 const TreeEntry *VTE = Entries[Idx]; 6200 int FoundLane = VTE->findLaneForValue(V); 6201 Mask[I] = Idx * VF + FoundLane; 6202 // Extra check required by isSingleSourceMaskImpl function (called by 6203 // ShuffleVectorInst::isSingleSourceMask). 6204 if (Mask[I] >= 2 * E) 6205 return None; 6206 } 6207 switch (Entries.size()) { 6208 case 1: 6209 return TargetTransformInfo::SK_PermuteSingleSrc; 6210 case 2: 6211 return TargetTransformInfo::SK_PermuteTwoSrc; 6212 default: 6213 break; 6214 } 6215 return None; 6216 } 6217 6218 InstructionCost 6219 BoUpSLP::getGatherCost(FixedVectorType *Ty, 6220 const DenseSet<unsigned> &ShuffledIndices, 6221 bool NeedToShuffle) const { 6222 unsigned NumElts = Ty->getNumElements(); 6223 APInt DemandedElts = APInt::getZero(NumElts); 6224 for (unsigned I = 0; I < NumElts; ++I) 6225 if (!ShuffledIndices.count(I)) 6226 DemandedElts.setBit(I); 6227 InstructionCost Cost = 6228 TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true, 6229 /*Extract*/ false); 6230 if (NeedToShuffle) 6231 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty); 6232 return Cost; 6233 } 6234 6235 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const { 6236 // Find the type of the operands in VL. 6237 Type *ScalarTy = VL[0]->getType(); 6238 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 6239 ScalarTy = SI->getValueOperand()->getType(); 6240 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 6241 bool DuplicateNonConst = false; 6242 // Find the cost of inserting/extracting values from the vector. 6243 // Check if the same elements are inserted several times and count them as 6244 // shuffle candidates. 6245 DenseSet<unsigned> ShuffledElements; 6246 DenseSet<Value *> UniqueElements; 6247 // Iterate in reverse order to consider insert elements with the high cost. 6248 for (unsigned I = VL.size(); I > 0; --I) { 6249 unsigned Idx = I - 1; 6250 // No need to shuffle duplicates for constants. 6251 if (isConstant(VL[Idx])) { 6252 ShuffledElements.insert(Idx); 6253 continue; 6254 } 6255 if (!UniqueElements.insert(VL[Idx]).second) { 6256 DuplicateNonConst = true; 6257 ShuffledElements.insert(Idx); 6258 } 6259 } 6260 return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst); 6261 } 6262 6263 // Perform operand reordering on the instructions in VL and return the reordered 6264 // operands in Left and Right. 6265 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 6266 SmallVectorImpl<Value *> &Left, 6267 SmallVectorImpl<Value *> &Right, 6268 const DataLayout &DL, 6269 ScalarEvolution &SE, 6270 const BoUpSLP &R) { 6271 if (VL.empty()) 6272 return; 6273 VLOperands Ops(VL, DL, SE, R); 6274 // Reorder the operands in place. 6275 Ops.reorder(); 6276 Left = Ops.getVL(0); 6277 Right = Ops.getVL(1); 6278 } 6279 6280 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) { 6281 // Get the basic block this bundle is in. All instructions in the bundle 6282 // should be in this block. 6283 auto *Front = E->getMainOp(); 6284 auto *BB = Front->getParent(); 6285 assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool { 6286 auto *I = cast<Instruction>(V); 6287 return !E->isOpcodeOrAlt(I) || I->getParent() == BB; 6288 })); 6289 6290 // The last instruction in the bundle in program order. 6291 Instruction *LastInst = nullptr; 6292 6293 // Find the last instruction. The common case should be that BB has been 6294 // scheduled, and the last instruction is VL.back(). So we start with 6295 // VL.back() and iterate over schedule data until we reach the end of the 6296 // bundle. The end of the bundle is marked by null ScheduleData. 6297 if (BlocksSchedules.count(BB)) { 6298 auto *Bundle = 6299 BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back())); 6300 if (Bundle && Bundle->isPartOfBundle()) 6301 for (; Bundle; Bundle = Bundle->NextInBundle) 6302 if (Bundle->OpValue == Bundle->Inst) 6303 LastInst = Bundle->Inst; 6304 } 6305 6306 // LastInst can still be null at this point if there's either not an entry 6307 // for BB in BlocksSchedules or there's no ScheduleData available for 6308 // VL.back(). This can be the case if buildTree_rec aborts for various 6309 // reasons (e.g., the maximum recursion depth is reached, the maximum region 6310 // size is reached, etc.). ScheduleData is initialized in the scheduling 6311 // "dry-run". 6312 // 6313 // If this happens, we can still find the last instruction by brute force. We 6314 // iterate forwards from Front (inclusive) until we either see all 6315 // instructions in the bundle or reach the end of the block. If Front is the 6316 // last instruction in program order, LastInst will be set to Front, and we 6317 // will visit all the remaining instructions in the block. 6318 // 6319 // One of the reasons we exit early from buildTree_rec is to place an upper 6320 // bound on compile-time. Thus, taking an additional compile-time hit here is 6321 // not ideal. However, this should be exceedingly rare since it requires that 6322 // we both exit early from buildTree_rec and that the bundle be out-of-order 6323 // (causing us to iterate all the way to the end of the block). 6324 if (!LastInst) { 6325 SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end()); 6326 for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) { 6327 if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I)) 6328 LastInst = &I; 6329 if (Bundle.empty()) 6330 break; 6331 } 6332 } 6333 assert(LastInst && "Failed to find last instruction in bundle"); 6334 6335 // Set the insertion point after the last instruction in the bundle. Set the 6336 // debug location to Front. 6337 Builder.SetInsertPoint(BB, ++LastInst->getIterator()); 6338 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 6339 } 6340 6341 Value *BoUpSLP::gather(ArrayRef<Value *> VL) { 6342 // List of instructions/lanes from current block and/or the blocks which are 6343 // part of the current loop. These instructions will be inserted at the end to 6344 // make it possible to optimize loops and hoist invariant instructions out of 6345 // the loops body with better chances for success. 6346 SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts; 6347 SmallSet<int, 4> PostponedIndices; 6348 Loop *L = LI->getLoopFor(Builder.GetInsertBlock()); 6349 auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) { 6350 SmallPtrSet<BasicBlock *, 4> Visited; 6351 while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second) 6352 InsertBB = InsertBB->getSinglePredecessor(); 6353 return InsertBB && InsertBB == InstBB; 6354 }; 6355 for (int I = 0, E = VL.size(); I < E; ++I) { 6356 if (auto *Inst = dyn_cast<Instruction>(VL[I])) 6357 if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) || 6358 getTreeEntry(Inst) || (L && (L->contains(Inst)))) && 6359 PostponedIndices.insert(I).second) 6360 PostponedInsts.emplace_back(Inst, I); 6361 } 6362 6363 auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) { 6364 Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos)); 6365 auto *InsElt = dyn_cast<InsertElementInst>(Vec); 6366 if (!InsElt) 6367 return Vec; 6368 GatherShuffleSeq.insert(InsElt); 6369 CSEBlocks.insert(InsElt->getParent()); 6370 // Add to our 'need-to-extract' list. 6371 if (TreeEntry *Entry = getTreeEntry(V)) { 6372 // Find which lane we need to extract. 6373 unsigned FoundLane = Entry->findLaneForValue(V); 6374 ExternalUses.emplace_back(V, InsElt, FoundLane); 6375 } 6376 return Vec; 6377 }; 6378 Value *Val0 = 6379 isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0]; 6380 FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size()); 6381 Value *Vec = PoisonValue::get(VecTy); 6382 SmallVector<int> NonConsts; 6383 // Insert constant values at first. 6384 for (int I = 0, E = VL.size(); I < E; ++I) { 6385 if (PostponedIndices.contains(I)) 6386 continue; 6387 if (!isConstant(VL[I])) { 6388 NonConsts.push_back(I); 6389 continue; 6390 } 6391 Vec = CreateInsertElement(Vec, VL[I], I); 6392 } 6393 // Insert non-constant values. 6394 for (int I : NonConsts) 6395 Vec = CreateInsertElement(Vec, VL[I], I); 6396 // Append instructions, which are/may be part of the loop, in the end to make 6397 // it possible to hoist non-loop-based instructions. 6398 for (const std::pair<Value *, unsigned> &Pair : PostponedInsts) 6399 Vec = CreateInsertElement(Vec, Pair.first, Pair.second); 6400 6401 return Vec; 6402 } 6403 6404 namespace { 6405 /// Merges shuffle masks and emits final shuffle instruction, if required. 6406 class ShuffleInstructionBuilder { 6407 IRBuilderBase &Builder; 6408 const unsigned VF = 0; 6409 bool IsFinalized = false; 6410 SmallVector<int, 4> Mask; 6411 /// Holds all of the instructions that we gathered. 6412 SetVector<Instruction *> &GatherShuffleSeq; 6413 /// A list of blocks that we are going to CSE. 6414 SetVector<BasicBlock *> &CSEBlocks; 6415 6416 public: 6417 ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF, 6418 SetVector<Instruction *> &GatherShuffleSeq, 6419 SetVector<BasicBlock *> &CSEBlocks) 6420 : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq), 6421 CSEBlocks(CSEBlocks) {} 6422 6423 /// Adds a mask, inverting it before applying. 6424 void addInversedMask(ArrayRef<unsigned> SubMask) { 6425 if (SubMask.empty()) 6426 return; 6427 SmallVector<int, 4> NewMask; 6428 inversePermutation(SubMask, NewMask); 6429 addMask(NewMask); 6430 } 6431 6432 /// Functions adds masks, merging them into single one. 6433 void addMask(ArrayRef<unsigned> SubMask) { 6434 SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end()); 6435 addMask(NewMask); 6436 } 6437 6438 void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); } 6439 6440 Value *finalize(Value *V) { 6441 IsFinalized = true; 6442 unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements(); 6443 if (VF == ValueVF && Mask.empty()) 6444 return V; 6445 SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem); 6446 std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0); 6447 addMask(NormalizedMask); 6448 6449 if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask)) 6450 return V; 6451 Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle"); 6452 if (auto *I = dyn_cast<Instruction>(Vec)) { 6453 GatherShuffleSeq.insert(I); 6454 CSEBlocks.insert(I->getParent()); 6455 } 6456 return Vec; 6457 } 6458 6459 ~ShuffleInstructionBuilder() { 6460 assert((IsFinalized || Mask.empty()) && 6461 "Shuffle construction must be finalized."); 6462 } 6463 }; 6464 } // namespace 6465 6466 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { 6467 unsigned VF = VL.size(); 6468 InstructionsState S = getSameOpcode(VL); 6469 if (S.getOpcode()) { 6470 if (TreeEntry *E = getTreeEntry(S.OpValue)) 6471 if (E->isSame(VL)) { 6472 Value *V = vectorizeTree(E); 6473 if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) { 6474 if (!E->ReuseShuffleIndices.empty()) { 6475 // Reshuffle to get only unique values. 6476 // If some of the scalars are duplicated in the vectorization tree 6477 // entry, we do not vectorize them but instead generate a mask for 6478 // the reuses. But if there are several users of the same entry, 6479 // they may have different vectorization factors. This is especially 6480 // important for PHI nodes. In this case, we need to adapt the 6481 // resulting instruction for the user vectorization factor and have 6482 // to reshuffle it again to take only unique elements of the vector. 6483 // Without this code the function incorrectly returns reduced vector 6484 // instruction with the same elements, not with the unique ones. 6485 6486 // block: 6487 // %phi = phi <2 x > { .., %entry} {%shuffle, %block} 6488 // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0> 6489 // ... (use %2) 6490 // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0} 6491 // br %block 6492 SmallVector<int> UniqueIdxs(VF, UndefMaskElem); 6493 SmallSet<int, 4> UsedIdxs; 6494 int Pos = 0; 6495 int Sz = VL.size(); 6496 for (int Idx : E->ReuseShuffleIndices) { 6497 if (Idx != Sz && Idx != UndefMaskElem && 6498 UsedIdxs.insert(Idx).second) 6499 UniqueIdxs[Idx] = Pos; 6500 ++Pos; 6501 } 6502 assert(VF >= UsedIdxs.size() && "Expected vectorization factor " 6503 "less than original vector size."); 6504 UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem); 6505 V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle"); 6506 } else { 6507 assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() && 6508 "Expected vectorization factor less " 6509 "than original vector size."); 6510 SmallVector<int> UniformMask(VF, 0); 6511 std::iota(UniformMask.begin(), UniformMask.end(), 0); 6512 V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle"); 6513 } 6514 if (auto *I = dyn_cast<Instruction>(V)) { 6515 GatherShuffleSeq.insert(I); 6516 CSEBlocks.insert(I->getParent()); 6517 } 6518 } 6519 return V; 6520 } 6521 } 6522 6523 // Check that every instruction appears once in this bundle. 6524 SmallVector<int> ReuseShuffleIndicies; 6525 SmallVector<Value *> UniqueValues; 6526 if (VL.size() > 2) { 6527 DenseMap<Value *, unsigned> UniquePositions; 6528 unsigned NumValues = 6529 std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) { 6530 return !isa<UndefValue>(V); 6531 }).base()); 6532 VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues)); 6533 int UniqueVals = 0; 6534 for (Value *V : VL.drop_back(VL.size() - VF)) { 6535 if (isa<UndefValue>(V)) { 6536 ReuseShuffleIndicies.emplace_back(UndefMaskElem); 6537 continue; 6538 } 6539 if (isConstant(V)) { 6540 ReuseShuffleIndicies.emplace_back(UniqueValues.size()); 6541 UniqueValues.emplace_back(V); 6542 continue; 6543 } 6544 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 6545 ReuseShuffleIndicies.emplace_back(Res.first->second); 6546 if (Res.second) { 6547 UniqueValues.emplace_back(V); 6548 ++UniqueVals; 6549 } 6550 } 6551 if (UniqueVals == 1 && UniqueValues.size() == 1) { 6552 // Emit pure splat vector. 6553 ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(), 6554 UndefMaskElem); 6555 } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) { 6556 ReuseShuffleIndicies.clear(); 6557 UniqueValues.clear(); 6558 UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues)); 6559 } 6560 UniqueValues.append(VF - UniqueValues.size(), 6561 PoisonValue::get(VL[0]->getType())); 6562 VL = UniqueValues; 6563 } 6564 6565 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 6566 CSEBlocks); 6567 Value *Vec = gather(VL); 6568 if (!ReuseShuffleIndicies.empty()) { 6569 ShuffleBuilder.addMask(ReuseShuffleIndicies); 6570 Vec = ShuffleBuilder.finalize(Vec); 6571 } 6572 return Vec; 6573 } 6574 6575 Value *BoUpSLP::vectorizeTree(TreeEntry *E) { 6576 IRBuilder<>::InsertPointGuard Guard(Builder); 6577 6578 if (E->VectorizedValue) { 6579 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"); 6580 return E->VectorizedValue; 6581 } 6582 6583 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 6584 unsigned VF = E->getVectorFactor(); 6585 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 6586 CSEBlocks); 6587 if (E->State == TreeEntry::NeedToGather) { 6588 if (E->getMainOp()) 6589 setInsertPointAfterBundle(E); 6590 Value *Vec; 6591 SmallVector<int> Mask; 6592 SmallVector<const TreeEntry *> Entries; 6593 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 6594 isGatherShuffledEntry(E, Mask, Entries); 6595 if (Shuffle.hasValue()) { 6596 assert((Entries.size() == 1 || Entries.size() == 2) && 6597 "Expected shuffle of 1 or 2 entries."); 6598 Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue, 6599 Entries.back()->VectorizedValue, Mask); 6600 if (auto *I = dyn_cast<Instruction>(Vec)) { 6601 GatherShuffleSeq.insert(I); 6602 CSEBlocks.insert(I->getParent()); 6603 } 6604 } else { 6605 Vec = gather(E->Scalars); 6606 } 6607 if (NeedToShuffleReuses) { 6608 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6609 Vec = ShuffleBuilder.finalize(Vec); 6610 } 6611 E->VectorizedValue = Vec; 6612 return Vec; 6613 } 6614 6615 assert((E->State == TreeEntry::Vectorize || 6616 E->State == TreeEntry::ScatterVectorize) && 6617 "Unhandled state"); 6618 unsigned ShuffleOrOp = 6619 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 6620 Instruction *VL0 = E->getMainOp(); 6621 Type *ScalarTy = VL0->getType(); 6622 if (auto *Store = dyn_cast<StoreInst>(VL0)) 6623 ScalarTy = Store->getValueOperand()->getType(); 6624 else if (auto *IE = dyn_cast<InsertElementInst>(VL0)) 6625 ScalarTy = IE->getOperand(1)->getType(); 6626 auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size()); 6627 switch (ShuffleOrOp) { 6628 case Instruction::PHI: { 6629 assert( 6630 (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) && 6631 "PHI reordering is free."); 6632 auto *PH = cast<PHINode>(VL0); 6633 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI()); 6634 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 6635 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); 6636 Value *V = NewPhi; 6637 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6638 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6639 V = ShuffleBuilder.finalize(V); 6640 6641 E->VectorizedValue = V; 6642 6643 // PHINodes may have multiple entries from the same block. We want to 6644 // visit every block once. 6645 SmallPtrSet<BasicBlock*, 4> VisitedBBs; 6646 6647 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 6648 ValueList Operands; 6649 BasicBlock *IBB = PH->getIncomingBlock(i); 6650 6651 if (!VisitedBBs.insert(IBB).second) { 6652 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB); 6653 continue; 6654 } 6655 6656 Builder.SetInsertPoint(IBB->getTerminator()); 6657 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 6658 Value *Vec = vectorizeTree(E->getOperand(i)); 6659 NewPhi->addIncoming(Vec, IBB); 6660 } 6661 6662 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && 6663 "Invalid number of incoming values"); 6664 return V; 6665 } 6666 6667 case Instruction::ExtractElement: { 6668 Value *V = E->getSingleOperand(0); 6669 Builder.SetInsertPoint(VL0); 6670 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6671 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6672 V = ShuffleBuilder.finalize(V); 6673 E->VectorizedValue = V; 6674 return V; 6675 } 6676 case Instruction::ExtractValue: { 6677 auto *LI = cast<LoadInst>(E->getSingleOperand(0)); 6678 Builder.SetInsertPoint(LI); 6679 auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace()); 6680 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy); 6681 LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign()); 6682 Value *NewV = propagateMetadata(V, E->Scalars); 6683 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6684 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6685 NewV = ShuffleBuilder.finalize(NewV); 6686 E->VectorizedValue = NewV; 6687 return NewV; 6688 } 6689 case Instruction::InsertElement: { 6690 assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique"); 6691 Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back())); 6692 Value *V = vectorizeTree(E->getOperand(1)); 6693 6694 // Create InsertVector shuffle if necessary 6695 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 6696 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); 6697 })); 6698 const unsigned NumElts = 6699 cast<FixedVectorType>(FirstInsert->getType())->getNumElements(); 6700 const unsigned NumScalars = E->Scalars.size(); 6701 6702 unsigned Offset = *getInsertIndex(VL0, 0); 6703 assert(Offset < NumElts && "Failed to find vector index offset"); 6704 6705 // Create shuffle to resize vector 6706 SmallVector<int> Mask; 6707 if (!E->ReorderIndices.empty()) { 6708 inversePermutation(E->ReorderIndices, Mask); 6709 Mask.append(NumElts - NumScalars, UndefMaskElem); 6710 } else { 6711 Mask.assign(NumElts, UndefMaskElem); 6712 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 6713 } 6714 // Create InsertVector shuffle if necessary 6715 bool IsIdentity = true; 6716 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 6717 Mask.swap(PrevMask); 6718 for (unsigned I = 0; I < NumScalars; ++I) { 6719 Value *Scalar = E->Scalars[PrevMask[I]]; 6720 Optional<int> InsertIdx = getInsertIndex(Scalar, 0); 6721 if (!InsertIdx || *InsertIdx == UndefMaskElem) 6722 continue; 6723 IsIdentity &= *InsertIdx - Offset == I; 6724 Mask[*InsertIdx - Offset] = I; 6725 } 6726 if (!IsIdentity || NumElts != NumScalars) { 6727 V = Builder.CreateShuffleVector(V, Mask); 6728 if (auto *I = dyn_cast<Instruction>(V)) { 6729 GatherShuffleSeq.insert(I); 6730 CSEBlocks.insert(I->getParent()); 6731 } 6732 } 6733 6734 if ((!IsIdentity || Offset != 0 || 6735 !isUndefVector(FirstInsert->getOperand(0))) && 6736 NumElts != NumScalars) { 6737 SmallVector<int> InsertMask(NumElts); 6738 std::iota(InsertMask.begin(), InsertMask.end(), 0); 6739 for (unsigned I = 0; I < NumElts; I++) { 6740 if (Mask[I] != UndefMaskElem) 6741 InsertMask[Offset + I] = NumElts + I; 6742 } 6743 6744 V = Builder.CreateShuffleVector( 6745 FirstInsert->getOperand(0), V, InsertMask, 6746 cast<Instruction>(E->Scalars.back())->getName()); 6747 if (auto *I = dyn_cast<Instruction>(V)) { 6748 GatherShuffleSeq.insert(I); 6749 CSEBlocks.insert(I->getParent()); 6750 } 6751 } 6752 6753 ++NumVectorInstructions; 6754 E->VectorizedValue = V; 6755 return V; 6756 } 6757 case Instruction::ZExt: 6758 case Instruction::SExt: 6759 case Instruction::FPToUI: 6760 case Instruction::FPToSI: 6761 case Instruction::FPExt: 6762 case Instruction::PtrToInt: 6763 case Instruction::IntToPtr: 6764 case Instruction::SIToFP: 6765 case Instruction::UIToFP: 6766 case Instruction::Trunc: 6767 case Instruction::FPTrunc: 6768 case Instruction::BitCast: { 6769 setInsertPointAfterBundle(E); 6770 6771 Value *InVec = vectorizeTree(E->getOperand(0)); 6772 6773 if (E->VectorizedValue) { 6774 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6775 return E->VectorizedValue; 6776 } 6777 6778 auto *CI = cast<CastInst>(VL0); 6779 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); 6780 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6781 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6782 V = ShuffleBuilder.finalize(V); 6783 6784 E->VectorizedValue = V; 6785 ++NumVectorInstructions; 6786 return V; 6787 } 6788 case Instruction::FCmp: 6789 case Instruction::ICmp: { 6790 setInsertPointAfterBundle(E); 6791 6792 Value *L = vectorizeTree(E->getOperand(0)); 6793 Value *R = vectorizeTree(E->getOperand(1)); 6794 6795 if (E->VectorizedValue) { 6796 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6797 return E->VectorizedValue; 6798 } 6799 6800 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 6801 Value *V = Builder.CreateCmp(P0, L, R); 6802 propagateIRFlags(V, E->Scalars, VL0); 6803 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6804 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6805 V = ShuffleBuilder.finalize(V); 6806 6807 E->VectorizedValue = V; 6808 ++NumVectorInstructions; 6809 return V; 6810 } 6811 case Instruction::Select: { 6812 setInsertPointAfterBundle(E); 6813 6814 Value *Cond = vectorizeTree(E->getOperand(0)); 6815 Value *True = vectorizeTree(E->getOperand(1)); 6816 Value *False = vectorizeTree(E->getOperand(2)); 6817 6818 if (E->VectorizedValue) { 6819 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6820 return E->VectorizedValue; 6821 } 6822 6823 Value *V = Builder.CreateSelect(Cond, True, False); 6824 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6825 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6826 V = ShuffleBuilder.finalize(V); 6827 6828 E->VectorizedValue = V; 6829 ++NumVectorInstructions; 6830 return V; 6831 } 6832 case Instruction::FNeg: { 6833 setInsertPointAfterBundle(E); 6834 6835 Value *Op = vectorizeTree(E->getOperand(0)); 6836 6837 if (E->VectorizedValue) { 6838 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6839 return E->VectorizedValue; 6840 } 6841 6842 Value *V = Builder.CreateUnOp( 6843 static_cast<Instruction::UnaryOps>(E->getOpcode()), Op); 6844 propagateIRFlags(V, E->Scalars, VL0); 6845 if (auto *I = dyn_cast<Instruction>(V)) 6846 V = propagateMetadata(I, E->Scalars); 6847 6848 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6849 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6850 V = ShuffleBuilder.finalize(V); 6851 6852 E->VectorizedValue = V; 6853 ++NumVectorInstructions; 6854 6855 return V; 6856 } 6857 case Instruction::Add: 6858 case Instruction::FAdd: 6859 case Instruction::Sub: 6860 case Instruction::FSub: 6861 case Instruction::Mul: 6862 case Instruction::FMul: 6863 case Instruction::UDiv: 6864 case Instruction::SDiv: 6865 case Instruction::FDiv: 6866 case Instruction::URem: 6867 case Instruction::SRem: 6868 case Instruction::FRem: 6869 case Instruction::Shl: 6870 case Instruction::LShr: 6871 case Instruction::AShr: 6872 case Instruction::And: 6873 case Instruction::Or: 6874 case Instruction::Xor: { 6875 setInsertPointAfterBundle(E); 6876 6877 Value *LHS = vectorizeTree(E->getOperand(0)); 6878 Value *RHS = vectorizeTree(E->getOperand(1)); 6879 6880 if (E->VectorizedValue) { 6881 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 6882 return E->VectorizedValue; 6883 } 6884 6885 Value *V = Builder.CreateBinOp( 6886 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, 6887 RHS); 6888 propagateIRFlags(V, E->Scalars, VL0); 6889 if (auto *I = dyn_cast<Instruction>(V)) 6890 V = propagateMetadata(I, E->Scalars); 6891 6892 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6893 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6894 V = ShuffleBuilder.finalize(V); 6895 6896 E->VectorizedValue = V; 6897 ++NumVectorInstructions; 6898 6899 return V; 6900 } 6901 case Instruction::Load: { 6902 // Loads are inserted at the head of the tree because we don't want to 6903 // sink them all the way down past store instructions. 6904 setInsertPointAfterBundle(E); 6905 6906 LoadInst *LI = cast<LoadInst>(VL0); 6907 Instruction *NewLI; 6908 unsigned AS = LI->getPointerAddressSpace(); 6909 Value *PO = LI->getPointerOperand(); 6910 if (E->State == TreeEntry::Vectorize) { 6911 6912 Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS)); 6913 6914 // The pointer operand uses an in-tree scalar so we add the new BitCast 6915 // to ExternalUses list to make sure that an extract will be generated 6916 // in the future. 6917 if (TreeEntry *Entry = getTreeEntry(PO)) { 6918 // Find which lane we need to extract. 6919 unsigned FoundLane = Entry->findLaneForValue(PO); 6920 ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane); 6921 } 6922 6923 NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign()); 6924 } else { 6925 assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state"); 6926 Value *VecPtr = vectorizeTree(E->getOperand(0)); 6927 // Use the minimum alignment of the gathered loads. 6928 Align CommonAlignment = LI->getAlign(); 6929 for (Value *V : E->Scalars) 6930 CommonAlignment = 6931 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 6932 NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment); 6933 } 6934 Value *V = propagateMetadata(NewLI, E->Scalars); 6935 6936 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6937 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6938 V = ShuffleBuilder.finalize(V); 6939 E->VectorizedValue = V; 6940 ++NumVectorInstructions; 6941 return V; 6942 } 6943 case Instruction::Store: { 6944 auto *SI = cast<StoreInst>(VL0); 6945 unsigned AS = SI->getPointerAddressSpace(); 6946 6947 setInsertPointAfterBundle(E); 6948 6949 Value *VecValue = vectorizeTree(E->getOperand(0)); 6950 ShuffleBuilder.addMask(E->ReorderIndices); 6951 VecValue = ShuffleBuilder.finalize(VecValue); 6952 6953 Value *ScalarPtr = SI->getPointerOperand(); 6954 Value *VecPtr = Builder.CreateBitCast( 6955 ScalarPtr, VecValue->getType()->getPointerTo(AS)); 6956 StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr, 6957 SI->getAlign()); 6958 6959 // The pointer operand uses an in-tree scalar, so add the new BitCast to 6960 // ExternalUses to make sure that an extract will be generated in the 6961 // future. 6962 if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) { 6963 // Find which lane we need to extract. 6964 unsigned FoundLane = Entry->findLaneForValue(ScalarPtr); 6965 ExternalUses.push_back( 6966 ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane)); 6967 } 6968 6969 Value *V = propagateMetadata(ST, E->Scalars); 6970 6971 E->VectorizedValue = V; 6972 ++NumVectorInstructions; 6973 return V; 6974 } 6975 case Instruction::GetElementPtr: { 6976 auto *GEP0 = cast<GetElementPtrInst>(VL0); 6977 setInsertPointAfterBundle(E); 6978 6979 Value *Op0 = vectorizeTree(E->getOperand(0)); 6980 6981 SmallVector<Value *> OpVecs; 6982 for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) { 6983 Value *OpVec = vectorizeTree(E->getOperand(J)); 6984 OpVecs.push_back(OpVec); 6985 } 6986 6987 Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs); 6988 if (Instruction *I = dyn_cast<Instruction>(V)) 6989 V = propagateMetadata(I, E->Scalars); 6990 6991 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6992 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6993 V = ShuffleBuilder.finalize(V); 6994 6995 E->VectorizedValue = V; 6996 ++NumVectorInstructions; 6997 6998 return V; 6999 } 7000 case Instruction::Call: { 7001 CallInst *CI = cast<CallInst>(VL0); 7002 setInsertPointAfterBundle(E); 7003 7004 Intrinsic::ID IID = Intrinsic::not_intrinsic; 7005 if (Function *FI = CI->getCalledFunction()) 7006 IID = FI->getIntrinsicID(); 7007 7008 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 7009 7010 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 7011 bool UseIntrinsic = ID != Intrinsic::not_intrinsic && 7012 VecCallCosts.first <= VecCallCosts.second; 7013 7014 Value *ScalarArg = nullptr; 7015 std::vector<Value *> OpVecs; 7016 SmallVector<Type *, 2> TysForDecl = 7017 {FixedVectorType::get(CI->getType(), E->Scalars.size())}; 7018 for (int j = 0, e = CI->arg_size(); j < e; ++j) { 7019 ValueList OpVL; 7020 // Some intrinsics have scalar arguments. This argument should not be 7021 // vectorized. 7022 if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) { 7023 CallInst *CEI = cast<CallInst>(VL0); 7024 ScalarArg = CEI->getArgOperand(j); 7025 OpVecs.push_back(CEI->getArgOperand(j)); 7026 if (hasVectorInstrinsicOverloadedScalarOpd(IID, j)) 7027 TysForDecl.push_back(ScalarArg->getType()); 7028 continue; 7029 } 7030 7031 Value *OpVec = vectorizeTree(E->getOperand(j)); 7032 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n"); 7033 OpVecs.push_back(OpVec); 7034 } 7035 7036 Function *CF; 7037 if (!UseIntrinsic) { 7038 VFShape Shape = 7039 VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 7040 VecTy->getNumElements())), 7041 false /*HasGlobalPred*/); 7042 CF = VFDatabase(*CI).getVectorizedFunction(Shape); 7043 } else { 7044 CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl); 7045 } 7046 7047 SmallVector<OperandBundleDef, 1> OpBundles; 7048 CI->getOperandBundlesAsDefs(OpBundles); 7049 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles); 7050 7051 // The scalar argument uses an in-tree scalar so we add the new vectorized 7052 // call to ExternalUses list to make sure that an extract will be 7053 // generated in the future. 7054 if (ScalarArg) { 7055 if (TreeEntry *Entry = getTreeEntry(ScalarArg)) { 7056 // Find which lane we need to extract. 7057 unsigned FoundLane = Entry->findLaneForValue(ScalarArg); 7058 ExternalUses.push_back( 7059 ExternalUser(ScalarArg, cast<User>(V), FoundLane)); 7060 } 7061 } 7062 7063 propagateIRFlags(V, E->Scalars, VL0); 7064 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7065 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7066 V = ShuffleBuilder.finalize(V); 7067 7068 E->VectorizedValue = V; 7069 ++NumVectorInstructions; 7070 return V; 7071 } 7072 case Instruction::ShuffleVector: { 7073 assert(E->isAltShuffle() && 7074 ((Instruction::isBinaryOp(E->getOpcode()) && 7075 Instruction::isBinaryOp(E->getAltOpcode())) || 7076 (Instruction::isCast(E->getOpcode()) && 7077 Instruction::isCast(E->getAltOpcode())) || 7078 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 7079 "Invalid Shuffle Vector Operand"); 7080 7081 Value *LHS = nullptr, *RHS = nullptr; 7082 if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) { 7083 setInsertPointAfterBundle(E); 7084 LHS = vectorizeTree(E->getOperand(0)); 7085 RHS = vectorizeTree(E->getOperand(1)); 7086 } else { 7087 setInsertPointAfterBundle(E); 7088 LHS = vectorizeTree(E->getOperand(0)); 7089 } 7090 7091 if (E->VectorizedValue) { 7092 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7093 return E->VectorizedValue; 7094 } 7095 7096 Value *V0, *V1; 7097 if (Instruction::isBinaryOp(E->getOpcode())) { 7098 V0 = Builder.CreateBinOp( 7099 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS); 7100 V1 = Builder.CreateBinOp( 7101 static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS); 7102 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 7103 V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS); 7104 auto *AltCI = cast<CmpInst>(E->getAltOp()); 7105 CmpInst::Predicate AltPred = AltCI->getPredicate(); 7106 unsigned AltIdx = 7107 std::distance(E->Scalars.begin(), find(E->Scalars, AltCI)); 7108 if (AltCI->getOperand(0) != E->getOperand(0)[AltIdx]) 7109 AltPred = CmpInst::getSwappedPredicate(AltPred); 7110 V1 = Builder.CreateCmp(AltPred, LHS, RHS); 7111 } else { 7112 V0 = Builder.CreateCast( 7113 static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy); 7114 V1 = Builder.CreateCast( 7115 static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy); 7116 } 7117 // Add V0 and V1 to later analysis to try to find and remove matching 7118 // instruction, if any. 7119 for (Value *V : {V0, V1}) { 7120 if (auto *I = dyn_cast<Instruction>(V)) { 7121 GatherShuffleSeq.insert(I); 7122 CSEBlocks.insert(I->getParent()); 7123 } 7124 } 7125 7126 // Create shuffle to take alternate operations from the vector. 7127 // Also, gather up main and alt scalar ops to propagate IR flags to 7128 // each vector operation. 7129 ValueList OpScalars, AltScalars; 7130 SmallVector<int> Mask; 7131 buildSuffleEntryMask( 7132 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 7133 [E](Instruction *I) { 7134 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 7135 if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) { 7136 auto *AltCI0 = cast<CmpInst>(E->getAltOp()); 7137 auto *CI = cast<CmpInst>(I); 7138 CmpInst::Predicate P0 = CI0->getPredicate(); 7139 CmpInst::Predicate AltP0 = AltCI0->getPredicate(); 7140 assert(P0 != AltP0 && 7141 "Expected different main/alternate predicates."); 7142 CmpInst::Predicate AltP0Swapped = 7143 CmpInst::getSwappedPredicate(AltP0); 7144 CmpInst::Predicate CurrentPred = CI->getPredicate(); 7145 if (P0 == AltP0Swapped) 7146 return (P0 == CurrentPred && 7147 !areCompatibleCmpOps( 7148 CI0->getOperand(0), CI0->getOperand(1), 7149 CI->getOperand(0), CI->getOperand(1))) || 7150 (AltP0 == CurrentPred && 7151 !areCompatibleCmpOps( 7152 CI0->getOperand(0), CI0->getOperand(1), 7153 CI->getOperand(1), CI->getOperand(0))); 7154 return AltP0 == CurrentPred || AltP0Swapped == CurrentPred; 7155 } 7156 return I->getOpcode() == E->getAltOpcode(); 7157 }, 7158 Mask, &OpScalars, &AltScalars); 7159 7160 propagateIRFlags(V0, OpScalars); 7161 propagateIRFlags(V1, AltScalars); 7162 7163 Value *V = Builder.CreateShuffleVector(V0, V1, Mask); 7164 if (auto *I = dyn_cast<Instruction>(V)) { 7165 V = propagateMetadata(I, E->Scalars); 7166 GatherShuffleSeq.insert(I); 7167 CSEBlocks.insert(I->getParent()); 7168 } 7169 V = ShuffleBuilder.finalize(V); 7170 7171 E->VectorizedValue = V; 7172 ++NumVectorInstructions; 7173 7174 return V; 7175 } 7176 default: 7177 llvm_unreachable("unknown inst"); 7178 } 7179 return nullptr; 7180 } 7181 7182 Value *BoUpSLP::vectorizeTree() { 7183 ExtraValueToDebugLocsMap ExternallyUsedValues; 7184 return vectorizeTree(ExternallyUsedValues); 7185 } 7186 7187 Value * 7188 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) { 7189 // All blocks must be scheduled before any instructions are inserted. 7190 for (auto &BSIter : BlocksSchedules) { 7191 scheduleBlock(BSIter.second.get()); 7192 } 7193 7194 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7195 auto *VectorRoot = vectorizeTree(VectorizableTree[0].get()); 7196 7197 // If the vectorized tree can be rewritten in a smaller type, we truncate the 7198 // vectorized root. InstCombine will then rewrite the entire expression. We 7199 // sign extend the extracted values below. 7200 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 7201 if (MinBWs.count(ScalarRoot)) { 7202 if (auto *I = dyn_cast<Instruction>(VectorRoot)) { 7203 // If current instr is a phi and not the last phi, insert it after the 7204 // last phi node. 7205 if (isa<PHINode>(I)) 7206 Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt()); 7207 else 7208 Builder.SetInsertPoint(&*++BasicBlock::iterator(I)); 7209 } 7210 auto BundleWidth = VectorizableTree[0]->Scalars.size(); 7211 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 7212 auto *VecTy = FixedVectorType::get(MinTy, BundleWidth); 7213 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy); 7214 VectorizableTree[0]->VectorizedValue = Trunc; 7215 } 7216 7217 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() 7218 << " values .\n"); 7219 7220 // Extract all of the elements with the external uses. 7221 for (const auto &ExternalUse : ExternalUses) { 7222 Value *Scalar = ExternalUse.Scalar; 7223 llvm::User *User = ExternalUse.User; 7224 7225 // Skip users that we already RAUW. This happens when one instruction 7226 // has multiple uses of the same value. 7227 if (User && !is_contained(Scalar->users(), User)) 7228 continue; 7229 TreeEntry *E = getTreeEntry(Scalar); 7230 assert(E && "Invalid scalar"); 7231 assert(E->State != TreeEntry::NeedToGather && 7232 "Extracting from a gather list"); 7233 7234 Value *Vec = E->VectorizedValue; 7235 assert(Vec && "Can't find vectorizable value"); 7236 7237 Value *Lane = Builder.getInt32(ExternalUse.Lane); 7238 auto ExtractAndExtendIfNeeded = [&](Value *Vec) { 7239 if (Scalar->getType() != Vec->getType()) { 7240 Value *Ex; 7241 // "Reuse" the existing extract to improve final codegen. 7242 if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) { 7243 Ex = Builder.CreateExtractElement(ES->getOperand(0), 7244 ES->getOperand(1)); 7245 } else { 7246 Ex = Builder.CreateExtractElement(Vec, Lane); 7247 } 7248 // If necessary, sign-extend or zero-extend ScalarRoot 7249 // to the larger type. 7250 if (!MinBWs.count(ScalarRoot)) 7251 return Ex; 7252 if (MinBWs[ScalarRoot].second) 7253 return Builder.CreateSExt(Ex, Scalar->getType()); 7254 return Builder.CreateZExt(Ex, Scalar->getType()); 7255 } 7256 assert(isa<FixedVectorType>(Scalar->getType()) && 7257 isa<InsertElementInst>(Scalar) && 7258 "In-tree scalar of vector type is not insertelement?"); 7259 return Vec; 7260 }; 7261 // If User == nullptr, the Scalar is used as extra arg. Generate 7262 // ExtractElement instruction and update the record for this scalar in 7263 // ExternallyUsedValues. 7264 if (!User) { 7265 assert(ExternallyUsedValues.count(Scalar) && 7266 "Scalar with nullptr as an external user must be registered in " 7267 "ExternallyUsedValues map"); 7268 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 7269 Builder.SetInsertPoint(VecI->getParent(), 7270 std::next(VecI->getIterator())); 7271 } else { 7272 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7273 } 7274 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7275 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent()); 7276 auto &NewInstLocs = ExternallyUsedValues[NewInst]; 7277 auto It = ExternallyUsedValues.find(Scalar); 7278 assert(It != ExternallyUsedValues.end() && 7279 "Externally used scalar is not found in ExternallyUsedValues"); 7280 NewInstLocs.append(It->second); 7281 ExternallyUsedValues.erase(Scalar); 7282 // Required to update internally referenced instructions. 7283 Scalar->replaceAllUsesWith(NewInst); 7284 continue; 7285 } 7286 7287 // Generate extracts for out-of-tree users. 7288 // Find the insertion point for the extractelement lane. 7289 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 7290 if (PHINode *PH = dyn_cast<PHINode>(User)) { 7291 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { 7292 if (PH->getIncomingValue(i) == Scalar) { 7293 Instruction *IncomingTerminator = 7294 PH->getIncomingBlock(i)->getTerminator(); 7295 if (isa<CatchSwitchInst>(IncomingTerminator)) { 7296 Builder.SetInsertPoint(VecI->getParent(), 7297 std::next(VecI->getIterator())); 7298 } else { 7299 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator()); 7300 } 7301 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7302 CSEBlocks.insert(PH->getIncomingBlock(i)); 7303 PH->setOperand(i, NewInst); 7304 } 7305 } 7306 } else { 7307 Builder.SetInsertPoint(cast<Instruction>(User)); 7308 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7309 CSEBlocks.insert(cast<Instruction>(User)->getParent()); 7310 User->replaceUsesOfWith(Scalar, NewInst); 7311 } 7312 } else { 7313 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7314 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7315 CSEBlocks.insert(&F->getEntryBlock()); 7316 User->replaceUsesOfWith(Scalar, NewInst); 7317 } 7318 7319 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n"); 7320 } 7321 7322 // For each vectorized value: 7323 for (auto &TEPtr : VectorizableTree) { 7324 TreeEntry *Entry = TEPtr.get(); 7325 7326 // No need to handle users of gathered values. 7327 if (Entry->State == TreeEntry::NeedToGather) 7328 continue; 7329 7330 assert(Entry->VectorizedValue && "Can't find vectorizable value"); 7331 7332 // For each lane: 7333 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 7334 Value *Scalar = Entry->Scalars[Lane]; 7335 7336 #ifndef NDEBUG 7337 Type *Ty = Scalar->getType(); 7338 if (!Ty->isVoidTy()) { 7339 for (User *U : Scalar->users()) { 7340 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n"); 7341 7342 // It is legal to delete users in the ignorelist. 7343 assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) || 7344 (isa_and_nonnull<Instruction>(U) && 7345 isDeleted(cast<Instruction>(U)))) && 7346 "Deleting out-of-tree value"); 7347 } 7348 } 7349 #endif 7350 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n"); 7351 eraseInstruction(cast<Instruction>(Scalar)); 7352 } 7353 } 7354 7355 Builder.ClearInsertionPoint(); 7356 InstrElementSize.clear(); 7357 7358 return VectorizableTree[0]->VectorizedValue; 7359 } 7360 7361 void BoUpSLP::optimizeGatherSequence() { 7362 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size() 7363 << " gather sequences instructions.\n"); 7364 // LICM InsertElementInst sequences. 7365 for (Instruction *I : GatherShuffleSeq) { 7366 if (isDeleted(I)) 7367 continue; 7368 7369 // Check if this block is inside a loop. 7370 Loop *L = LI->getLoopFor(I->getParent()); 7371 if (!L) 7372 continue; 7373 7374 // Check if it has a preheader. 7375 BasicBlock *PreHeader = L->getLoopPreheader(); 7376 if (!PreHeader) 7377 continue; 7378 7379 // If the vector or the element that we insert into it are 7380 // instructions that are defined in this basic block then we can't 7381 // hoist this instruction. 7382 if (any_of(I->operands(), [L](Value *V) { 7383 auto *OpI = dyn_cast<Instruction>(V); 7384 return OpI && L->contains(OpI); 7385 })) 7386 continue; 7387 7388 // We can hoist this instruction. Move it to the pre-header. 7389 I->moveBefore(PreHeader->getTerminator()); 7390 } 7391 7392 // Make a list of all reachable blocks in our CSE queue. 7393 SmallVector<const DomTreeNode *, 8> CSEWorkList; 7394 CSEWorkList.reserve(CSEBlocks.size()); 7395 for (BasicBlock *BB : CSEBlocks) 7396 if (DomTreeNode *N = DT->getNode(BB)) { 7397 assert(DT->isReachableFromEntry(N)); 7398 CSEWorkList.push_back(N); 7399 } 7400 7401 // Sort blocks by domination. This ensures we visit a block after all blocks 7402 // dominating it are visited. 7403 llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) { 7404 assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && 7405 "Different nodes should have different DFS numbers"); 7406 return A->getDFSNumIn() < B->getDFSNumIn(); 7407 }); 7408 7409 // Less defined shuffles can be replaced by the more defined copies. 7410 // Between two shuffles one is less defined if it has the same vector operands 7411 // and its mask indeces are the same as in the first one or undefs. E.g. 7412 // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0, 7413 // poison, <0, 0, 0, 0>. 7414 auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2, 7415 SmallVectorImpl<int> &NewMask) { 7416 if (I1->getType() != I2->getType()) 7417 return false; 7418 auto *SI1 = dyn_cast<ShuffleVectorInst>(I1); 7419 auto *SI2 = dyn_cast<ShuffleVectorInst>(I2); 7420 if (!SI1 || !SI2) 7421 return I1->isIdenticalTo(I2); 7422 if (SI1->isIdenticalTo(SI2)) 7423 return true; 7424 for (int I = 0, E = SI1->getNumOperands(); I < E; ++I) 7425 if (SI1->getOperand(I) != SI2->getOperand(I)) 7426 return false; 7427 // Check if the second instruction is more defined than the first one. 7428 NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end()); 7429 ArrayRef<int> SM1 = SI1->getShuffleMask(); 7430 // Count trailing undefs in the mask to check the final number of used 7431 // registers. 7432 unsigned LastUndefsCnt = 0; 7433 for (int I = 0, E = NewMask.size(); I < E; ++I) { 7434 if (SM1[I] == UndefMaskElem) 7435 ++LastUndefsCnt; 7436 else 7437 LastUndefsCnt = 0; 7438 if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem && 7439 NewMask[I] != SM1[I]) 7440 return false; 7441 if (NewMask[I] == UndefMaskElem) 7442 NewMask[I] = SM1[I]; 7443 } 7444 // Check if the last undefs actually change the final number of used vector 7445 // registers. 7446 return SM1.size() - LastUndefsCnt > 1 && 7447 TTI->getNumberOfParts(SI1->getType()) == 7448 TTI->getNumberOfParts( 7449 FixedVectorType::get(SI1->getType()->getElementType(), 7450 SM1.size() - LastUndefsCnt)); 7451 }; 7452 // Perform O(N^2) search over the gather/shuffle sequences and merge identical 7453 // instructions. TODO: We can further optimize this scan if we split the 7454 // instructions into different buckets based on the insert lane. 7455 SmallVector<Instruction *, 16> Visited; 7456 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) { 7457 assert(*I && 7458 (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && 7459 "Worklist not sorted properly!"); 7460 BasicBlock *BB = (*I)->getBlock(); 7461 // For all instructions in blocks containing gather sequences: 7462 for (Instruction &In : llvm::make_early_inc_range(*BB)) { 7463 if (isDeleted(&In)) 7464 continue; 7465 if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) && 7466 !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In)) 7467 continue; 7468 7469 // Check if we can replace this instruction with any of the 7470 // visited instructions. 7471 bool Replaced = false; 7472 for (Instruction *&V : Visited) { 7473 SmallVector<int> NewMask; 7474 if (IsIdenticalOrLessDefined(&In, V, NewMask) && 7475 DT->dominates(V->getParent(), In.getParent())) { 7476 In.replaceAllUsesWith(V); 7477 eraseInstruction(&In); 7478 if (auto *SI = dyn_cast<ShuffleVectorInst>(V)) 7479 if (!NewMask.empty()) 7480 SI->setShuffleMask(NewMask); 7481 Replaced = true; 7482 break; 7483 } 7484 if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) && 7485 GatherShuffleSeq.contains(V) && 7486 IsIdenticalOrLessDefined(V, &In, NewMask) && 7487 DT->dominates(In.getParent(), V->getParent())) { 7488 In.moveAfter(V); 7489 V->replaceAllUsesWith(&In); 7490 eraseInstruction(V); 7491 if (auto *SI = dyn_cast<ShuffleVectorInst>(&In)) 7492 if (!NewMask.empty()) 7493 SI->setShuffleMask(NewMask); 7494 V = &In; 7495 Replaced = true; 7496 break; 7497 } 7498 } 7499 if (!Replaced) { 7500 assert(!is_contained(Visited, &In)); 7501 Visited.push_back(&In); 7502 } 7503 } 7504 } 7505 CSEBlocks.clear(); 7506 GatherShuffleSeq.clear(); 7507 } 7508 7509 BoUpSLP::ScheduleData * 7510 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) { 7511 ScheduleData *Bundle = nullptr; 7512 ScheduleData *PrevInBundle = nullptr; 7513 for (Value *V : VL) { 7514 ScheduleData *BundleMember = getScheduleData(V); 7515 assert(BundleMember && 7516 "no ScheduleData for bundle member " 7517 "(maybe not in same basic block)"); 7518 assert(BundleMember->isSchedulingEntity() && 7519 "bundle member already part of other bundle"); 7520 if (PrevInBundle) { 7521 PrevInBundle->NextInBundle = BundleMember; 7522 } else { 7523 Bundle = BundleMember; 7524 } 7525 7526 // Group the instructions to a bundle. 7527 BundleMember->FirstInBundle = Bundle; 7528 PrevInBundle = BundleMember; 7529 } 7530 assert(Bundle && "Failed to find schedule bundle"); 7531 return Bundle; 7532 } 7533 7534 // Groups the instructions to a bundle (which is then a single scheduling entity) 7535 // and schedules instructions until the bundle gets ready. 7536 Optional<BoUpSLP::ScheduleData *> 7537 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 7538 const InstructionsState &S) { 7539 // No need to schedule PHIs, insertelement, extractelement and extractvalue 7540 // instructions. 7541 if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue)) 7542 return nullptr; 7543 7544 // Initialize the instruction bundle. 7545 Instruction *OldScheduleEnd = ScheduleEnd; 7546 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n"); 7547 7548 auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule, 7549 ScheduleData *Bundle) { 7550 // The scheduling region got new instructions at the lower end (or it is a 7551 // new region for the first bundle). This makes it necessary to 7552 // recalculate all dependencies. 7553 // It is seldom that this needs to be done a second time after adding the 7554 // initial bundle to the region. 7555 if (ScheduleEnd != OldScheduleEnd) { 7556 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) 7557 doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); }); 7558 ReSchedule = true; 7559 } 7560 if (Bundle) { 7561 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle 7562 << " in block " << BB->getName() << "\n"); 7563 calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP); 7564 } 7565 7566 if (ReSchedule) { 7567 resetSchedule(); 7568 initialFillReadyList(ReadyInsts); 7569 } 7570 7571 // Now try to schedule the new bundle or (if no bundle) just calculate 7572 // dependencies. As soon as the bundle is "ready" it means that there are no 7573 // cyclic dependencies and we can schedule it. Note that's important that we 7574 // don't "schedule" the bundle yet (see cancelScheduling). 7575 while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) && 7576 !ReadyInsts.empty()) { 7577 ScheduleData *Picked = ReadyInsts.pop_back_val(); 7578 assert(Picked->isSchedulingEntity() && Picked->isReady() && 7579 "must be ready to schedule"); 7580 schedule(Picked, ReadyInsts); 7581 } 7582 }; 7583 7584 // Make sure that the scheduling region contains all 7585 // instructions of the bundle. 7586 for (Value *V : VL) { 7587 if (!extendSchedulingRegion(V, S)) { 7588 // If the scheduling region got new instructions at the lower end (or it 7589 // is a new region for the first bundle). This makes it necessary to 7590 // recalculate all dependencies. 7591 // Otherwise the compiler may crash trying to incorrectly calculate 7592 // dependencies and emit instruction in the wrong order at the actual 7593 // scheduling. 7594 TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr); 7595 return None; 7596 } 7597 } 7598 7599 bool ReSchedule = false; 7600 for (Value *V : VL) { 7601 ScheduleData *BundleMember = getScheduleData(V); 7602 assert(BundleMember && 7603 "no ScheduleData for bundle member (maybe not in same basic block)"); 7604 7605 // Make sure we don't leave the pieces of the bundle in the ready list when 7606 // whole bundle might not be ready. 7607 ReadyInsts.remove(BundleMember); 7608 7609 if (!BundleMember->IsScheduled) 7610 continue; 7611 // A bundle member was scheduled as single instruction before and now 7612 // needs to be scheduled as part of the bundle. We just get rid of the 7613 // existing schedule. 7614 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember 7615 << " was already scheduled\n"); 7616 ReSchedule = true; 7617 } 7618 7619 auto *Bundle = buildBundle(VL); 7620 TryScheduleBundleImpl(ReSchedule, Bundle); 7621 if (!Bundle->isReady()) { 7622 cancelScheduling(VL, S.OpValue); 7623 return None; 7624 } 7625 return Bundle; 7626 } 7627 7628 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL, 7629 Value *OpValue) { 7630 if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue)) 7631 return; 7632 7633 ScheduleData *Bundle = getScheduleData(OpValue); 7634 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n"); 7635 assert(!Bundle->IsScheduled && 7636 "Can't cancel bundle which is already scheduled"); 7637 assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() && 7638 "tried to unbundle something which is not a bundle"); 7639 7640 // Remove the bundle from the ready list. 7641 if (Bundle->isReady()) 7642 ReadyInsts.remove(Bundle); 7643 7644 // Un-bundle: make single instructions out of the bundle. 7645 ScheduleData *BundleMember = Bundle; 7646 while (BundleMember) { 7647 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links"); 7648 BundleMember->FirstInBundle = BundleMember; 7649 ScheduleData *Next = BundleMember->NextInBundle; 7650 BundleMember->NextInBundle = nullptr; 7651 if (BundleMember->unscheduledDepsInBundle() == 0) { 7652 ReadyInsts.insert(BundleMember); 7653 } 7654 BundleMember = Next; 7655 } 7656 } 7657 7658 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() { 7659 // Allocate a new ScheduleData for the instruction. 7660 if (ChunkPos >= ChunkSize) { 7661 ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize)); 7662 ChunkPos = 0; 7663 } 7664 return &(ScheduleDataChunks.back()[ChunkPos++]); 7665 } 7666 7667 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V, 7668 const InstructionsState &S) { 7669 if (getScheduleData(V, isOneOf(S, V))) 7670 return true; 7671 Instruction *I = dyn_cast<Instruction>(V); 7672 assert(I && "bundle member must be an instruction"); 7673 assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && 7674 "phi nodes/insertelements/extractelements/extractvalues don't need to " 7675 "be scheduled"); 7676 auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool { 7677 ScheduleData *ISD = getScheduleData(I); 7678 if (!ISD) 7679 return false; 7680 assert(isInSchedulingRegion(ISD) && 7681 "ScheduleData not in scheduling region"); 7682 ScheduleData *SD = allocateScheduleDataChunks(); 7683 SD->Inst = I; 7684 SD->init(SchedulingRegionID, S.OpValue); 7685 ExtraScheduleDataMap[I][S.OpValue] = SD; 7686 return true; 7687 }; 7688 if (CheckSheduleForI(I)) 7689 return true; 7690 if (!ScheduleStart) { 7691 // It's the first instruction in the new region. 7692 initScheduleData(I, I->getNextNode(), nullptr, nullptr); 7693 ScheduleStart = I; 7694 ScheduleEnd = I->getNextNode(); 7695 if (isOneOf(S, I) != I) 7696 CheckSheduleForI(I); 7697 assert(ScheduleEnd && "tried to vectorize a terminator?"); 7698 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n"); 7699 return true; 7700 } 7701 // Search up and down at the same time, because we don't know if the new 7702 // instruction is above or below the existing scheduling region. 7703 BasicBlock::reverse_iterator UpIter = 7704 ++ScheduleStart->getIterator().getReverse(); 7705 BasicBlock::reverse_iterator UpperEnd = BB->rend(); 7706 BasicBlock::iterator DownIter = ScheduleEnd->getIterator(); 7707 BasicBlock::iterator LowerEnd = BB->end(); 7708 while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I && 7709 &*DownIter != I) { 7710 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) { 7711 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n"); 7712 return false; 7713 } 7714 7715 ++UpIter; 7716 ++DownIter; 7717 } 7718 if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) { 7719 assert(I->getParent() == ScheduleStart->getParent() && 7720 "Instruction is in wrong basic block."); 7721 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion); 7722 ScheduleStart = I; 7723 if (isOneOf(S, I) != I) 7724 CheckSheduleForI(I); 7725 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I 7726 << "\n"); 7727 return true; 7728 } 7729 assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && 7730 "Expected to reach top of the basic block or instruction down the " 7731 "lower end."); 7732 assert(I->getParent() == ScheduleEnd->getParent() && 7733 "Instruction is in wrong basic block."); 7734 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion, 7735 nullptr); 7736 ScheduleEnd = I->getNextNode(); 7737 if (isOneOf(S, I) != I) 7738 CheckSheduleForI(I); 7739 assert(ScheduleEnd && "tried to vectorize a terminator?"); 7740 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n"); 7741 return true; 7742 } 7743 7744 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI, 7745 Instruction *ToI, 7746 ScheduleData *PrevLoadStore, 7747 ScheduleData *NextLoadStore) { 7748 ScheduleData *CurrentLoadStore = PrevLoadStore; 7749 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) { 7750 ScheduleData *SD = ScheduleDataMap[I]; 7751 if (!SD) { 7752 SD = allocateScheduleDataChunks(); 7753 ScheduleDataMap[I] = SD; 7754 SD->Inst = I; 7755 } 7756 assert(!isInSchedulingRegion(SD) && 7757 "new ScheduleData already in scheduling region"); 7758 SD->init(SchedulingRegionID, I); 7759 7760 if (I->mayReadOrWriteMemory() && 7761 (!isa<IntrinsicInst>(I) || 7762 (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect && 7763 cast<IntrinsicInst>(I)->getIntrinsicID() != 7764 Intrinsic::pseudoprobe))) { 7765 // Update the linked list of memory accessing instructions. 7766 if (CurrentLoadStore) { 7767 CurrentLoadStore->NextLoadStore = SD; 7768 } else { 7769 FirstLoadStoreInRegion = SD; 7770 } 7771 CurrentLoadStore = SD; 7772 } 7773 } 7774 if (NextLoadStore) { 7775 if (CurrentLoadStore) 7776 CurrentLoadStore->NextLoadStore = NextLoadStore; 7777 } else { 7778 LastLoadStoreInRegion = CurrentLoadStore; 7779 } 7780 } 7781 7782 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD, 7783 bool InsertInReadyList, 7784 BoUpSLP *SLP) { 7785 assert(SD->isSchedulingEntity()); 7786 7787 SmallVector<ScheduleData *, 10> WorkList; 7788 WorkList.push_back(SD); 7789 7790 while (!WorkList.empty()) { 7791 ScheduleData *SD = WorkList.pop_back_val(); 7792 for (ScheduleData *BundleMember = SD; BundleMember; 7793 BundleMember = BundleMember->NextInBundle) { 7794 assert(isInSchedulingRegion(BundleMember)); 7795 if (BundleMember->hasValidDependencies()) 7796 continue; 7797 7798 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember 7799 << "\n"); 7800 BundleMember->Dependencies = 0; 7801 BundleMember->resetUnscheduledDeps(); 7802 7803 // Handle def-use chain dependencies. 7804 if (BundleMember->OpValue != BundleMember->Inst) { 7805 ScheduleData *UseSD = getScheduleData(BundleMember->Inst); 7806 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) { 7807 BundleMember->Dependencies++; 7808 ScheduleData *DestBundle = UseSD->FirstInBundle; 7809 if (!DestBundle->IsScheduled) 7810 BundleMember->incrementUnscheduledDeps(1); 7811 if (!DestBundle->hasValidDependencies()) 7812 WorkList.push_back(DestBundle); 7813 } 7814 } else { 7815 for (User *U : BundleMember->Inst->users()) { 7816 assert(isa<Instruction>(U) && 7817 "user of instruction must be instruction"); 7818 ScheduleData *UseSD = getScheduleData(U); 7819 if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) { 7820 BundleMember->Dependencies++; 7821 ScheduleData *DestBundle = UseSD->FirstInBundle; 7822 if (!DestBundle->IsScheduled) 7823 BundleMember->incrementUnscheduledDeps(1); 7824 if (!DestBundle->hasValidDependencies()) 7825 WorkList.push_back(DestBundle); 7826 } 7827 } 7828 } 7829 7830 // Handle the memory dependencies (if any). 7831 ScheduleData *DepDest = BundleMember->NextLoadStore; 7832 if (!DepDest) 7833 continue; 7834 Instruction *SrcInst = BundleMember->Inst; 7835 assert(SrcInst->mayReadOrWriteMemory() && 7836 "NextLoadStore list for non memory effecting bundle?"); 7837 MemoryLocation SrcLoc = getLocation(SrcInst); 7838 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory(); 7839 unsigned numAliased = 0; 7840 unsigned DistToSrc = 1; 7841 7842 for ( ; DepDest; DepDest = DepDest->NextLoadStore) { 7843 assert(isInSchedulingRegion(DepDest)); 7844 7845 // We have two limits to reduce the complexity: 7846 // 1) AliasedCheckLimit: It's a small limit to reduce calls to 7847 // SLP->isAliased (which is the expensive part in this loop). 7848 // 2) MaxMemDepDistance: It's for very large blocks and it aborts 7849 // the whole loop (even if the loop is fast, it's quadratic). 7850 // It's important for the loop break condition (see below) to 7851 // check this limit even between two read-only instructions. 7852 if (DistToSrc >= MaxMemDepDistance || 7853 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) && 7854 (numAliased >= AliasedCheckLimit || 7855 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) { 7856 7857 // We increment the counter only if the locations are aliased 7858 // (instead of counting all alias checks). This gives a better 7859 // balance between reduced runtime and accurate dependencies. 7860 numAliased++; 7861 7862 DepDest->MemoryDependencies.push_back(BundleMember); 7863 BundleMember->Dependencies++; 7864 ScheduleData *DestBundle = DepDest->FirstInBundle; 7865 if (!DestBundle->IsScheduled) { 7866 BundleMember->incrementUnscheduledDeps(1); 7867 } 7868 if (!DestBundle->hasValidDependencies()) { 7869 WorkList.push_back(DestBundle); 7870 } 7871 } 7872 7873 // Example, explaining the loop break condition: Let's assume our 7874 // starting instruction is i0 and MaxMemDepDistance = 3. 7875 // 7876 // +--------v--v--v 7877 // i0,i1,i2,i3,i4,i5,i6,i7,i8 7878 // +--------^--^--^ 7879 // 7880 // MaxMemDepDistance let us stop alias-checking at i3 and we add 7881 // dependencies from i0 to i3,i4,.. (even if they are not aliased). 7882 // Previously we already added dependencies from i3 to i6,i7,i8 7883 // (because of MaxMemDepDistance). As we added a dependency from 7884 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8 7885 // and we can abort this loop at i6. 7886 if (DistToSrc >= 2 * MaxMemDepDistance) 7887 break; 7888 DistToSrc++; 7889 } 7890 } 7891 if (InsertInReadyList && SD->isReady()) { 7892 ReadyInsts.insert(SD); 7893 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst 7894 << "\n"); 7895 } 7896 } 7897 } 7898 7899 void BoUpSLP::BlockScheduling::resetSchedule() { 7900 assert(ScheduleStart && 7901 "tried to reset schedule on block which has not been scheduled"); 7902 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 7903 doForAllOpcodes(I, [&](ScheduleData *SD) { 7904 assert(isInSchedulingRegion(SD) && 7905 "ScheduleData not in scheduling region"); 7906 SD->IsScheduled = false; 7907 SD->resetUnscheduledDeps(); 7908 }); 7909 } 7910 ReadyInsts.clear(); 7911 } 7912 7913 void BoUpSLP::scheduleBlock(BlockScheduling *BS) { 7914 if (!BS->ScheduleStart) 7915 return; 7916 7917 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n"); 7918 7919 BS->resetSchedule(); 7920 7921 // For the real scheduling we use a more sophisticated ready-list: it is 7922 // sorted by the original instruction location. This lets the final schedule 7923 // be as close as possible to the original instruction order. 7924 struct ScheduleDataCompare { 7925 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const { 7926 return SD2->SchedulingPriority < SD1->SchedulingPriority; 7927 } 7928 }; 7929 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts; 7930 7931 // Ensure that all dependency data is updated and fill the ready-list with 7932 // initial instructions. 7933 int Idx = 0; 7934 int NumToSchedule = 0; 7935 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; 7936 I = I->getNextNode()) { 7937 BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) { 7938 assert((isVectorLikeInstWithConstOps(SD->Inst) || 7939 SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) && 7940 "scheduler and vectorizer bundle mismatch"); 7941 SD->FirstInBundle->SchedulingPriority = Idx++; 7942 if (SD->isSchedulingEntity()) { 7943 BS->calculateDependencies(SD, false, this); 7944 NumToSchedule++; 7945 } 7946 }); 7947 } 7948 BS->initialFillReadyList(ReadyInsts); 7949 7950 Instruction *LastScheduledInst = BS->ScheduleEnd; 7951 7952 // Do the "real" scheduling. 7953 while (!ReadyInsts.empty()) { 7954 ScheduleData *picked = *ReadyInsts.begin(); 7955 ReadyInsts.erase(ReadyInsts.begin()); 7956 7957 // Move the scheduled instruction(s) to their dedicated places, if not 7958 // there yet. 7959 for (ScheduleData *BundleMember = picked; BundleMember; 7960 BundleMember = BundleMember->NextInBundle) { 7961 Instruction *pickedInst = BundleMember->Inst; 7962 if (pickedInst->getNextNode() != LastScheduledInst) 7963 pickedInst->moveBefore(LastScheduledInst); 7964 LastScheduledInst = pickedInst; 7965 } 7966 7967 BS->schedule(picked, ReadyInsts); 7968 NumToSchedule--; 7969 } 7970 assert(NumToSchedule == 0 && "could not schedule all instructions"); 7971 7972 // Check that we didn't break any of our invariants. 7973 #ifdef EXPENSIVE_CHECKS 7974 BS->verify(); 7975 #endif 7976 7977 // Avoid duplicate scheduling of the block. 7978 BS->ScheduleStart = nullptr; 7979 } 7980 7981 unsigned BoUpSLP::getVectorElementSize(Value *V) { 7982 // If V is a store, just return the width of the stored value (or value 7983 // truncated just before storing) without traversing the expression tree. 7984 // This is the common case. 7985 if (auto *Store = dyn_cast<StoreInst>(V)) { 7986 if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand())) 7987 return DL->getTypeSizeInBits(Trunc->getSrcTy()); 7988 return DL->getTypeSizeInBits(Store->getValueOperand()->getType()); 7989 } 7990 7991 if (auto *IEI = dyn_cast<InsertElementInst>(V)) 7992 return getVectorElementSize(IEI->getOperand(1)); 7993 7994 auto E = InstrElementSize.find(V); 7995 if (E != InstrElementSize.end()) 7996 return E->second; 7997 7998 // If V is not a store, we can traverse the expression tree to find loads 7999 // that feed it. The type of the loaded value may indicate a more suitable 8000 // width than V's type. We want to base the vector element size on the width 8001 // of memory operations where possible. 8002 SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist; 8003 SmallPtrSet<Instruction *, 16> Visited; 8004 if (auto *I = dyn_cast<Instruction>(V)) { 8005 Worklist.emplace_back(I, I->getParent()); 8006 Visited.insert(I); 8007 } 8008 8009 // Traverse the expression tree in bottom-up order looking for loads. If we 8010 // encounter an instruction we don't yet handle, we give up. 8011 auto Width = 0u; 8012 while (!Worklist.empty()) { 8013 Instruction *I; 8014 BasicBlock *Parent; 8015 std::tie(I, Parent) = Worklist.pop_back_val(); 8016 8017 // We should only be looking at scalar instructions here. If the current 8018 // instruction has a vector type, skip. 8019 auto *Ty = I->getType(); 8020 if (isa<VectorType>(Ty)) 8021 continue; 8022 8023 // If the current instruction is a load, update MaxWidth to reflect the 8024 // width of the loaded value. 8025 if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) || 8026 isa<ExtractValueInst>(I)) 8027 Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty)); 8028 8029 // Otherwise, we need to visit the operands of the instruction. We only 8030 // handle the interesting cases from buildTree here. If an operand is an 8031 // instruction we haven't yet visited and from the same basic block as the 8032 // user or the use is a PHI node, we add it to the worklist. 8033 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8034 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) || 8035 isa<UnaryOperator>(I)) { 8036 for (Use &U : I->operands()) 8037 if (auto *J = dyn_cast<Instruction>(U.get())) 8038 if (Visited.insert(J).second && 8039 (isa<PHINode>(I) || J->getParent() == Parent)) 8040 Worklist.emplace_back(J, J->getParent()); 8041 } else { 8042 break; 8043 } 8044 } 8045 8046 // If we didn't encounter a memory access in the expression tree, or if we 8047 // gave up for some reason, just return the width of V. Otherwise, return the 8048 // maximum width we found. 8049 if (!Width) { 8050 if (auto *CI = dyn_cast<CmpInst>(V)) 8051 V = CI->getOperand(0); 8052 Width = DL->getTypeSizeInBits(V->getType()); 8053 } 8054 8055 for (Instruction *I : Visited) 8056 InstrElementSize[I] = Width; 8057 8058 return Width; 8059 } 8060 8061 // Determine if a value V in a vectorizable expression Expr can be demoted to a 8062 // smaller type with a truncation. We collect the values that will be demoted 8063 // in ToDemote and additional roots that require investigating in Roots. 8064 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr, 8065 SmallVectorImpl<Value *> &ToDemote, 8066 SmallVectorImpl<Value *> &Roots) { 8067 // We can always demote constants. 8068 if (isa<Constant>(V)) { 8069 ToDemote.push_back(V); 8070 return true; 8071 } 8072 8073 // If the value is not an instruction in the expression with only one use, it 8074 // cannot be demoted. 8075 auto *I = dyn_cast<Instruction>(V); 8076 if (!I || !I->hasOneUse() || !Expr.count(I)) 8077 return false; 8078 8079 switch (I->getOpcode()) { 8080 8081 // We can always demote truncations and extensions. Since truncations can 8082 // seed additional demotion, we save the truncated value. 8083 case Instruction::Trunc: 8084 Roots.push_back(I->getOperand(0)); 8085 break; 8086 case Instruction::ZExt: 8087 case Instruction::SExt: 8088 if (isa<ExtractElementInst>(I->getOperand(0)) || 8089 isa<InsertElementInst>(I->getOperand(0))) 8090 return false; 8091 break; 8092 8093 // We can demote certain binary operations if we can demote both of their 8094 // operands. 8095 case Instruction::Add: 8096 case Instruction::Sub: 8097 case Instruction::Mul: 8098 case Instruction::And: 8099 case Instruction::Or: 8100 case Instruction::Xor: 8101 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) || 8102 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots)) 8103 return false; 8104 break; 8105 8106 // We can demote selects if we can demote their true and false values. 8107 case Instruction::Select: { 8108 SelectInst *SI = cast<SelectInst>(I); 8109 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) || 8110 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots)) 8111 return false; 8112 break; 8113 } 8114 8115 // We can demote phis if we can demote all their incoming operands. Note that 8116 // we don't need to worry about cycles since we ensure single use above. 8117 case Instruction::PHI: { 8118 PHINode *PN = cast<PHINode>(I); 8119 for (Value *IncValue : PN->incoming_values()) 8120 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots)) 8121 return false; 8122 break; 8123 } 8124 8125 // Otherwise, conservatively give up. 8126 default: 8127 return false; 8128 } 8129 8130 // Record the value that we can demote. 8131 ToDemote.push_back(V); 8132 return true; 8133 } 8134 8135 void BoUpSLP::computeMinimumValueSizes() { 8136 // If there are no external uses, the expression tree must be rooted by a 8137 // store. We can't demote in-memory values, so there is nothing to do here. 8138 if (ExternalUses.empty()) 8139 return; 8140 8141 // We only attempt to truncate integer expressions. 8142 auto &TreeRoot = VectorizableTree[0]->Scalars; 8143 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType()); 8144 if (!TreeRootIT) 8145 return; 8146 8147 // If the expression is not rooted by a store, these roots should have 8148 // external uses. We will rely on InstCombine to rewrite the expression in 8149 // the narrower type. However, InstCombine only rewrites single-use values. 8150 // This means that if a tree entry other than a root is used externally, it 8151 // must have multiple uses and InstCombine will not rewrite it. The code 8152 // below ensures that only the roots are used externally. 8153 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end()); 8154 for (auto &EU : ExternalUses) 8155 if (!Expr.erase(EU.Scalar)) 8156 return; 8157 if (!Expr.empty()) 8158 return; 8159 8160 // Collect the scalar values of the vectorizable expression. We will use this 8161 // context to determine which values can be demoted. If we see a truncation, 8162 // we mark it as seeding another demotion. 8163 for (auto &EntryPtr : VectorizableTree) 8164 Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end()); 8165 8166 // Ensure the roots of the vectorizable tree don't form a cycle. They must 8167 // have a single external user that is not in the vectorizable tree. 8168 for (auto *Root : TreeRoot) 8169 if (!Root->hasOneUse() || Expr.count(*Root->user_begin())) 8170 return; 8171 8172 // Conservatively determine if we can actually truncate the roots of the 8173 // expression. Collect the values that can be demoted in ToDemote and 8174 // additional roots that require investigating in Roots. 8175 SmallVector<Value *, 32> ToDemote; 8176 SmallVector<Value *, 4> Roots; 8177 for (auto *Root : TreeRoot) 8178 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots)) 8179 return; 8180 8181 // The maximum bit width required to represent all the values that can be 8182 // demoted without loss of precision. It would be safe to truncate the roots 8183 // of the expression to this width. 8184 auto MaxBitWidth = 8u; 8185 8186 // We first check if all the bits of the roots are demanded. If they're not, 8187 // we can truncate the roots to this narrower type. 8188 for (auto *Root : TreeRoot) { 8189 auto Mask = DB->getDemandedBits(cast<Instruction>(Root)); 8190 MaxBitWidth = std::max<unsigned>( 8191 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth); 8192 } 8193 8194 // True if the roots can be zero-extended back to their original type, rather 8195 // than sign-extended. We know that if the leading bits are not demanded, we 8196 // can safely zero-extend. So we initialize IsKnownPositive to True. 8197 bool IsKnownPositive = true; 8198 8199 // If all the bits of the roots are demanded, we can try a little harder to 8200 // compute a narrower type. This can happen, for example, if the roots are 8201 // getelementptr indices. InstCombine promotes these indices to the pointer 8202 // width. Thus, all their bits are technically demanded even though the 8203 // address computation might be vectorized in a smaller type. 8204 // 8205 // We start by looking at each entry that can be demoted. We compute the 8206 // maximum bit width required to store the scalar by using ValueTracking to 8207 // compute the number of high-order bits we can truncate. 8208 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) && 8209 llvm::all_of(TreeRoot, [](Value *R) { 8210 assert(R->hasOneUse() && "Root should have only one use!"); 8211 return isa<GetElementPtrInst>(R->user_back()); 8212 })) { 8213 MaxBitWidth = 8u; 8214 8215 // Determine if the sign bit of all the roots is known to be zero. If not, 8216 // IsKnownPositive is set to False. 8217 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) { 8218 KnownBits Known = computeKnownBits(R, *DL); 8219 return Known.isNonNegative(); 8220 }); 8221 8222 // Determine the maximum number of bits required to store the scalar 8223 // values. 8224 for (auto *Scalar : ToDemote) { 8225 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT); 8226 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType()); 8227 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth); 8228 } 8229 8230 // If we can't prove that the sign bit is zero, we must add one to the 8231 // maximum bit width to account for the unknown sign bit. This preserves 8232 // the existing sign bit so we can safely sign-extend the root back to the 8233 // original type. Otherwise, if we know the sign bit is zero, we will 8234 // zero-extend the root instead. 8235 // 8236 // FIXME: This is somewhat suboptimal, as there will be cases where adding 8237 // one to the maximum bit width will yield a larger-than-necessary 8238 // type. In general, we need to add an extra bit only if we can't 8239 // prove that the upper bit of the original type is equal to the 8240 // upper bit of the proposed smaller type. If these two bits are the 8241 // same (either zero or one) we know that sign-extending from the 8242 // smaller type will result in the same value. Here, since we can't 8243 // yet prove this, we are just making the proposed smaller type 8244 // larger to ensure correctness. 8245 if (!IsKnownPositive) 8246 ++MaxBitWidth; 8247 } 8248 8249 // Round MaxBitWidth up to the next power-of-two. 8250 if (!isPowerOf2_64(MaxBitWidth)) 8251 MaxBitWidth = NextPowerOf2(MaxBitWidth); 8252 8253 // If the maximum bit width we compute is less than the with of the roots' 8254 // type, we can proceed with the narrowing. Otherwise, do nothing. 8255 if (MaxBitWidth >= TreeRootIT->getBitWidth()) 8256 return; 8257 8258 // If we can truncate the root, we must collect additional values that might 8259 // be demoted as a result. That is, those seeded by truncations we will 8260 // modify. 8261 while (!Roots.empty()) 8262 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots); 8263 8264 // Finally, map the values we can demote to the maximum bit with we computed. 8265 for (auto *Scalar : ToDemote) 8266 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive); 8267 } 8268 8269 namespace { 8270 8271 /// The SLPVectorizer Pass. 8272 struct SLPVectorizer : public FunctionPass { 8273 SLPVectorizerPass Impl; 8274 8275 /// Pass identification, replacement for typeid 8276 static char ID; 8277 8278 explicit SLPVectorizer() : FunctionPass(ID) { 8279 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); 8280 } 8281 8282 bool doInitialization(Module &M) override { return false; } 8283 8284 bool runOnFunction(Function &F) override { 8285 if (skipFunction(F)) 8286 return false; 8287 8288 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 8289 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 8290 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 8291 auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr; 8292 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 8293 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 8294 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 8295 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 8296 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); 8297 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 8298 8299 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 8300 } 8301 8302 void getAnalysisUsage(AnalysisUsage &AU) const override { 8303 FunctionPass::getAnalysisUsage(AU); 8304 AU.addRequired<AssumptionCacheTracker>(); 8305 AU.addRequired<ScalarEvolutionWrapperPass>(); 8306 AU.addRequired<AAResultsWrapperPass>(); 8307 AU.addRequired<TargetTransformInfoWrapperPass>(); 8308 AU.addRequired<LoopInfoWrapperPass>(); 8309 AU.addRequired<DominatorTreeWrapperPass>(); 8310 AU.addRequired<DemandedBitsWrapperPass>(); 8311 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 8312 AU.addRequired<InjectTLIMappingsLegacy>(); 8313 AU.addPreserved<LoopInfoWrapperPass>(); 8314 AU.addPreserved<DominatorTreeWrapperPass>(); 8315 AU.addPreserved<AAResultsWrapperPass>(); 8316 AU.addPreserved<GlobalsAAWrapperPass>(); 8317 AU.setPreservesCFG(); 8318 } 8319 }; 8320 8321 } // end anonymous namespace 8322 8323 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) { 8324 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 8325 auto *TTI = &AM.getResult<TargetIRAnalysis>(F); 8326 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F); 8327 auto *AA = &AM.getResult<AAManager>(F); 8328 auto *LI = &AM.getResult<LoopAnalysis>(F); 8329 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 8330 auto *AC = &AM.getResult<AssumptionAnalysis>(F); 8331 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F); 8332 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 8333 8334 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 8335 if (!Changed) 8336 return PreservedAnalyses::all(); 8337 8338 PreservedAnalyses PA; 8339 PA.preserveSet<CFGAnalyses>(); 8340 return PA; 8341 } 8342 8343 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_, 8344 TargetTransformInfo *TTI_, 8345 TargetLibraryInfo *TLI_, AAResults *AA_, 8346 LoopInfo *LI_, DominatorTree *DT_, 8347 AssumptionCache *AC_, DemandedBits *DB_, 8348 OptimizationRemarkEmitter *ORE_) { 8349 if (!RunSLPVectorization) 8350 return false; 8351 SE = SE_; 8352 TTI = TTI_; 8353 TLI = TLI_; 8354 AA = AA_; 8355 LI = LI_; 8356 DT = DT_; 8357 AC = AC_; 8358 DB = DB_; 8359 DL = &F.getParent()->getDataLayout(); 8360 8361 Stores.clear(); 8362 GEPs.clear(); 8363 bool Changed = false; 8364 8365 // If the target claims to have no vector registers don't attempt 8366 // vectorization. 8367 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) { 8368 LLVM_DEBUG( 8369 dbgs() << "SLP: Didn't find any vector registers for target, abort.\n"); 8370 return false; 8371 } 8372 8373 // Don't vectorize when the attribute NoImplicitFloat is used. 8374 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) 8375 return false; 8376 8377 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"); 8378 8379 // Use the bottom up slp vectorizer to construct chains that start with 8380 // store instructions. 8381 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_); 8382 8383 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to 8384 // delete instructions. 8385 8386 // Update DFS numbers now so that we can use them for ordering. 8387 DT->updateDFSNumbers(); 8388 8389 // Scan the blocks in the function in post order. 8390 for (auto BB : post_order(&F.getEntryBlock())) { 8391 collectSeedInstructions(BB); 8392 8393 // Vectorize trees that end at stores. 8394 if (!Stores.empty()) { 8395 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size() 8396 << " underlying objects.\n"); 8397 Changed |= vectorizeStoreChains(R); 8398 } 8399 8400 // Vectorize trees that end at reductions. 8401 Changed |= vectorizeChainsInBlock(BB, R); 8402 8403 // Vectorize the index computations of getelementptr instructions. This 8404 // is primarily intended to catch gather-like idioms ending at 8405 // non-consecutive loads. 8406 if (!GEPs.empty()) { 8407 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size() 8408 << " underlying objects.\n"); 8409 Changed |= vectorizeGEPIndices(BB, R); 8410 } 8411 } 8412 8413 if (Changed) { 8414 R.optimizeGatherSequence(); 8415 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n"); 8416 } 8417 return Changed; 8418 } 8419 8420 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R, 8421 unsigned Idx) { 8422 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size() 8423 << "\n"); 8424 const unsigned Sz = R.getVectorElementSize(Chain[0]); 8425 const unsigned MinVF = R.getMinVecRegSize() / Sz; 8426 unsigned VF = Chain.size(); 8427 8428 if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF) 8429 return false; 8430 8431 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx 8432 << "\n"); 8433 8434 R.buildTree(Chain); 8435 if (R.isTreeTinyAndNotFullyVectorizable()) 8436 return false; 8437 if (R.isLoadCombineCandidate()) 8438 return false; 8439 R.reorderTopToBottom(); 8440 R.reorderBottomToTop(); 8441 R.buildExternalUses(); 8442 8443 R.computeMinimumValueSizes(); 8444 8445 InstructionCost Cost = R.getTreeCost(); 8446 8447 LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n"); 8448 if (Cost < -SLPCostThreshold) { 8449 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n"); 8450 8451 using namespace ore; 8452 8453 R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized", 8454 cast<StoreInst>(Chain[0])) 8455 << "Stores SLP vectorized with cost " << NV("Cost", Cost) 8456 << " and with tree size " 8457 << NV("TreeSize", R.getTreeSize())); 8458 8459 R.vectorizeTree(); 8460 return true; 8461 } 8462 8463 return false; 8464 } 8465 8466 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores, 8467 BoUpSLP &R) { 8468 // We may run into multiple chains that merge into a single chain. We mark the 8469 // stores that we vectorized so that we don't visit the same store twice. 8470 BoUpSLP::ValueSet VectorizedStores; 8471 bool Changed = false; 8472 8473 int E = Stores.size(); 8474 SmallBitVector Tails(E, false); 8475 int MaxIter = MaxStoreLookup.getValue(); 8476 SmallVector<std::pair<int, int>, 16> ConsecutiveChain( 8477 E, std::make_pair(E, INT_MAX)); 8478 SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false)); 8479 int IterCnt; 8480 auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter, 8481 &CheckedPairs, 8482 &ConsecutiveChain](int K, int Idx) { 8483 if (IterCnt >= MaxIter) 8484 return true; 8485 if (CheckedPairs[Idx].test(K)) 8486 return ConsecutiveChain[K].second == 1 && 8487 ConsecutiveChain[K].first == Idx; 8488 ++IterCnt; 8489 CheckedPairs[Idx].set(K); 8490 CheckedPairs[K].set(Idx); 8491 Optional<int> Diff = getPointersDiff( 8492 Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(), 8493 Stores[Idx]->getValueOperand()->getType(), 8494 Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true); 8495 if (!Diff || *Diff == 0) 8496 return false; 8497 int Val = *Diff; 8498 if (Val < 0) { 8499 if (ConsecutiveChain[Idx].second > -Val) { 8500 Tails.set(K); 8501 ConsecutiveChain[Idx] = std::make_pair(K, -Val); 8502 } 8503 return false; 8504 } 8505 if (ConsecutiveChain[K].second <= Val) 8506 return false; 8507 8508 Tails.set(Idx); 8509 ConsecutiveChain[K] = std::make_pair(Idx, Val); 8510 return Val == 1; 8511 }; 8512 // Do a quadratic search on all of the given stores in reverse order and find 8513 // all of the pairs of stores that follow each other. 8514 for (int Idx = E - 1; Idx >= 0; --Idx) { 8515 // If a store has multiple consecutive store candidates, search according 8516 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ... 8517 // This is because usually pairing with immediate succeeding or preceding 8518 // candidate create the best chance to find slp vectorization opportunity. 8519 const int MaxLookDepth = std::max(E - Idx, Idx + 1); 8520 IterCnt = 0; 8521 for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset) 8522 if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) || 8523 (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx))) 8524 break; 8525 } 8526 8527 // Tracks if we tried to vectorize stores starting from the given tail 8528 // already. 8529 SmallBitVector TriedTails(E, false); 8530 // For stores that start but don't end a link in the chain: 8531 for (int Cnt = E; Cnt > 0; --Cnt) { 8532 int I = Cnt - 1; 8533 if (ConsecutiveChain[I].first == E || Tails.test(I)) 8534 continue; 8535 // We found a store instr that starts a chain. Now follow the chain and try 8536 // to vectorize it. 8537 BoUpSLP::ValueList Operands; 8538 // Collect the chain into a list. 8539 while (I != E && !VectorizedStores.count(Stores[I])) { 8540 Operands.push_back(Stores[I]); 8541 Tails.set(I); 8542 if (ConsecutiveChain[I].second != 1) { 8543 // Mark the new end in the chain and go back, if required. It might be 8544 // required if the original stores come in reversed order, for example. 8545 if (ConsecutiveChain[I].first != E && 8546 Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) && 8547 !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) { 8548 TriedTails.set(I); 8549 Tails.reset(ConsecutiveChain[I].first); 8550 if (Cnt < ConsecutiveChain[I].first + 2) 8551 Cnt = ConsecutiveChain[I].first + 2; 8552 } 8553 break; 8554 } 8555 // Move to the next value in the chain. 8556 I = ConsecutiveChain[I].first; 8557 } 8558 assert(!Operands.empty() && "Expected non-empty list of stores."); 8559 8560 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 8561 unsigned EltSize = R.getVectorElementSize(Operands[0]); 8562 unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize); 8563 8564 unsigned MinVF = R.getMinVF(EltSize); 8565 unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store), 8566 MaxElts); 8567 8568 // FIXME: Is division-by-2 the correct step? Should we assert that the 8569 // register size is a power-of-2? 8570 unsigned StartIdx = 0; 8571 for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) { 8572 for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) { 8573 ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size); 8574 if (!VectorizedStores.count(Slice.front()) && 8575 !VectorizedStores.count(Slice.back()) && 8576 vectorizeStoreChain(Slice, R, Cnt)) { 8577 // Mark the vectorized stores so that we don't vectorize them again. 8578 VectorizedStores.insert(Slice.begin(), Slice.end()); 8579 Changed = true; 8580 // If we vectorized initial block, no need to try to vectorize it 8581 // again. 8582 if (Cnt == StartIdx) 8583 StartIdx += Size; 8584 Cnt += Size; 8585 continue; 8586 } 8587 ++Cnt; 8588 } 8589 // Check if the whole array was vectorized already - exit. 8590 if (StartIdx >= Operands.size()) 8591 break; 8592 } 8593 } 8594 8595 return Changed; 8596 } 8597 8598 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) { 8599 // Initialize the collections. We will make a single pass over the block. 8600 Stores.clear(); 8601 GEPs.clear(); 8602 8603 // Visit the store and getelementptr instructions in BB and organize them in 8604 // Stores and GEPs according to the underlying objects of their pointer 8605 // operands. 8606 for (Instruction &I : *BB) { 8607 // Ignore store instructions that are volatile or have a pointer operand 8608 // that doesn't point to a scalar type. 8609 if (auto *SI = dyn_cast<StoreInst>(&I)) { 8610 if (!SI->isSimple()) 8611 continue; 8612 if (!isValidElementType(SI->getValueOperand()->getType())) 8613 continue; 8614 Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI); 8615 } 8616 8617 // Ignore getelementptr instructions that have more than one index, a 8618 // constant index, or a pointer operand that doesn't point to a scalar 8619 // type. 8620 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 8621 auto Idx = GEP->idx_begin()->get(); 8622 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx)) 8623 continue; 8624 if (!isValidElementType(Idx->getType())) 8625 continue; 8626 if (GEP->getType()->isVectorTy()) 8627 continue; 8628 GEPs[GEP->getPointerOperand()].push_back(GEP); 8629 } 8630 } 8631 } 8632 8633 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { 8634 if (!A || !B) 8635 return false; 8636 Value *VL[] = {A, B}; 8637 return tryToVectorizeList(VL, R); 8638 } 8639 8640 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, 8641 bool LimitForRegisterSize) { 8642 if (VL.size() < 2) 8643 return false; 8644 8645 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " 8646 << VL.size() << ".\n"); 8647 8648 // Check that all of the parts are instructions of the same type, 8649 // we permit an alternate opcode via InstructionsState. 8650 InstructionsState S = getSameOpcode(VL); 8651 if (!S.getOpcode()) 8652 return false; 8653 8654 Instruction *I0 = cast<Instruction>(S.OpValue); 8655 // Make sure invalid types (including vector type) are rejected before 8656 // determining vectorization factor for scalar instructions. 8657 for (Value *V : VL) { 8658 Type *Ty = V->getType(); 8659 if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) { 8660 // NOTE: the following will give user internal llvm type name, which may 8661 // not be useful. 8662 R.getORE()->emit([&]() { 8663 std::string type_str; 8664 llvm::raw_string_ostream rso(type_str); 8665 Ty->print(rso); 8666 return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0) 8667 << "Cannot SLP vectorize list: type " 8668 << rso.str() + " is unsupported by vectorizer"; 8669 }); 8670 return false; 8671 } 8672 } 8673 8674 unsigned Sz = R.getVectorElementSize(I0); 8675 unsigned MinVF = R.getMinVF(Sz); 8676 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF); 8677 MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF); 8678 if (MaxVF < 2) { 8679 R.getORE()->emit([&]() { 8680 return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0) 8681 << "Cannot SLP vectorize list: vectorization factor " 8682 << "less than 2 is not supported"; 8683 }); 8684 return false; 8685 } 8686 8687 bool Changed = false; 8688 bool CandidateFound = false; 8689 InstructionCost MinCost = SLPCostThreshold.getValue(); 8690 Type *ScalarTy = VL[0]->getType(); 8691 if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 8692 ScalarTy = IE->getOperand(1)->getType(); 8693 8694 unsigned NextInst = 0, MaxInst = VL.size(); 8695 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) { 8696 // No actual vectorization should happen, if number of parts is the same as 8697 // provided vectorization factor (i.e. the scalar type is used for vector 8698 // code during codegen). 8699 auto *VecTy = FixedVectorType::get(ScalarTy, VF); 8700 if (TTI->getNumberOfParts(VecTy) == VF) 8701 continue; 8702 for (unsigned I = NextInst; I < MaxInst; ++I) { 8703 unsigned OpsWidth = 0; 8704 8705 if (I + VF > MaxInst) 8706 OpsWidth = MaxInst - I; 8707 else 8708 OpsWidth = VF; 8709 8710 if (!isPowerOf2_32(OpsWidth)) 8711 continue; 8712 8713 if ((LimitForRegisterSize && OpsWidth < MaxVF) || 8714 (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2)) 8715 break; 8716 8717 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth); 8718 // Check that a previous iteration of this loop did not delete the Value. 8719 if (llvm::any_of(Ops, [&R](Value *V) { 8720 auto *I = dyn_cast<Instruction>(V); 8721 return I && R.isDeleted(I); 8722 })) 8723 continue; 8724 8725 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " 8726 << "\n"); 8727 8728 R.buildTree(Ops); 8729 if (R.isTreeTinyAndNotFullyVectorizable()) 8730 continue; 8731 R.reorderTopToBottom(); 8732 R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front())); 8733 R.buildExternalUses(); 8734 8735 R.computeMinimumValueSizes(); 8736 InstructionCost Cost = R.getTreeCost(); 8737 CandidateFound = true; 8738 MinCost = std::min(MinCost, Cost); 8739 8740 if (Cost < -SLPCostThreshold) { 8741 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n"); 8742 R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList", 8743 cast<Instruction>(Ops[0])) 8744 << "SLP vectorized with cost " << ore::NV("Cost", Cost) 8745 << " and with tree size " 8746 << ore::NV("TreeSize", R.getTreeSize())); 8747 8748 R.vectorizeTree(); 8749 // Move to the next bundle. 8750 I += VF - 1; 8751 NextInst = I + 1; 8752 Changed = true; 8753 } 8754 } 8755 } 8756 8757 if (!Changed && CandidateFound) { 8758 R.getORE()->emit([&]() { 8759 return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0) 8760 << "List vectorization was possible but not beneficial with cost " 8761 << ore::NV("Cost", MinCost) << " >= " 8762 << ore::NV("Treshold", -SLPCostThreshold); 8763 }); 8764 } else if (!Changed) { 8765 R.getORE()->emit([&]() { 8766 return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0) 8767 << "Cannot SLP vectorize list: vectorization was impossible" 8768 << " with available vectorization factors"; 8769 }); 8770 } 8771 return Changed; 8772 } 8773 8774 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) { 8775 if (!I) 8776 return false; 8777 8778 if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) 8779 return false; 8780 8781 Value *P = I->getParent(); 8782 8783 // Vectorize in current basic block only. 8784 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0)); 8785 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1)); 8786 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P) 8787 return false; 8788 8789 // Try to vectorize V. 8790 if (tryToVectorizePair(Op0, Op1, R)) 8791 return true; 8792 8793 auto *A = dyn_cast<BinaryOperator>(Op0); 8794 auto *B = dyn_cast<BinaryOperator>(Op1); 8795 // Try to skip B. 8796 if (B && B->hasOneUse()) { 8797 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); 8798 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); 8799 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R)) 8800 return true; 8801 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R)) 8802 return true; 8803 } 8804 8805 // Try to skip A. 8806 if (A && A->hasOneUse()) { 8807 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); 8808 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); 8809 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R)) 8810 return true; 8811 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R)) 8812 return true; 8813 } 8814 return false; 8815 } 8816 8817 namespace { 8818 8819 /// Model horizontal reductions. 8820 /// 8821 /// A horizontal reduction is a tree of reduction instructions that has values 8822 /// that can be put into a vector as its leaves. For example: 8823 /// 8824 /// mul mul mul mul 8825 /// \ / \ / 8826 /// + + 8827 /// \ / 8828 /// + 8829 /// This tree has "mul" as its leaf values and "+" as its reduction 8830 /// instructions. A reduction can feed into a store or a binary operation 8831 /// feeding a phi. 8832 /// ... 8833 /// \ / 8834 /// + 8835 /// | 8836 /// phi += 8837 /// 8838 /// Or: 8839 /// ... 8840 /// \ / 8841 /// + 8842 /// | 8843 /// *p = 8844 /// 8845 class HorizontalReduction { 8846 using ReductionOpsType = SmallVector<Value *, 16>; 8847 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>; 8848 ReductionOpsListType ReductionOps; 8849 SmallVector<Value *, 32> ReducedVals; 8850 // Use map vector to make stable output. 8851 MapVector<Instruction *, Value *> ExtraArgs; 8852 WeakTrackingVH ReductionRoot; 8853 /// The type of reduction operation. 8854 RecurKind RdxKind; 8855 8856 const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max(); 8857 8858 static bool isCmpSelMinMax(Instruction *I) { 8859 return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) && 8860 RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I)); 8861 } 8862 8863 // And/or are potentially poison-safe logical patterns like: 8864 // select x, y, false 8865 // select x, true, y 8866 static bool isBoolLogicOp(Instruction *I) { 8867 return match(I, m_LogicalAnd(m_Value(), m_Value())) || 8868 match(I, m_LogicalOr(m_Value(), m_Value())); 8869 } 8870 8871 /// Checks if instruction is associative and can be vectorized. 8872 static bool isVectorizable(RecurKind Kind, Instruction *I) { 8873 if (Kind == RecurKind::None) 8874 return false; 8875 8876 // Integer ops that map to select instructions or intrinsics are fine. 8877 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) || 8878 isBoolLogicOp(I)) 8879 return true; 8880 8881 if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) { 8882 // FP min/max are associative except for NaN and -0.0. We do not 8883 // have to rule out -0.0 here because the intrinsic semantics do not 8884 // specify a fixed result for it. 8885 return I->getFastMathFlags().noNaNs(); 8886 } 8887 8888 return I->isAssociative(); 8889 } 8890 8891 static Value *getRdxOperand(Instruction *I, unsigned Index) { 8892 // Poison-safe 'or' takes the form: select X, true, Y 8893 // To make that work with the normal operand processing, we skip the 8894 // true value operand. 8895 // TODO: Change the code and data structures to handle this without a hack. 8896 if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1) 8897 return I->getOperand(2); 8898 return I->getOperand(Index); 8899 } 8900 8901 /// Checks if the ParentStackElem.first should be marked as a reduction 8902 /// operation with an extra argument or as extra argument itself. 8903 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem, 8904 Value *ExtraArg) { 8905 if (ExtraArgs.count(ParentStackElem.first)) { 8906 ExtraArgs[ParentStackElem.first] = nullptr; 8907 // We ran into something like: 8908 // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg. 8909 // The whole ParentStackElem.first should be considered as an extra value 8910 // in this case. 8911 // Do not perform analysis of remaining operands of ParentStackElem.first 8912 // instruction, this whole instruction is an extra argument. 8913 ParentStackElem.second = INVALID_OPERAND_INDEX; 8914 } else { 8915 // We ran into something like: 8916 // ParentStackElem.first += ... + ExtraArg + ... 8917 ExtraArgs[ParentStackElem.first] = ExtraArg; 8918 } 8919 } 8920 8921 /// Creates reduction operation with the current opcode. 8922 static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS, 8923 Value *RHS, const Twine &Name, bool UseSelect) { 8924 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind); 8925 switch (Kind) { 8926 case RecurKind::Or: 8927 if (UseSelect && 8928 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 8929 return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name); 8930 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8931 Name); 8932 case RecurKind::And: 8933 if (UseSelect && 8934 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 8935 return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name); 8936 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8937 Name); 8938 case RecurKind::Add: 8939 case RecurKind::Mul: 8940 case RecurKind::Xor: 8941 case RecurKind::FAdd: 8942 case RecurKind::FMul: 8943 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 8944 Name); 8945 case RecurKind::FMax: 8946 return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS); 8947 case RecurKind::FMin: 8948 return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS); 8949 case RecurKind::SMax: 8950 if (UseSelect) { 8951 Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name); 8952 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8953 } 8954 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS); 8955 case RecurKind::SMin: 8956 if (UseSelect) { 8957 Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name); 8958 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8959 } 8960 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS); 8961 case RecurKind::UMax: 8962 if (UseSelect) { 8963 Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name); 8964 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8965 } 8966 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS); 8967 case RecurKind::UMin: 8968 if (UseSelect) { 8969 Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name); 8970 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 8971 } 8972 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS); 8973 default: 8974 llvm_unreachable("Unknown reduction operation."); 8975 } 8976 } 8977 8978 /// Creates reduction operation with the current opcode with the IR flags 8979 /// from \p ReductionOps. 8980 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 8981 Value *RHS, const Twine &Name, 8982 const ReductionOpsListType &ReductionOps) { 8983 bool UseSelect = ReductionOps.size() == 2 || 8984 // Logical or/and. 8985 (ReductionOps.size() == 1 && 8986 isa<SelectInst>(ReductionOps.front().front())); 8987 assert((!UseSelect || ReductionOps.size() != 2 || 8988 isa<SelectInst>(ReductionOps[1][0])) && 8989 "Expected cmp + select pairs for reduction"); 8990 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect); 8991 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 8992 if (auto *Sel = dyn_cast<SelectInst>(Op)) { 8993 propagateIRFlags(Sel->getCondition(), ReductionOps[0]); 8994 propagateIRFlags(Op, ReductionOps[1]); 8995 return Op; 8996 } 8997 } 8998 propagateIRFlags(Op, ReductionOps[0]); 8999 return Op; 9000 } 9001 9002 /// Creates reduction operation with the current opcode with the IR flags 9003 /// from \p I. 9004 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 9005 Value *RHS, const Twine &Name, Instruction *I) { 9006 auto *SelI = dyn_cast<SelectInst>(I); 9007 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr); 9008 if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 9009 if (auto *Sel = dyn_cast<SelectInst>(Op)) 9010 propagateIRFlags(Sel->getCondition(), SelI->getCondition()); 9011 } 9012 propagateIRFlags(Op, I); 9013 return Op; 9014 } 9015 9016 static RecurKind getRdxKind(Instruction *I) { 9017 assert(I && "Expected instruction for reduction matching"); 9018 if (match(I, m_Add(m_Value(), m_Value()))) 9019 return RecurKind::Add; 9020 if (match(I, m_Mul(m_Value(), m_Value()))) 9021 return RecurKind::Mul; 9022 if (match(I, m_And(m_Value(), m_Value())) || 9023 match(I, m_LogicalAnd(m_Value(), m_Value()))) 9024 return RecurKind::And; 9025 if (match(I, m_Or(m_Value(), m_Value())) || 9026 match(I, m_LogicalOr(m_Value(), m_Value()))) 9027 return RecurKind::Or; 9028 if (match(I, m_Xor(m_Value(), m_Value()))) 9029 return RecurKind::Xor; 9030 if (match(I, m_FAdd(m_Value(), m_Value()))) 9031 return RecurKind::FAdd; 9032 if (match(I, m_FMul(m_Value(), m_Value()))) 9033 return RecurKind::FMul; 9034 9035 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value()))) 9036 return RecurKind::FMax; 9037 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value()))) 9038 return RecurKind::FMin; 9039 9040 // This matches either cmp+select or intrinsics. SLP is expected to handle 9041 // either form. 9042 // TODO: If we are canonicalizing to intrinsics, we can remove several 9043 // special-case paths that deal with selects. 9044 if (match(I, m_SMax(m_Value(), m_Value()))) 9045 return RecurKind::SMax; 9046 if (match(I, m_SMin(m_Value(), m_Value()))) 9047 return RecurKind::SMin; 9048 if (match(I, m_UMax(m_Value(), m_Value()))) 9049 return RecurKind::UMax; 9050 if (match(I, m_UMin(m_Value(), m_Value()))) 9051 return RecurKind::UMin; 9052 9053 if (auto *Select = dyn_cast<SelectInst>(I)) { 9054 // Try harder: look for min/max pattern based on instructions producing 9055 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2). 9056 // During the intermediate stages of SLP, it's very common to have 9057 // pattern like this (since optimizeGatherSequence is run only once 9058 // at the end): 9059 // %1 = extractelement <2 x i32> %a, i32 0 9060 // %2 = extractelement <2 x i32> %a, i32 1 9061 // %cond = icmp sgt i32 %1, %2 9062 // %3 = extractelement <2 x i32> %a, i32 0 9063 // %4 = extractelement <2 x i32> %a, i32 1 9064 // %select = select i1 %cond, i32 %3, i32 %4 9065 CmpInst::Predicate Pred; 9066 Instruction *L1; 9067 Instruction *L2; 9068 9069 Value *LHS = Select->getTrueValue(); 9070 Value *RHS = Select->getFalseValue(); 9071 Value *Cond = Select->getCondition(); 9072 9073 // TODO: Support inverse predicates. 9074 if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) { 9075 if (!isa<ExtractElementInst>(RHS) || 9076 !L2->isIdenticalTo(cast<Instruction>(RHS))) 9077 return RecurKind::None; 9078 } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) { 9079 if (!isa<ExtractElementInst>(LHS) || 9080 !L1->isIdenticalTo(cast<Instruction>(LHS))) 9081 return RecurKind::None; 9082 } else { 9083 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS)) 9084 return RecurKind::None; 9085 if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) || 9086 !L1->isIdenticalTo(cast<Instruction>(LHS)) || 9087 !L2->isIdenticalTo(cast<Instruction>(RHS))) 9088 return RecurKind::None; 9089 } 9090 9091 switch (Pred) { 9092 default: 9093 return RecurKind::None; 9094 case CmpInst::ICMP_SGT: 9095 case CmpInst::ICMP_SGE: 9096 return RecurKind::SMax; 9097 case CmpInst::ICMP_SLT: 9098 case CmpInst::ICMP_SLE: 9099 return RecurKind::SMin; 9100 case CmpInst::ICMP_UGT: 9101 case CmpInst::ICMP_UGE: 9102 return RecurKind::UMax; 9103 case CmpInst::ICMP_ULT: 9104 case CmpInst::ICMP_ULE: 9105 return RecurKind::UMin; 9106 } 9107 } 9108 return RecurKind::None; 9109 } 9110 9111 /// Get the index of the first operand. 9112 static unsigned getFirstOperandIndex(Instruction *I) { 9113 return isCmpSelMinMax(I) ? 1 : 0; 9114 } 9115 9116 /// Total number of operands in the reduction operation. 9117 static unsigned getNumberOfOperands(Instruction *I) { 9118 return isCmpSelMinMax(I) ? 3 : 2; 9119 } 9120 9121 /// Checks if the instruction is in basic block \p BB. 9122 /// For a cmp+sel min/max reduction check that both ops are in \p BB. 9123 static bool hasSameParent(Instruction *I, BasicBlock *BB) { 9124 if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) { 9125 auto *Sel = cast<SelectInst>(I); 9126 auto *Cmp = dyn_cast<Instruction>(Sel->getCondition()); 9127 return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB; 9128 } 9129 return I->getParent() == BB; 9130 } 9131 9132 /// Expected number of uses for reduction operations/reduced values. 9133 static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) { 9134 if (IsCmpSelMinMax) { 9135 // SelectInst must be used twice while the condition op must have single 9136 // use only. 9137 if (auto *Sel = dyn_cast<SelectInst>(I)) 9138 return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse(); 9139 return I->hasNUses(2); 9140 } 9141 9142 // Arithmetic reduction operation must be used once only. 9143 return I->hasOneUse(); 9144 } 9145 9146 /// Initializes the list of reduction operations. 9147 void initReductionOps(Instruction *I) { 9148 if (isCmpSelMinMax(I)) 9149 ReductionOps.assign(2, ReductionOpsType()); 9150 else 9151 ReductionOps.assign(1, ReductionOpsType()); 9152 } 9153 9154 /// Add all reduction operations for the reduction instruction \p I. 9155 void addReductionOps(Instruction *I) { 9156 if (isCmpSelMinMax(I)) { 9157 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition()); 9158 ReductionOps[1].emplace_back(I); 9159 } else { 9160 ReductionOps[0].emplace_back(I); 9161 } 9162 } 9163 9164 static Value *getLHS(RecurKind Kind, Instruction *I) { 9165 if (Kind == RecurKind::None) 9166 return nullptr; 9167 return I->getOperand(getFirstOperandIndex(I)); 9168 } 9169 static Value *getRHS(RecurKind Kind, Instruction *I) { 9170 if (Kind == RecurKind::None) 9171 return nullptr; 9172 return I->getOperand(getFirstOperandIndex(I) + 1); 9173 } 9174 9175 public: 9176 HorizontalReduction() = default; 9177 9178 /// Try to find a reduction tree. 9179 bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) { 9180 assert((!Phi || is_contained(Phi->operands(), Inst)) && 9181 "Phi needs to use the binary operator"); 9182 assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || 9183 isa<IntrinsicInst>(Inst)) && 9184 "Expected binop, select, or intrinsic for reduction matching"); 9185 RdxKind = getRdxKind(Inst); 9186 9187 // We could have a initial reductions that is not an add. 9188 // r *= v1 + v2 + v3 + v4 9189 // In such a case start looking for a tree rooted in the first '+'. 9190 if (Phi) { 9191 if (getLHS(RdxKind, Inst) == Phi) { 9192 Phi = nullptr; 9193 Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst)); 9194 if (!Inst) 9195 return false; 9196 RdxKind = getRdxKind(Inst); 9197 } else if (getRHS(RdxKind, Inst) == Phi) { 9198 Phi = nullptr; 9199 Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst)); 9200 if (!Inst) 9201 return false; 9202 RdxKind = getRdxKind(Inst); 9203 } 9204 } 9205 9206 if (!isVectorizable(RdxKind, Inst)) 9207 return false; 9208 9209 // Analyze "regular" integer/FP types for reductions - no target-specific 9210 // types or pointers. 9211 Type *Ty = Inst->getType(); 9212 if (!isValidElementType(Ty) || Ty->isPointerTy()) 9213 return false; 9214 9215 // Though the ultimate reduction may have multiple uses, its condition must 9216 // have only single use. 9217 if (auto *Sel = dyn_cast<SelectInst>(Inst)) 9218 if (!Sel->getCondition()->hasOneUse()) 9219 return false; 9220 9221 ReductionRoot = Inst; 9222 9223 // The opcode for leaf values that we perform a reduction on. 9224 // For example: load(x) + load(y) + load(z) + fptoui(w) 9225 // The leaf opcode for 'w' does not match, so we don't include it as a 9226 // potential candidate for the reduction. 9227 unsigned LeafOpcode = 0; 9228 9229 // Post-order traverse the reduction tree starting at Inst. We only handle 9230 // true trees containing binary operators or selects. 9231 SmallVector<std::pair<Instruction *, unsigned>, 32> Stack; 9232 Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst))); 9233 initReductionOps(Inst); 9234 while (!Stack.empty()) { 9235 Instruction *TreeN = Stack.back().first; 9236 unsigned EdgeToVisit = Stack.back().second++; 9237 const RecurKind TreeRdxKind = getRdxKind(TreeN); 9238 bool IsReducedValue = TreeRdxKind != RdxKind; 9239 9240 // Postorder visit. 9241 if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) { 9242 if (IsReducedValue) 9243 ReducedVals.push_back(TreeN); 9244 else { 9245 auto ExtraArgsIter = ExtraArgs.find(TreeN); 9246 if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) { 9247 // Check if TreeN is an extra argument of its parent operation. 9248 if (Stack.size() <= 1) { 9249 // TreeN can't be an extra argument as it is a root reduction 9250 // operation. 9251 return false; 9252 } 9253 // Yes, TreeN is an extra argument, do not add it to a list of 9254 // reduction operations. 9255 // Stack[Stack.size() - 2] always points to the parent operation. 9256 markExtraArg(Stack[Stack.size() - 2], TreeN); 9257 ExtraArgs.erase(TreeN); 9258 } else 9259 addReductionOps(TreeN); 9260 } 9261 // Retract. 9262 Stack.pop_back(); 9263 continue; 9264 } 9265 9266 // Visit operands. 9267 Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit); 9268 auto *EdgeInst = dyn_cast<Instruction>(EdgeVal); 9269 if (!EdgeInst) { 9270 // Edge value is not a reduction instruction or a leaf instruction. 9271 // (It may be a constant, function argument, or something else.) 9272 markExtraArg(Stack.back(), EdgeVal); 9273 continue; 9274 } 9275 RecurKind EdgeRdxKind = getRdxKind(EdgeInst); 9276 // Continue analysis if the next operand is a reduction operation or 9277 // (possibly) a leaf value. If the leaf value opcode is not set, 9278 // the first met operation != reduction operation is considered as the 9279 // leaf opcode. 9280 // Only handle trees in the current basic block. 9281 // Each tree node needs to have minimal number of users except for the 9282 // ultimate reduction. 9283 const bool IsRdxInst = EdgeRdxKind == RdxKind; 9284 if (EdgeInst != Phi && EdgeInst != Inst && 9285 hasSameParent(EdgeInst, Inst->getParent()) && 9286 hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) && 9287 (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) { 9288 if (IsRdxInst) { 9289 // We need to be able to reassociate the reduction operations. 9290 if (!isVectorizable(EdgeRdxKind, EdgeInst)) { 9291 // I is an extra argument for TreeN (its parent operation). 9292 markExtraArg(Stack.back(), EdgeInst); 9293 continue; 9294 } 9295 } else if (!LeafOpcode) { 9296 LeafOpcode = EdgeInst->getOpcode(); 9297 } 9298 Stack.push_back( 9299 std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst))); 9300 continue; 9301 } 9302 // I is an extra argument for TreeN (its parent operation). 9303 markExtraArg(Stack.back(), EdgeInst); 9304 } 9305 return true; 9306 } 9307 9308 /// Attempt to vectorize the tree found by matchAssociativeReduction. 9309 Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) { 9310 // If there are a sufficient number of reduction values, reduce 9311 // to a nearby power-of-2. We can safely generate oversized 9312 // vectors and rely on the backend to split them to legal sizes. 9313 unsigned NumReducedVals = ReducedVals.size(); 9314 if (NumReducedVals < 4) 9315 return nullptr; 9316 9317 // Intersect the fast-math-flags from all reduction operations. 9318 FastMathFlags RdxFMF; 9319 RdxFMF.set(); 9320 for (ReductionOpsType &RdxOp : ReductionOps) { 9321 for (Value *RdxVal : RdxOp) { 9322 if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal)) 9323 RdxFMF &= FPMO->getFastMathFlags(); 9324 } 9325 } 9326 9327 IRBuilder<> Builder(cast<Instruction>(ReductionRoot)); 9328 Builder.setFastMathFlags(RdxFMF); 9329 9330 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues; 9331 // The same extra argument may be used several times, so log each attempt 9332 // to use it. 9333 for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) { 9334 assert(Pair.first && "DebugLoc must be set."); 9335 ExternallyUsedValues[Pair.second].push_back(Pair.first); 9336 } 9337 9338 // The compare instruction of a min/max is the insertion point for new 9339 // instructions and may be replaced with a new compare instruction. 9340 auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) { 9341 assert(isa<SelectInst>(RdxRootInst) && 9342 "Expected min/max reduction to have select root instruction"); 9343 Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition(); 9344 assert(isa<Instruction>(ScalarCond) && 9345 "Expected min/max reduction to have compare condition"); 9346 return cast<Instruction>(ScalarCond); 9347 }; 9348 9349 // The reduction root is used as the insertion point for new instructions, 9350 // so set it as externally used to prevent it from being deleted. 9351 ExternallyUsedValues[ReductionRoot]; 9352 SmallVector<Value *, 16> IgnoreList; 9353 for (ReductionOpsType &RdxOp : ReductionOps) 9354 IgnoreList.append(RdxOp.begin(), RdxOp.end()); 9355 9356 unsigned ReduxWidth = PowerOf2Floor(NumReducedVals); 9357 if (NumReducedVals > ReduxWidth) { 9358 // In the loop below, we are building a tree based on a window of 9359 // 'ReduxWidth' values. 9360 // If the operands of those values have common traits (compare predicate, 9361 // constant operand, etc), then we want to group those together to 9362 // minimize the cost of the reduction. 9363 9364 // TODO: This should be extended to count common operands for 9365 // compares and binops. 9366 9367 // Step 1: Count the number of times each compare predicate occurs. 9368 SmallDenseMap<unsigned, unsigned> PredCountMap; 9369 for (Value *RdxVal : ReducedVals) { 9370 CmpInst::Predicate Pred; 9371 if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value()))) 9372 ++PredCountMap[Pred]; 9373 } 9374 // Step 2: Sort the values so the most common predicates come first. 9375 stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) { 9376 CmpInst::Predicate PredA, PredB; 9377 if (match(A, m_Cmp(PredA, m_Value(), m_Value())) && 9378 match(B, m_Cmp(PredB, m_Value(), m_Value()))) { 9379 return PredCountMap[PredA] > PredCountMap[PredB]; 9380 } 9381 return false; 9382 }); 9383 } 9384 9385 Value *VectorizedTree = nullptr; 9386 unsigned i = 0; 9387 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) { 9388 ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth); 9389 V.buildTree(VL, IgnoreList); 9390 if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) 9391 break; 9392 if (V.isLoadCombineReductionCandidate(RdxKind)) 9393 break; 9394 V.reorderTopToBottom(); 9395 V.reorderBottomToTop(/*IgnoreReorder=*/true); 9396 V.buildExternalUses(ExternallyUsedValues); 9397 9398 // For a poison-safe boolean logic reduction, do not replace select 9399 // instructions with logic ops. All reduced values will be frozen (see 9400 // below) to prevent leaking poison. 9401 if (isa<SelectInst>(ReductionRoot) && 9402 isBoolLogicOp(cast<Instruction>(ReductionRoot)) && 9403 NumReducedVals != ReduxWidth) 9404 break; 9405 9406 V.computeMinimumValueSizes(); 9407 9408 // Estimate cost. 9409 InstructionCost TreeCost = 9410 V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth)); 9411 InstructionCost ReductionCost = 9412 getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF); 9413 InstructionCost Cost = TreeCost + ReductionCost; 9414 if (!Cost.isValid()) { 9415 LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n"); 9416 return nullptr; 9417 } 9418 if (Cost >= -SLPCostThreshold) { 9419 V.getORE()->emit([&]() { 9420 return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial", 9421 cast<Instruction>(VL[0])) 9422 << "Vectorizing horizontal reduction is possible" 9423 << "but not beneficial with cost " << ore::NV("Cost", Cost) 9424 << " and threshold " 9425 << ore::NV("Threshold", -SLPCostThreshold); 9426 }); 9427 break; 9428 } 9429 9430 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" 9431 << Cost << ". (HorRdx)\n"); 9432 V.getORE()->emit([&]() { 9433 return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction", 9434 cast<Instruction>(VL[0])) 9435 << "Vectorized horizontal reduction with cost " 9436 << ore::NV("Cost", Cost) << " and with tree size " 9437 << ore::NV("TreeSize", V.getTreeSize()); 9438 }); 9439 9440 // Vectorize a tree. 9441 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc(); 9442 Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues); 9443 9444 // Emit a reduction. If the root is a select (min/max idiom), the insert 9445 // point is the compare condition of that select. 9446 Instruction *RdxRootInst = cast<Instruction>(ReductionRoot); 9447 if (isCmpSelMinMax(RdxRootInst)) 9448 Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst)); 9449 else 9450 Builder.SetInsertPoint(RdxRootInst); 9451 9452 // To prevent poison from leaking across what used to be sequential, safe, 9453 // scalar boolean logic operations, the reduction operand must be frozen. 9454 if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst)) 9455 VectorizedRoot = Builder.CreateFreeze(VectorizedRoot); 9456 9457 Value *ReducedSubTree = 9458 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI); 9459 9460 if (!VectorizedTree) { 9461 // Initialize the final value in the reduction. 9462 VectorizedTree = ReducedSubTree; 9463 } else { 9464 // Update the final value in the reduction. 9465 Builder.SetCurrentDebugLocation(Loc); 9466 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 9467 ReducedSubTree, "op.rdx", ReductionOps); 9468 } 9469 i += ReduxWidth; 9470 ReduxWidth = PowerOf2Floor(NumReducedVals - i); 9471 } 9472 9473 if (VectorizedTree) { 9474 // Finish the reduction. 9475 for (; i < NumReducedVals; ++i) { 9476 auto *I = cast<Instruction>(ReducedVals[i]); 9477 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 9478 VectorizedTree = 9479 createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps); 9480 } 9481 for (auto &Pair : ExternallyUsedValues) { 9482 // Add each externally used value to the final reduction. 9483 for (auto *I : Pair.second) { 9484 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 9485 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 9486 Pair.first, "op.extra", I); 9487 } 9488 } 9489 9490 ReductionRoot->replaceAllUsesWith(VectorizedTree); 9491 9492 // Mark all scalar reduction ops for deletion, they are replaced by the 9493 // vector reductions. 9494 V.eraseInstructions(IgnoreList); 9495 } 9496 return VectorizedTree; 9497 } 9498 9499 unsigned numReductionValues() const { return ReducedVals.size(); } 9500 9501 private: 9502 /// Calculate the cost of a reduction. 9503 InstructionCost getReductionCost(TargetTransformInfo *TTI, 9504 Value *FirstReducedVal, unsigned ReduxWidth, 9505 FastMathFlags FMF) { 9506 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 9507 Type *ScalarTy = FirstReducedVal->getType(); 9508 FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth); 9509 InstructionCost VectorCost, ScalarCost; 9510 switch (RdxKind) { 9511 case RecurKind::Add: 9512 case RecurKind::Mul: 9513 case RecurKind::Or: 9514 case RecurKind::And: 9515 case RecurKind::Xor: 9516 case RecurKind::FAdd: 9517 case RecurKind::FMul: { 9518 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind); 9519 VectorCost = 9520 TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind); 9521 ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind); 9522 break; 9523 } 9524 case RecurKind::FMax: 9525 case RecurKind::FMin: { 9526 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 9527 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 9528 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, 9529 /*IsUnsigned=*/false, CostKind); 9530 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 9531 ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy, 9532 SclCondTy, RdxPred, CostKind) + 9533 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 9534 SclCondTy, RdxPred, CostKind); 9535 break; 9536 } 9537 case RecurKind::SMax: 9538 case RecurKind::SMin: 9539 case RecurKind::UMax: 9540 case RecurKind::UMin: { 9541 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 9542 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 9543 bool IsUnsigned = 9544 RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin; 9545 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned, 9546 CostKind); 9547 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 9548 ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy, 9549 SclCondTy, RdxPred, CostKind) + 9550 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 9551 SclCondTy, RdxPred, CostKind); 9552 break; 9553 } 9554 default: 9555 llvm_unreachable("Expected arithmetic or min/max reduction operation"); 9556 } 9557 9558 // Scalar cost is repeated for N-1 elements. 9559 ScalarCost *= (ReduxWidth - 1); 9560 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost 9561 << " for reduction that starts with " << *FirstReducedVal 9562 << " (It is a splitting reduction)\n"); 9563 return VectorCost - ScalarCost; 9564 } 9565 9566 /// Emit a horizontal reduction of the vectorized value. 9567 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder, 9568 unsigned ReduxWidth, const TargetTransformInfo *TTI) { 9569 assert(VectorizedValue && "Need to have a vectorized tree node"); 9570 assert(isPowerOf2_32(ReduxWidth) && 9571 "We only handle power-of-two reductions for now"); 9572 assert(RdxKind != RecurKind::FMulAdd && 9573 "A call to the llvm.fmuladd intrinsic is not handled yet"); 9574 9575 ++NumVectorInstructions; 9576 return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind); 9577 } 9578 }; 9579 9580 } // end anonymous namespace 9581 9582 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) { 9583 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) 9584 return cast<FixedVectorType>(IE->getType())->getNumElements(); 9585 9586 unsigned AggregateSize = 1; 9587 auto *IV = cast<InsertValueInst>(InsertInst); 9588 Type *CurrentType = IV->getType(); 9589 do { 9590 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 9591 for (auto *Elt : ST->elements()) 9592 if (Elt != ST->getElementType(0)) // check homogeneity 9593 return None; 9594 AggregateSize *= ST->getNumElements(); 9595 CurrentType = ST->getElementType(0); 9596 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 9597 AggregateSize *= AT->getNumElements(); 9598 CurrentType = AT->getElementType(); 9599 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) { 9600 AggregateSize *= VT->getNumElements(); 9601 return AggregateSize; 9602 } else if (CurrentType->isSingleValueType()) { 9603 return AggregateSize; 9604 } else { 9605 return None; 9606 } 9607 } while (true); 9608 } 9609 9610 static bool findBuildAggregate_rec(Instruction *LastInsertInst, 9611 TargetTransformInfo *TTI, 9612 SmallVectorImpl<Value *> &BuildVectorOpds, 9613 SmallVectorImpl<Value *> &InsertElts, 9614 unsigned OperandOffset) { 9615 do { 9616 Value *InsertedOperand = LastInsertInst->getOperand(1); 9617 Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset); 9618 if (!OperandIndex) 9619 return false; 9620 if (isa<InsertElementInst>(InsertedOperand) || 9621 isa<InsertValueInst>(InsertedOperand)) { 9622 if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI, 9623 BuildVectorOpds, InsertElts, *OperandIndex)) 9624 return false; 9625 } else { 9626 BuildVectorOpds[*OperandIndex] = InsertedOperand; 9627 InsertElts[*OperandIndex] = LastInsertInst; 9628 } 9629 LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0)); 9630 } while (LastInsertInst != nullptr && 9631 (isa<InsertValueInst>(LastInsertInst) || 9632 isa<InsertElementInst>(LastInsertInst)) && 9633 LastInsertInst->hasOneUse()); 9634 return true; 9635 } 9636 9637 /// Recognize construction of vectors like 9638 /// %ra = insertelement <4 x float> poison, float %s0, i32 0 9639 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1 9640 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2 9641 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3 9642 /// starting from the last insertelement or insertvalue instruction. 9643 /// 9644 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>}, 9645 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on. 9646 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples. 9647 /// 9648 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type. 9649 /// 9650 /// \return true if it matches. 9651 static bool findBuildAggregate(Instruction *LastInsertInst, 9652 TargetTransformInfo *TTI, 9653 SmallVectorImpl<Value *> &BuildVectorOpds, 9654 SmallVectorImpl<Value *> &InsertElts) { 9655 9656 assert((isa<InsertElementInst>(LastInsertInst) || 9657 isa<InsertValueInst>(LastInsertInst)) && 9658 "Expected insertelement or insertvalue instruction!"); 9659 9660 assert((BuildVectorOpds.empty() && InsertElts.empty()) && 9661 "Expected empty result vectors!"); 9662 9663 Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst); 9664 if (!AggregateSize) 9665 return false; 9666 BuildVectorOpds.resize(*AggregateSize); 9667 InsertElts.resize(*AggregateSize); 9668 9669 if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 9670 0)) { 9671 llvm::erase_value(BuildVectorOpds, nullptr); 9672 llvm::erase_value(InsertElts, nullptr); 9673 if (BuildVectorOpds.size() >= 2) 9674 return true; 9675 } 9676 9677 return false; 9678 } 9679 9680 /// Try and get a reduction value from a phi node. 9681 /// 9682 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions 9683 /// if they come from either \p ParentBB or a containing loop latch. 9684 /// 9685 /// \returns A candidate reduction value if possible, or \code nullptr \endcode 9686 /// if not possible. 9687 static Value *getReductionValue(const DominatorTree *DT, PHINode *P, 9688 BasicBlock *ParentBB, LoopInfo *LI) { 9689 // There are situations where the reduction value is not dominated by the 9690 // reduction phi. Vectorizing such cases has been reported to cause 9691 // miscompiles. See PR25787. 9692 auto DominatedReduxValue = [&](Value *R) { 9693 return isa<Instruction>(R) && 9694 DT->dominates(P->getParent(), cast<Instruction>(R)->getParent()); 9695 }; 9696 9697 Value *Rdx = nullptr; 9698 9699 // Return the incoming value if it comes from the same BB as the phi node. 9700 if (P->getIncomingBlock(0) == ParentBB) { 9701 Rdx = P->getIncomingValue(0); 9702 } else if (P->getIncomingBlock(1) == ParentBB) { 9703 Rdx = P->getIncomingValue(1); 9704 } 9705 9706 if (Rdx && DominatedReduxValue(Rdx)) 9707 return Rdx; 9708 9709 // Otherwise, check whether we have a loop latch to look at. 9710 Loop *BBL = LI->getLoopFor(ParentBB); 9711 if (!BBL) 9712 return nullptr; 9713 BasicBlock *BBLatch = BBL->getLoopLatch(); 9714 if (!BBLatch) 9715 return nullptr; 9716 9717 // There is a loop latch, return the incoming value if it comes from 9718 // that. This reduction pattern occasionally turns up. 9719 if (P->getIncomingBlock(0) == BBLatch) { 9720 Rdx = P->getIncomingValue(0); 9721 } else if (P->getIncomingBlock(1) == BBLatch) { 9722 Rdx = P->getIncomingValue(1); 9723 } 9724 9725 if (Rdx && DominatedReduxValue(Rdx)) 9726 return Rdx; 9727 9728 return nullptr; 9729 } 9730 9731 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) { 9732 if (match(I, m_BinOp(m_Value(V0), m_Value(V1)))) 9733 return true; 9734 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1)))) 9735 return true; 9736 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1)))) 9737 return true; 9738 if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1)))) 9739 return true; 9740 if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1)))) 9741 return true; 9742 if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1)))) 9743 return true; 9744 if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1)))) 9745 return true; 9746 return false; 9747 } 9748 9749 /// Attempt to reduce a horizontal reduction. 9750 /// If it is legal to match a horizontal reduction feeding the phi node \a P 9751 /// with reduction operators \a Root (or one of its operands) in a basic block 9752 /// \a BB, then check if it can be done. If horizontal reduction is not found 9753 /// and root instruction is a binary operation, vectorization of the operands is 9754 /// attempted. 9755 /// \returns true if a horizontal reduction was matched and reduced or operands 9756 /// of one of the binary instruction were vectorized. 9757 /// \returns false if a horizontal reduction was not matched (or not possible) 9758 /// or no vectorization of any binary operation feeding \a Root instruction was 9759 /// performed. 9760 static bool tryToVectorizeHorReductionOrInstOperands( 9761 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, 9762 TargetTransformInfo *TTI, 9763 const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) { 9764 if (!ShouldVectorizeHor) 9765 return false; 9766 9767 if (!Root) 9768 return false; 9769 9770 if (Root->getParent() != BB || isa<PHINode>(Root)) 9771 return false; 9772 // Start analysis starting from Root instruction. If horizontal reduction is 9773 // found, try to vectorize it. If it is not a horizontal reduction or 9774 // vectorization is not possible or not effective, and currently analyzed 9775 // instruction is a binary operation, try to vectorize the operands, using 9776 // pre-order DFS traversal order. If the operands were not vectorized, repeat 9777 // the same procedure considering each operand as a possible root of the 9778 // horizontal reduction. 9779 // Interrupt the process if the Root instruction itself was vectorized or all 9780 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized. 9781 // Skip the analysis of CmpInsts.Compiler implements postanalysis of the 9782 // CmpInsts so we can skip extra attempts in 9783 // tryToVectorizeHorReductionOrInstOperands and save compile time. 9784 std::queue<std::pair<Instruction *, unsigned>> Stack; 9785 Stack.emplace(Root, 0); 9786 SmallPtrSet<Value *, 8> VisitedInstrs; 9787 SmallVector<WeakTrackingVH> PostponedInsts; 9788 bool Res = false; 9789 auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0, 9790 Value *&B1) -> Value * { 9791 bool IsBinop = matchRdxBop(Inst, B0, B1); 9792 bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value())); 9793 if (IsBinop || IsSelect) { 9794 HorizontalReduction HorRdx; 9795 if (HorRdx.matchAssociativeReduction(P, Inst)) 9796 return HorRdx.tryToReduce(R, TTI); 9797 } 9798 return nullptr; 9799 }; 9800 while (!Stack.empty()) { 9801 Instruction *Inst; 9802 unsigned Level; 9803 std::tie(Inst, Level) = Stack.front(); 9804 Stack.pop(); 9805 // Do not try to analyze instruction that has already been vectorized. 9806 // This may happen when we vectorize instruction operands on a previous 9807 // iteration while stack was populated before that happened. 9808 if (R.isDeleted(Inst)) 9809 continue; 9810 Value *B0 = nullptr, *B1 = nullptr; 9811 if (Value *V = TryToReduce(Inst, B0, B1)) { 9812 Res = true; 9813 // Set P to nullptr to avoid re-analysis of phi node in 9814 // matchAssociativeReduction function unless this is the root node. 9815 P = nullptr; 9816 if (auto *I = dyn_cast<Instruction>(V)) { 9817 // Try to find another reduction. 9818 Stack.emplace(I, Level); 9819 continue; 9820 } 9821 } else { 9822 bool IsBinop = B0 && B1; 9823 if (P && IsBinop) { 9824 Inst = dyn_cast<Instruction>(B0); 9825 if (Inst == P) 9826 Inst = dyn_cast<Instruction>(B1); 9827 if (!Inst) { 9828 // Set P to nullptr to avoid re-analysis of phi node in 9829 // matchAssociativeReduction function unless this is the root node. 9830 P = nullptr; 9831 continue; 9832 } 9833 } 9834 // Set P to nullptr to avoid re-analysis of phi node in 9835 // matchAssociativeReduction function unless this is the root node. 9836 P = nullptr; 9837 // Do not try to vectorize CmpInst operands, this is done separately. 9838 // Final attempt for binop args vectorization should happen after the loop 9839 // to try to find reductions. 9840 if (!isa<CmpInst>(Inst)) 9841 PostponedInsts.push_back(Inst); 9842 } 9843 9844 // Try to vectorize operands. 9845 // Continue analysis for the instruction from the same basic block only to 9846 // save compile time. 9847 if (++Level < RecursionMaxDepth) 9848 for (auto *Op : Inst->operand_values()) 9849 if (VisitedInstrs.insert(Op).second) 9850 if (auto *I = dyn_cast<Instruction>(Op)) 9851 // Do not try to vectorize CmpInst operands, this is done 9852 // separately. 9853 if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) && 9854 I->getParent() == BB) 9855 Stack.emplace(I, Level); 9856 } 9857 // Try to vectorized binops where reductions were not found. 9858 for (Value *V : PostponedInsts) 9859 if (auto *Inst = dyn_cast<Instruction>(V)) 9860 if (!R.isDeleted(Inst)) 9861 Res |= Vectorize(Inst, R); 9862 return Res; 9863 } 9864 9865 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V, 9866 BasicBlock *BB, BoUpSLP &R, 9867 TargetTransformInfo *TTI) { 9868 auto *I = dyn_cast_or_null<Instruction>(V); 9869 if (!I) 9870 return false; 9871 9872 if (!isa<BinaryOperator>(I)) 9873 P = nullptr; 9874 // Try to match and vectorize a horizontal reduction. 9875 auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool { 9876 return tryToVectorize(I, R); 9877 }; 9878 return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, 9879 ExtraVectorization); 9880 } 9881 9882 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI, 9883 BasicBlock *BB, BoUpSLP &R) { 9884 const DataLayout &DL = BB->getModule()->getDataLayout(); 9885 if (!R.canMapToVector(IVI->getType(), DL)) 9886 return false; 9887 9888 SmallVector<Value *, 16> BuildVectorOpds; 9889 SmallVector<Value *, 16> BuildVectorInsts; 9890 if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts)) 9891 return false; 9892 9893 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n"); 9894 // Aggregate value is unlikely to be processed in vector register. 9895 return tryToVectorizeList(BuildVectorOpds, R); 9896 } 9897 9898 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI, 9899 BasicBlock *BB, BoUpSLP &R) { 9900 SmallVector<Value *, 16> BuildVectorInsts; 9901 SmallVector<Value *, 16> BuildVectorOpds; 9902 SmallVector<int> Mask; 9903 if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) || 9904 (llvm::all_of( 9905 BuildVectorOpds, 9906 [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) && 9907 isFixedVectorShuffle(BuildVectorOpds, Mask))) 9908 return false; 9909 9910 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n"); 9911 return tryToVectorizeList(BuildVectorInsts, R); 9912 } 9913 9914 template <typename T> 9915 static bool 9916 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming, 9917 function_ref<unsigned(T *)> Limit, 9918 function_ref<bool(T *, T *)> Comparator, 9919 function_ref<bool(T *, T *)> AreCompatible, 9920 function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper, 9921 bool LimitForRegisterSize) { 9922 bool Changed = false; 9923 // Sort by type, parent, operands. 9924 stable_sort(Incoming, Comparator); 9925 9926 // Try to vectorize elements base on their type. 9927 SmallVector<T *> Candidates; 9928 for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) { 9929 // Look for the next elements with the same type, parent and operand 9930 // kinds. 9931 auto *SameTypeIt = IncIt; 9932 while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt)) 9933 ++SameTypeIt; 9934 9935 // Try to vectorize them. 9936 unsigned NumElts = (SameTypeIt - IncIt); 9937 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes (" 9938 << NumElts << ")\n"); 9939 // The vectorization is a 3-state attempt: 9940 // 1. Try to vectorize instructions with the same/alternate opcodes with the 9941 // size of maximal register at first. 9942 // 2. Try to vectorize remaining instructions with the same type, if 9943 // possible. This may result in the better vectorization results rather than 9944 // if we try just to vectorize instructions with the same/alternate opcodes. 9945 // 3. Final attempt to try to vectorize all instructions with the 9946 // same/alternate ops only, this may result in some extra final 9947 // vectorization. 9948 if (NumElts > 1 && 9949 TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) { 9950 // Success start over because instructions might have been changed. 9951 Changed = true; 9952 } else if (NumElts < Limit(*IncIt) && 9953 (Candidates.empty() || 9954 Candidates.front()->getType() == (*IncIt)->getType())) { 9955 Candidates.append(IncIt, std::next(IncIt, NumElts)); 9956 } 9957 // Final attempt to vectorize instructions with the same types. 9958 if (Candidates.size() > 1 && 9959 (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) { 9960 if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) { 9961 // Success start over because instructions might have been changed. 9962 Changed = true; 9963 } else if (LimitForRegisterSize) { 9964 // Try to vectorize using small vectors. 9965 for (auto *It = Candidates.begin(), *End = Candidates.end(); 9966 It != End;) { 9967 auto *SameTypeIt = It; 9968 while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It)) 9969 ++SameTypeIt; 9970 unsigned NumElts = (SameTypeIt - It); 9971 if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts), 9972 /*LimitForRegisterSize=*/false)) 9973 Changed = true; 9974 It = SameTypeIt; 9975 } 9976 } 9977 Candidates.clear(); 9978 } 9979 9980 // Start over at the next instruction of a different type (or the end). 9981 IncIt = SameTypeIt; 9982 } 9983 return Changed; 9984 } 9985 9986 /// Compare two cmp instructions. If IsCompatibility is true, function returns 9987 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding 9988 /// operands. If IsCompatibility is false, function implements strict weak 9989 /// ordering relation between two cmp instructions, returning true if the first 9990 /// instruction is "less" than the second, i.e. its predicate is less than the 9991 /// predicate of the second or the operands IDs are less than the operands IDs 9992 /// of the second cmp instruction. 9993 template <bool IsCompatibility> 9994 static bool compareCmp(Value *V, Value *V2, 9995 function_ref<bool(Instruction *)> IsDeleted) { 9996 auto *CI1 = cast<CmpInst>(V); 9997 auto *CI2 = cast<CmpInst>(V2); 9998 if (IsDeleted(CI2) || !isValidElementType(CI2->getType())) 9999 return false; 10000 if (CI1->getOperand(0)->getType()->getTypeID() < 10001 CI2->getOperand(0)->getType()->getTypeID()) 10002 return !IsCompatibility; 10003 if (CI1->getOperand(0)->getType()->getTypeID() > 10004 CI2->getOperand(0)->getType()->getTypeID()) 10005 return false; 10006 CmpInst::Predicate Pred1 = CI1->getPredicate(); 10007 CmpInst::Predicate Pred2 = CI2->getPredicate(); 10008 CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1); 10009 CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2); 10010 CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1); 10011 CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2); 10012 if (BasePred1 < BasePred2) 10013 return !IsCompatibility; 10014 if (BasePred1 > BasePred2) 10015 return false; 10016 // Compare operands. 10017 bool LEPreds = Pred1 <= Pred2; 10018 bool GEPreds = Pred1 >= Pred2; 10019 for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) { 10020 auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1); 10021 auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1); 10022 if (Op1->getValueID() < Op2->getValueID()) 10023 return !IsCompatibility; 10024 if (Op1->getValueID() > Op2->getValueID()) 10025 return false; 10026 if (auto *I1 = dyn_cast<Instruction>(Op1)) 10027 if (auto *I2 = dyn_cast<Instruction>(Op2)) { 10028 if (I1->getParent() != I2->getParent()) 10029 return false; 10030 InstructionsState S = getSameOpcode({I1, I2}); 10031 if (S.getOpcode()) 10032 continue; 10033 return false; 10034 } 10035 } 10036 return IsCompatibility; 10037 } 10038 10039 bool SLPVectorizerPass::vectorizeSimpleInstructions( 10040 SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R, 10041 bool AtTerminator) { 10042 bool OpsChanged = false; 10043 SmallVector<Instruction *, 4> PostponedCmps; 10044 for (auto *I : reverse(Instructions)) { 10045 if (R.isDeleted(I)) 10046 continue; 10047 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) 10048 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R); 10049 else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) 10050 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R); 10051 else if (isa<CmpInst>(I)) 10052 PostponedCmps.push_back(I); 10053 } 10054 if (AtTerminator) { 10055 // Try to find reductions first. 10056 for (Instruction *I : PostponedCmps) { 10057 if (R.isDeleted(I)) 10058 continue; 10059 for (Value *Op : I->operands()) 10060 OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI); 10061 } 10062 // Try to vectorize operands as vector bundles. 10063 for (Instruction *I : PostponedCmps) { 10064 if (R.isDeleted(I)) 10065 continue; 10066 OpsChanged |= tryToVectorize(I, R); 10067 } 10068 // Try to vectorize list of compares. 10069 // Sort by type, compare predicate, etc. 10070 auto &&CompareSorter = [&R](Value *V, Value *V2) { 10071 return compareCmp<false>(V, V2, 10072 [&R](Instruction *I) { return R.isDeleted(I); }); 10073 }; 10074 10075 auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) { 10076 if (V1 == V2) 10077 return true; 10078 return compareCmp<true>(V1, V2, 10079 [&R](Instruction *I) { return R.isDeleted(I); }); 10080 }; 10081 auto Limit = [&R](Value *V) { 10082 unsigned EltSize = R.getVectorElementSize(V); 10083 return std::max(2U, R.getMaxVecRegSize() / EltSize); 10084 }; 10085 10086 SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end()); 10087 OpsChanged |= tryToVectorizeSequence<Value>( 10088 Vals, Limit, CompareSorter, AreCompatibleCompares, 10089 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 10090 // Exclude possible reductions from other blocks. 10091 bool ArePossiblyReducedInOtherBlock = 10092 any_of(Candidates, [](Value *V) { 10093 return any_of(V->users(), [V](User *U) { 10094 return isa<SelectInst>(U) && 10095 cast<SelectInst>(U)->getParent() != 10096 cast<Instruction>(V)->getParent(); 10097 }); 10098 }); 10099 if (ArePossiblyReducedInOtherBlock) 10100 return false; 10101 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 10102 }, 10103 /*LimitForRegisterSize=*/true); 10104 Instructions.clear(); 10105 } else { 10106 // Insert in reverse order since the PostponedCmps vector was filled in 10107 // reverse order. 10108 Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend()); 10109 } 10110 return OpsChanged; 10111 } 10112 10113 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { 10114 bool Changed = false; 10115 SmallVector<Value *, 4> Incoming; 10116 SmallPtrSet<Value *, 16> VisitedInstrs; 10117 // Maps phi nodes to the non-phi nodes found in the use tree for each phi 10118 // node. Allows better to identify the chains that can be vectorized in the 10119 // better way. 10120 DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes; 10121 auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) { 10122 assert(isValidElementType(V1->getType()) && 10123 isValidElementType(V2->getType()) && 10124 "Expected vectorizable types only."); 10125 // It is fine to compare type IDs here, since we expect only vectorizable 10126 // types, like ints, floats and pointers, we don't care about other type. 10127 if (V1->getType()->getTypeID() < V2->getType()->getTypeID()) 10128 return true; 10129 if (V1->getType()->getTypeID() > V2->getType()->getTypeID()) 10130 return false; 10131 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 10132 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 10133 if (Opcodes1.size() < Opcodes2.size()) 10134 return true; 10135 if (Opcodes1.size() > Opcodes2.size()) 10136 return false; 10137 Optional<bool> ConstOrder; 10138 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 10139 // Undefs are compatible with any other value. 10140 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) { 10141 if (!ConstOrder) 10142 ConstOrder = 10143 !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]); 10144 continue; 10145 } 10146 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 10147 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 10148 DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent()); 10149 DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent()); 10150 if (!NodeI1) 10151 return NodeI2 != nullptr; 10152 if (!NodeI2) 10153 return false; 10154 assert((NodeI1 == NodeI2) == 10155 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 10156 "Different nodes should have different DFS numbers"); 10157 if (NodeI1 != NodeI2) 10158 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 10159 InstructionsState S = getSameOpcode({I1, I2}); 10160 if (S.getOpcode()) 10161 continue; 10162 return I1->getOpcode() < I2->getOpcode(); 10163 } 10164 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) { 10165 if (!ConstOrder) 10166 ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID(); 10167 continue; 10168 } 10169 if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID()) 10170 return true; 10171 if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID()) 10172 return false; 10173 } 10174 return ConstOrder && *ConstOrder; 10175 }; 10176 auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) { 10177 if (V1 == V2) 10178 return true; 10179 if (V1->getType() != V2->getType()) 10180 return false; 10181 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 10182 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 10183 if (Opcodes1.size() != Opcodes2.size()) 10184 return false; 10185 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 10186 // Undefs are compatible with any other value. 10187 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) 10188 continue; 10189 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 10190 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 10191 if (I1->getParent() != I2->getParent()) 10192 return false; 10193 InstructionsState S = getSameOpcode({I1, I2}); 10194 if (S.getOpcode()) 10195 continue; 10196 return false; 10197 } 10198 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) 10199 continue; 10200 if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID()) 10201 return false; 10202 } 10203 return true; 10204 }; 10205 auto Limit = [&R](Value *V) { 10206 unsigned EltSize = R.getVectorElementSize(V); 10207 return std::max(2U, R.getMaxVecRegSize() / EltSize); 10208 }; 10209 10210 bool HaveVectorizedPhiNodes = false; 10211 do { 10212 // Collect the incoming values from the PHIs. 10213 Incoming.clear(); 10214 for (Instruction &I : *BB) { 10215 PHINode *P = dyn_cast<PHINode>(&I); 10216 if (!P) 10217 break; 10218 10219 // No need to analyze deleted, vectorized and non-vectorizable 10220 // instructions. 10221 if (!VisitedInstrs.count(P) && !R.isDeleted(P) && 10222 isValidElementType(P->getType())) 10223 Incoming.push_back(P); 10224 } 10225 10226 // Find the corresponding non-phi nodes for better matching when trying to 10227 // build the tree. 10228 for (Value *V : Incoming) { 10229 SmallVectorImpl<Value *> &Opcodes = 10230 PHIToOpcodes.try_emplace(V).first->getSecond(); 10231 if (!Opcodes.empty()) 10232 continue; 10233 SmallVector<Value *, 4> Nodes(1, V); 10234 SmallPtrSet<Value *, 4> Visited; 10235 while (!Nodes.empty()) { 10236 auto *PHI = cast<PHINode>(Nodes.pop_back_val()); 10237 if (!Visited.insert(PHI).second) 10238 continue; 10239 for (Value *V : PHI->incoming_values()) { 10240 if (auto *PHI1 = dyn_cast<PHINode>((V))) { 10241 Nodes.push_back(PHI1); 10242 continue; 10243 } 10244 Opcodes.emplace_back(V); 10245 } 10246 } 10247 } 10248 10249 HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>( 10250 Incoming, Limit, PHICompare, AreCompatiblePHIs, 10251 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 10252 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 10253 }, 10254 /*LimitForRegisterSize=*/true); 10255 Changed |= HaveVectorizedPhiNodes; 10256 VisitedInstrs.insert(Incoming.begin(), Incoming.end()); 10257 } while (HaveVectorizedPhiNodes); 10258 10259 VisitedInstrs.clear(); 10260 10261 SmallVector<Instruction *, 8> PostProcessInstructions; 10262 SmallDenseSet<Instruction *, 4> KeyNodes; 10263 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 10264 // Skip instructions with scalable type. The num of elements is unknown at 10265 // compile-time for scalable type. 10266 if (isa<ScalableVectorType>(it->getType())) 10267 continue; 10268 10269 // Skip instructions marked for the deletion. 10270 if (R.isDeleted(&*it)) 10271 continue; 10272 // We may go through BB multiple times so skip the one we have checked. 10273 if (!VisitedInstrs.insert(&*it).second) { 10274 if (it->use_empty() && KeyNodes.contains(&*it) && 10275 vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 10276 it->isTerminator())) { 10277 // We would like to start over since some instructions are deleted 10278 // and the iterator may become invalid value. 10279 Changed = true; 10280 it = BB->begin(); 10281 e = BB->end(); 10282 } 10283 continue; 10284 } 10285 10286 if (isa<DbgInfoIntrinsic>(it)) 10287 continue; 10288 10289 // Try to vectorize reductions that use PHINodes. 10290 if (PHINode *P = dyn_cast<PHINode>(it)) { 10291 // Check that the PHI is a reduction PHI. 10292 if (P->getNumIncomingValues() == 2) { 10293 // Try to match and vectorize a horizontal reduction. 10294 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R, 10295 TTI)) { 10296 Changed = true; 10297 it = BB->begin(); 10298 e = BB->end(); 10299 continue; 10300 } 10301 } 10302 // Try to vectorize the incoming values of the PHI, to catch reductions 10303 // that feed into PHIs. 10304 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) { 10305 // Skip if the incoming block is the current BB for now. Also, bypass 10306 // unreachable IR for efficiency and to avoid crashing. 10307 // TODO: Collect the skipped incoming values and try to vectorize them 10308 // after processing BB. 10309 if (BB == P->getIncomingBlock(I) || 10310 !DT->isReachableFromEntry(P->getIncomingBlock(I))) 10311 continue; 10312 10313 Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I), 10314 P->getIncomingBlock(I), R, TTI); 10315 } 10316 continue; 10317 } 10318 10319 // Ran into an instruction without users, like terminator, or function call 10320 // with ignored return value, store. Ignore unused instructions (basing on 10321 // instruction type, except for CallInst and InvokeInst). 10322 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) || 10323 isa<InvokeInst>(it))) { 10324 KeyNodes.insert(&*it); 10325 bool OpsChanged = false; 10326 if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) { 10327 for (auto *V : it->operand_values()) { 10328 // Try to match and vectorize a horizontal reduction. 10329 OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI); 10330 } 10331 } 10332 // Start vectorization of post-process list of instructions from the 10333 // top-tree instructions to try to vectorize as many instructions as 10334 // possible. 10335 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 10336 it->isTerminator()); 10337 if (OpsChanged) { 10338 // We would like to start over since some instructions are deleted 10339 // and the iterator may become invalid value. 10340 Changed = true; 10341 it = BB->begin(); 10342 e = BB->end(); 10343 continue; 10344 } 10345 } 10346 10347 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) || 10348 isa<InsertValueInst>(it)) 10349 PostProcessInstructions.push_back(&*it); 10350 } 10351 10352 return Changed; 10353 } 10354 10355 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) { 10356 auto Changed = false; 10357 for (auto &Entry : GEPs) { 10358 // If the getelementptr list has fewer than two elements, there's nothing 10359 // to do. 10360 if (Entry.second.size() < 2) 10361 continue; 10362 10363 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length " 10364 << Entry.second.size() << ".\n"); 10365 10366 // Process the GEP list in chunks suitable for the target's supported 10367 // vector size. If a vector register can't hold 1 element, we are done. We 10368 // are trying to vectorize the index computations, so the maximum number of 10369 // elements is based on the size of the index expression, rather than the 10370 // size of the GEP itself (the target's pointer size). 10371 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 10372 unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin()); 10373 if (MaxVecRegSize < EltSize) 10374 continue; 10375 10376 unsigned MaxElts = MaxVecRegSize / EltSize; 10377 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) { 10378 auto Len = std::min<unsigned>(BE - BI, MaxElts); 10379 ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len); 10380 10381 // Initialize a set a candidate getelementptrs. Note that we use a 10382 // SetVector here to preserve program order. If the index computations 10383 // are vectorizable and begin with loads, we want to minimize the chance 10384 // of having to reorder them later. 10385 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end()); 10386 10387 // Some of the candidates may have already been vectorized after we 10388 // initially collected them. If so, they are marked as deleted, so remove 10389 // them from the set of candidates. 10390 Candidates.remove_if( 10391 [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); }); 10392 10393 // Remove from the set of candidates all pairs of getelementptrs with 10394 // constant differences. Such getelementptrs are likely not good 10395 // candidates for vectorization in a bottom-up phase since one can be 10396 // computed from the other. We also ensure all candidate getelementptr 10397 // indices are unique. 10398 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) { 10399 auto *GEPI = GEPList[I]; 10400 if (!Candidates.count(GEPI)) 10401 continue; 10402 auto *SCEVI = SE->getSCEV(GEPList[I]); 10403 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) { 10404 auto *GEPJ = GEPList[J]; 10405 auto *SCEVJ = SE->getSCEV(GEPList[J]); 10406 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) { 10407 Candidates.remove(GEPI); 10408 Candidates.remove(GEPJ); 10409 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) { 10410 Candidates.remove(GEPJ); 10411 } 10412 } 10413 } 10414 10415 // We break out of the above computation as soon as we know there are 10416 // fewer than two candidates remaining. 10417 if (Candidates.size() < 2) 10418 continue; 10419 10420 // Add the single, non-constant index of each candidate to the bundle. We 10421 // ensured the indices met these constraints when we originally collected 10422 // the getelementptrs. 10423 SmallVector<Value *, 16> Bundle(Candidates.size()); 10424 auto BundleIndex = 0u; 10425 for (auto *V : Candidates) { 10426 auto *GEP = cast<GetElementPtrInst>(V); 10427 auto *GEPIdx = GEP->idx_begin()->get(); 10428 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)); 10429 Bundle[BundleIndex++] = GEPIdx; 10430 } 10431 10432 // Try and vectorize the indices. We are currently only interested in 10433 // gather-like cases of the form: 10434 // 10435 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ... 10436 // 10437 // where the loads of "a", the loads of "b", and the subtractions can be 10438 // performed in parallel. It's likely that detecting this pattern in a 10439 // bottom-up phase will be simpler and less costly than building a 10440 // full-blown top-down phase beginning at the consecutive loads. 10441 Changed |= tryToVectorizeList(Bundle, R); 10442 } 10443 } 10444 return Changed; 10445 } 10446 10447 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) { 10448 bool Changed = false; 10449 // Sort by type, base pointers and values operand. Value operands must be 10450 // compatible (have the same opcode, same parent), otherwise it is 10451 // definitely not profitable to try to vectorize them. 10452 auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) { 10453 if (V->getPointerOperandType()->getTypeID() < 10454 V2->getPointerOperandType()->getTypeID()) 10455 return true; 10456 if (V->getPointerOperandType()->getTypeID() > 10457 V2->getPointerOperandType()->getTypeID()) 10458 return false; 10459 // UndefValues are compatible with all other values. 10460 if (isa<UndefValue>(V->getValueOperand()) || 10461 isa<UndefValue>(V2->getValueOperand())) 10462 return false; 10463 if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand())) 10464 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 10465 DomTreeNodeBase<llvm::BasicBlock> *NodeI1 = 10466 DT->getNode(I1->getParent()); 10467 DomTreeNodeBase<llvm::BasicBlock> *NodeI2 = 10468 DT->getNode(I2->getParent()); 10469 assert(NodeI1 && "Should only process reachable instructions"); 10470 assert(NodeI1 && "Should only process reachable instructions"); 10471 assert((NodeI1 == NodeI2) == 10472 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 10473 "Different nodes should have different DFS numbers"); 10474 if (NodeI1 != NodeI2) 10475 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 10476 InstructionsState S = getSameOpcode({I1, I2}); 10477 if (S.getOpcode()) 10478 return false; 10479 return I1->getOpcode() < I2->getOpcode(); 10480 } 10481 if (isa<Constant>(V->getValueOperand()) && 10482 isa<Constant>(V2->getValueOperand())) 10483 return false; 10484 return V->getValueOperand()->getValueID() < 10485 V2->getValueOperand()->getValueID(); 10486 }; 10487 10488 auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) { 10489 if (V1 == V2) 10490 return true; 10491 if (V1->getPointerOperandType() != V2->getPointerOperandType()) 10492 return false; 10493 // Undefs are compatible with any other value. 10494 if (isa<UndefValue>(V1->getValueOperand()) || 10495 isa<UndefValue>(V2->getValueOperand())) 10496 return true; 10497 if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand())) 10498 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 10499 if (I1->getParent() != I2->getParent()) 10500 return false; 10501 InstructionsState S = getSameOpcode({I1, I2}); 10502 return S.getOpcode() > 0; 10503 } 10504 if (isa<Constant>(V1->getValueOperand()) && 10505 isa<Constant>(V2->getValueOperand())) 10506 return true; 10507 return V1->getValueOperand()->getValueID() == 10508 V2->getValueOperand()->getValueID(); 10509 }; 10510 auto Limit = [&R, this](StoreInst *SI) { 10511 unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType()); 10512 return R.getMinVF(EltSize); 10513 }; 10514 10515 // Attempt to sort and vectorize each of the store-groups. 10516 for (auto &Pair : Stores) { 10517 if (Pair.second.size() < 2) 10518 continue; 10519 10520 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " 10521 << Pair.second.size() << ".\n"); 10522 10523 if (!isValidElementType(Pair.second.front()->getValueOperand()->getType())) 10524 continue; 10525 10526 Changed |= tryToVectorizeSequence<StoreInst>( 10527 Pair.second, Limit, StoreSorter, AreCompatibleStores, 10528 [this, &R](ArrayRef<StoreInst *> Candidates, bool) { 10529 return vectorizeStores(Candidates, R); 10530 }, 10531 /*LimitForRegisterSize=*/false); 10532 } 10533 return Changed; 10534 } 10535 10536 char SLPVectorizer::ID = 0; 10537 10538 static const char lv_name[] = "SLP Vectorizer"; 10539 10540 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false) 10541 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 10542 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 10543 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10544 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 10545 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 10546 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) 10547 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 10548 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy) 10549 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) 10550 10551 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); } 10552