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/Operator.h" 68 #include "llvm/IR/PatternMatch.h" 69 #include "llvm/IR/Type.h" 70 #include "llvm/IR/Use.h" 71 #include "llvm/IR/User.h" 72 #include "llvm/IR/Value.h" 73 #include "llvm/IR/ValueHandle.h" 74 #include "llvm/IR/Verifier.h" 75 #include "llvm/Pass.h" 76 #include "llvm/Support/Casting.h" 77 #include "llvm/Support/CommandLine.h" 78 #include "llvm/Support/Compiler.h" 79 #include "llvm/Support/DOTGraphTraits.h" 80 #include "llvm/Support/Debug.h" 81 #include "llvm/Support/ErrorHandling.h" 82 #include "llvm/Support/GraphWriter.h" 83 #include "llvm/Support/InstructionCost.h" 84 #include "llvm/Support/KnownBits.h" 85 #include "llvm/Support/MathExtras.h" 86 #include "llvm/Support/raw_ostream.h" 87 #include "llvm/Transforms/Utils/InjectTLIMappings.h" 88 #include "llvm/Transforms/Utils/LoopUtils.h" 89 #include "llvm/Transforms/Vectorize.h" 90 #include <algorithm> 91 #include <cassert> 92 #include <cstdint> 93 #include <iterator> 94 #include <memory> 95 #include <set> 96 #include <string> 97 #include <tuple> 98 #include <utility> 99 #include <vector> 100 101 using namespace llvm; 102 using namespace llvm::PatternMatch; 103 using namespace slpvectorizer; 104 105 #define SV_NAME "slp-vectorizer" 106 #define DEBUG_TYPE "SLP" 107 108 STATISTIC(NumVectorInstructions, "Number of vector instructions generated"); 109 110 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden, 111 cl::desc("Run the SLP vectorization passes")); 112 113 static cl::opt<int> 114 SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden, 115 cl::desc("Only vectorize if you gain more than this " 116 "number ")); 117 118 static cl::opt<bool> 119 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden, 120 cl::desc("Attempt to vectorize horizontal reductions")); 121 122 static cl::opt<bool> ShouldStartVectorizeHorAtStore( 123 "slp-vectorize-hor-store", cl::init(false), cl::Hidden, 124 cl::desc( 125 "Attempt to vectorize horizontal reductions feeding into a store")); 126 127 static cl::opt<int> 128 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden, 129 cl::desc("Attempt to vectorize for this register size in bits")); 130 131 static cl::opt<unsigned> 132 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden, 133 cl::desc("Maximum SLP vectorization factor (0=unlimited)")); 134 135 static cl::opt<int> 136 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden, 137 cl::desc("Maximum depth of the lookup for consecutive stores.")); 138 139 /// Limits the size of scheduling regions in a block. 140 /// It avoid long compile times for _very_ large blocks where vector 141 /// instructions are spread over a wide range. 142 /// This limit is way higher than needed by real-world functions. 143 static cl::opt<int> 144 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden, 145 cl::desc("Limit the size of the SLP scheduling region per block")); 146 147 static cl::opt<int> MinVectorRegSizeOption( 148 "slp-min-reg-size", cl::init(128), cl::Hidden, 149 cl::desc("Attempt to vectorize for this register size in bits")); 150 151 static cl::opt<unsigned> RecursionMaxDepth( 152 "slp-recursion-max-depth", cl::init(12), cl::Hidden, 153 cl::desc("Limit the recursion depth when building a vectorizable tree")); 154 155 static cl::opt<unsigned> MinTreeSize( 156 "slp-min-tree-size", cl::init(3), cl::Hidden, 157 cl::desc("Only vectorize small trees if they are fully vectorizable")); 158 159 // The maximum depth that the look-ahead score heuristic will explore. 160 // The higher this value, the higher the compilation time overhead. 161 static cl::opt<int> LookAheadMaxDepth( 162 "slp-max-look-ahead-depth", cl::init(2), cl::Hidden, 163 cl::desc("The maximum look-ahead depth for operand reordering scores")); 164 165 static cl::opt<bool> 166 ViewSLPTree("view-slp-tree", cl::Hidden, 167 cl::desc("Display the SLP trees with Graphviz")); 168 169 // Limit the number of alias checks. The limit is chosen so that 170 // it has no negative effect on the llvm benchmarks. 171 static const unsigned AliasedCheckLimit = 10; 172 173 // Another limit for the alias checks: The maximum distance between load/store 174 // instructions where alias checks are done. 175 // This limit is useful for very large basic blocks. 176 static const unsigned MaxMemDepDistance = 160; 177 178 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling 179 /// regions to be handled. 180 static const int MinScheduleRegionSize = 16; 181 182 /// Predicate for the element types that the SLP vectorizer supports. 183 /// 184 /// The most important thing to filter here are types which are invalid in LLVM 185 /// vectors. We also filter target specific types which have absolutely no 186 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just 187 /// avoids spending time checking the cost model and realizing that they will 188 /// be inevitably scalarized. 189 static bool isValidElementType(Type *Ty) { 190 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() && 191 !Ty->isPPC_FP128Ty(); 192 } 193 194 /// \returns True if the value is a constant (but not globals/constant 195 /// expressions). 196 static bool isConstant(Value *V) { 197 return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V); 198 } 199 200 /// Checks if \p V is one of vector-like instructions, i.e. undef, 201 /// insertelement/extractelement with constant indices for fixed vector type or 202 /// extractvalue instruction. 203 static bool isVectorLikeInstWithConstOps(Value *V) { 204 if (!isa<InsertElementInst, ExtractElementInst>(V) && 205 !isa<ExtractValueInst, UndefValue>(V)) 206 return false; 207 auto *I = dyn_cast<Instruction>(V); 208 if (!I || isa<ExtractValueInst>(I)) 209 return true; 210 if (!isa<FixedVectorType>(I->getOperand(0)->getType())) 211 return false; 212 if (isa<ExtractElementInst>(I)) 213 return isConstant(I->getOperand(1)); 214 assert(isa<InsertElementInst>(V) && "Expected only insertelement."); 215 return isConstant(I->getOperand(2)); 216 } 217 218 /// \returns true if all of the instructions in \p VL are in the same block or 219 /// false otherwise. 220 static bool allSameBlock(ArrayRef<Value *> VL) { 221 Instruction *I0 = dyn_cast<Instruction>(VL[0]); 222 if (!I0) 223 return false; 224 if (all_of(VL, isVectorLikeInstWithConstOps)) 225 return true; 226 227 BasicBlock *BB = I0->getParent(); 228 for (int I = 1, E = VL.size(); I < E; I++) { 229 auto *II = dyn_cast<Instruction>(VL[I]); 230 if (!II) 231 return false; 232 233 if (BB != II->getParent()) 234 return false; 235 } 236 return true; 237 } 238 239 /// \returns True if all of the values in \p VL are constants (but not 240 /// globals/constant expressions). 241 static bool allConstant(ArrayRef<Value *> VL) { 242 // Constant expressions and globals can't be vectorized like normal integer/FP 243 // constants. 244 return all_of(VL, isConstant); 245 } 246 247 /// \returns True if all of the values in \p VL are identical or some of them 248 /// are UndefValue. 249 static bool isSplat(ArrayRef<Value *> VL) { 250 Value *FirstNonUndef = nullptr; 251 for (Value *V : VL) { 252 if (isa<UndefValue>(V)) 253 continue; 254 if (!FirstNonUndef) { 255 FirstNonUndef = V; 256 continue; 257 } 258 if (V != FirstNonUndef) 259 return false; 260 } 261 return FirstNonUndef != nullptr; 262 } 263 264 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator. 265 static bool isCommutative(Instruction *I) { 266 if (auto *Cmp = dyn_cast<CmpInst>(I)) 267 return Cmp->isCommutative(); 268 if (auto *BO = dyn_cast<BinaryOperator>(I)) 269 return BO->isCommutative(); 270 // TODO: This should check for generic Instruction::isCommutative(), but 271 // we need to confirm that the caller code correctly handles Intrinsics 272 // for example (does not have 2 operands). 273 return false; 274 } 275 276 /// Checks if the given value is actually an undefined constant vector. 277 static bool isUndefVector(const Value *V) { 278 if (isa<UndefValue>(V)) 279 return true; 280 auto *C = dyn_cast<Constant>(V); 281 if (!C) 282 return false; 283 if (!C->containsUndefOrPoisonElement()) 284 return false; 285 auto *VecTy = dyn_cast<FixedVectorType>(C->getType()); 286 if (!VecTy) 287 return false; 288 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) { 289 if (Constant *Elem = C->getAggregateElement(I)) 290 if (!isa<UndefValue>(Elem)) 291 return false; 292 } 293 return true; 294 } 295 296 /// Checks if the vector of instructions can be represented as a shuffle, like: 297 /// %x0 = extractelement <4 x i8> %x, i32 0 298 /// %x3 = extractelement <4 x i8> %x, i32 3 299 /// %y1 = extractelement <4 x i8> %y, i32 1 300 /// %y2 = extractelement <4 x i8> %y, i32 2 301 /// %x0x0 = mul i8 %x0, %x0 302 /// %x3x3 = mul i8 %x3, %x3 303 /// %y1y1 = mul i8 %y1, %y1 304 /// %y2y2 = mul i8 %y2, %y2 305 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0 306 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1 307 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2 308 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3 309 /// ret <4 x i8> %ins4 310 /// can be transformed into: 311 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5, 312 /// i32 6> 313 /// %2 = mul <4 x i8> %1, %1 314 /// ret <4 x i8> %2 315 /// We convert this initially to something like: 316 /// %x0 = extractelement <4 x i8> %x, i32 0 317 /// %x3 = extractelement <4 x i8> %x, i32 3 318 /// %y1 = extractelement <4 x i8> %y, i32 1 319 /// %y2 = extractelement <4 x i8> %y, i32 2 320 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0 321 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1 322 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2 323 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3 324 /// %5 = mul <4 x i8> %4, %4 325 /// %6 = extractelement <4 x i8> %5, i32 0 326 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0 327 /// %7 = extractelement <4 x i8> %5, i32 1 328 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1 329 /// %8 = extractelement <4 x i8> %5, i32 2 330 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2 331 /// %9 = extractelement <4 x i8> %5, i32 3 332 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3 333 /// ret <4 x i8> %ins4 334 /// InstCombiner transforms this into a shuffle and vector mul 335 /// Mask will return the Shuffle Mask equivalent to the extracted elements. 336 /// TODO: Can we split off and reuse the shuffle mask detection from 337 /// TargetTransformInfo::getInstructionThroughput? 338 static Optional<TargetTransformInfo::ShuffleKind> 339 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) { 340 const auto *It = 341 find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); }); 342 if (It == VL.end()) 343 return None; 344 auto *EI0 = cast<ExtractElementInst>(*It); 345 if (isa<ScalableVectorType>(EI0->getVectorOperandType())) 346 return None; 347 unsigned Size = 348 cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements(); 349 Value *Vec1 = nullptr; 350 Value *Vec2 = nullptr; 351 enum ShuffleMode { Unknown, Select, Permute }; 352 ShuffleMode CommonShuffleMode = Unknown; 353 Mask.assign(VL.size(), UndefMaskElem); 354 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 355 // Undef can be represented as an undef element in a vector. 356 if (isa<UndefValue>(VL[I])) 357 continue; 358 auto *EI = cast<ExtractElementInst>(VL[I]); 359 if (isa<ScalableVectorType>(EI->getVectorOperandType())) 360 return None; 361 auto *Vec = EI->getVectorOperand(); 362 // We can extractelement from undef or poison vector. 363 if (isUndefVector(Vec)) 364 continue; 365 // All vector operands must have the same number of vector elements. 366 if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size) 367 return None; 368 if (isa<UndefValue>(EI->getIndexOperand())) 369 continue; 370 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand()); 371 if (!Idx) 372 return None; 373 // Undefined behavior if Idx is negative or >= Size. 374 if (Idx->getValue().uge(Size)) 375 continue; 376 unsigned IntIdx = Idx->getValue().getZExtValue(); 377 Mask[I] = IntIdx; 378 // For correct shuffling we have to have at most 2 different vector operands 379 // in all extractelement instructions. 380 if (!Vec1 || Vec1 == Vec) { 381 Vec1 = Vec; 382 } else if (!Vec2 || Vec2 == Vec) { 383 Vec2 = Vec; 384 Mask[I] += Size; 385 } else { 386 return None; 387 } 388 if (CommonShuffleMode == Permute) 389 continue; 390 // If the extract index is not the same as the operation number, it is a 391 // permutation. 392 if (IntIdx != I) { 393 CommonShuffleMode = Permute; 394 continue; 395 } 396 CommonShuffleMode = Select; 397 } 398 // If we're not crossing lanes in different vectors, consider it as blending. 399 if (CommonShuffleMode == Select && Vec2) 400 return TargetTransformInfo::SK_Select; 401 // If Vec2 was never used, we have a permutation of a single vector, otherwise 402 // we have permutation of 2 vectors. 403 return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc 404 : TargetTransformInfo::SK_PermuteSingleSrc; 405 } 406 407 namespace { 408 409 /// Main data required for vectorization of instructions. 410 struct InstructionsState { 411 /// The very first instruction in the list with the main opcode. 412 Value *OpValue = nullptr; 413 414 /// The main/alternate instruction. 415 Instruction *MainOp = nullptr; 416 Instruction *AltOp = nullptr; 417 418 /// The main/alternate opcodes for the list of instructions. 419 unsigned getOpcode() const { 420 return MainOp ? MainOp->getOpcode() : 0; 421 } 422 423 unsigned getAltOpcode() const { 424 return AltOp ? AltOp->getOpcode() : 0; 425 } 426 427 /// Some of the instructions in the list have alternate opcodes. 428 bool isAltShuffle() const { return AltOp != MainOp; } 429 430 bool isOpcodeOrAlt(Instruction *I) const { 431 unsigned CheckedOpcode = I->getOpcode(); 432 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode; 433 } 434 435 InstructionsState() = delete; 436 InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp) 437 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {} 438 }; 439 440 } // end anonymous namespace 441 442 /// Chooses the correct key for scheduling data. If \p Op has the same (or 443 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p 444 /// OpValue. 445 static Value *isOneOf(const InstructionsState &S, Value *Op) { 446 auto *I = dyn_cast<Instruction>(Op); 447 if (I && S.isOpcodeOrAlt(I)) 448 return Op; 449 return S.OpValue; 450 } 451 452 /// \returns true if \p Opcode is allowed as part of of the main/alternate 453 /// instruction for SLP vectorization. 454 /// 455 /// Example of unsupported opcode is SDIV that can potentially cause UB if the 456 /// "shuffled out" lane would result in division by zero. 457 static bool isValidForAlternation(unsigned Opcode) { 458 if (Instruction::isIntDivRem(Opcode)) 459 return false; 460 461 return true; 462 } 463 464 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 465 unsigned BaseIndex = 0); 466 467 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e. 468 /// compatible instructions or constants, or just some other regular values. 469 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0, 470 Value *Op1) { 471 return (isConstant(BaseOp0) && isConstant(Op0)) || 472 (isConstant(BaseOp1) && isConstant(Op1)) || 473 (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) && 474 !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) || 475 getSameOpcode({BaseOp0, Op0}).getOpcode() || 476 getSameOpcode({BaseOp1, Op1}).getOpcode(); 477 } 478 479 /// \returns analysis of the Instructions in \p VL described in 480 /// InstructionsState, the Opcode that we suppose the whole list 481 /// could be vectorized even if its structure is diverse. 482 static InstructionsState getSameOpcode(ArrayRef<Value *> VL, 483 unsigned BaseIndex) { 484 // Make sure these are all Instructions. 485 if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); })) 486 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 487 488 bool IsCastOp = isa<CastInst>(VL[BaseIndex]); 489 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]); 490 bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]); 491 CmpInst::Predicate BasePred = 492 IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate() 493 : CmpInst::BAD_ICMP_PREDICATE; 494 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode(); 495 unsigned AltOpcode = Opcode; 496 unsigned AltIndex = BaseIndex; 497 498 // Check for one alternate opcode from another BinaryOperator. 499 // TODO - generalize to support all operators (types, calls etc.). 500 for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) { 501 unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode(); 502 if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) { 503 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 504 continue; 505 if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) && 506 isValidForAlternation(Opcode)) { 507 AltOpcode = InstOpcode; 508 AltIndex = Cnt; 509 continue; 510 } 511 } else if (IsCastOp && isa<CastInst>(VL[Cnt])) { 512 Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType(); 513 Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType(); 514 if (Ty0 == Ty1) { 515 if (InstOpcode == Opcode || InstOpcode == AltOpcode) 516 continue; 517 if (Opcode == AltOpcode) { 518 assert(isValidForAlternation(Opcode) && 519 isValidForAlternation(InstOpcode) && 520 "Cast isn't safe for alternation, logic needs to be updated!"); 521 AltOpcode = InstOpcode; 522 AltIndex = Cnt; 523 continue; 524 } 525 } 526 } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) { 527 auto *BaseInst = cast<Instruction>(VL[BaseIndex]); 528 auto *Inst = cast<Instruction>(VL[Cnt]); 529 Type *Ty0 = BaseInst->getOperand(0)->getType(); 530 Type *Ty1 = Inst->getOperand(0)->getType(); 531 if (Ty0 == Ty1) { 532 Value *BaseOp0 = BaseInst->getOperand(0); 533 Value *BaseOp1 = BaseInst->getOperand(1); 534 Value *Op0 = Inst->getOperand(0); 535 Value *Op1 = Inst->getOperand(1); 536 CmpInst::Predicate CurrentPred = 537 cast<CmpInst>(VL[Cnt])->getPredicate(); 538 CmpInst::Predicate SwappedCurrentPred = 539 CmpInst::getSwappedPredicate(CurrentPred); 540 // Check for compatible operands. If the corresponding operands are not 541 // compatible - need to perform alternate vectorization. 542 if (InstOpcode == Opcode) { 543 if (BasePred == CurrentPred && 544 areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1)) 545 continue; 546 if (BasePred == SwappedCurrentPred && 547 areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0)) 548 continue; 549 if (E == 2 && 550 (BasePred == CurrentPred || BasePred == SwappedCurrentPred)) 551 continue; 552 auto *AltInst = cast<CmpInst>(VL[AltIndex]); 553 CmpInst::Predicate AltPred = AltInst->getPredicate(); 554 Value *AltOp0 = AltInst->getOperand(0); 555 Value *AltOp1 = AltInst->getOperand(1); 556 // Check if operands are compatible with alternate operands. 557 if (AltPred == CurrentPred && 558 areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1)) 559 continue; 560 if (AltPred == SwappedCurrentPred && 561 areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0)) 562 continue; 563 } 564 if (BaseIndex == AltIndex && BasePred != CurrentPred) { 565 assert(isValidForAlternation(Opcode) && 566 isValidForAlternation(InstOpcode) && 567 "Cast isn't safe for alternation, logic needs to be updated!"); 568 AltIndex = Cnt; 569 continue; 570 } 571 auto *AltInst = cast<CmpInst>(VL[AltIndex]); 572 CmpInst::Predicate AltPred = AltInst->getPredicate(); 573 if (BasePred == CurrentPred || BasePred == SwappedCurrentPred || 574 AltPred == CurrentPred || AltPred == SwappedCurrentPred) 575 continue; 576 } 577 } else if (InstOpcode == Opcode || InstOpcode == AltOpcode) 578 continue; 579 return InstructionsState(VL[BaseIndex], nullptr, nullptr); 580 } 581 582 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]), 583 cast<Instruction>(VL[AltIndex])); 584 } 585 586 /// \returns true if all of the values in \p VL have the same type or false 587 /// otherwise. 588 static bool allSameType(ArrayRef<Value *> VL) { 589 Type *Ty = VL[0]->getType(); 590 for (int i = 1, e = VL.size(); i < e; i++) 591 if (VL[i]->getType() != Ty) 592 return false; 593 594 return true; 595 } 596 597 /// \returns True if Extract{Value,Element} instruction extracts element Idx. 598 static Optional<unsigned> getExtractIndex(Instruction *E) { 599 unsigned Opcode = E->getOpcode(); 600 assert((Opcode == Instruction::ExtractElement || 601 Opcode == Instruction::ExtractValue) && 602 "Expected extractelement or extractvalue instruction."); 603 if (Opcode == Instruction::ExtractElement) { 604 auto *CI = dyn_cast<ConstantInt>(E->getOperand(1)); 605 if (!CI) 606 return None; 607 return CI->getZExtValue(); 608 } 609 ExtractValueInst *EI = cast<ExtractValueInst>(E); 610 if (EI->getNumIndices() != 1) 611 return None; 612 return *EI->idx_begin(); 613 } 614 615 /// \returns True if in-tree use also needs extract. This refers to 616 /// possible scalar operand in vectorized instruction. 617 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst, 618 TargetLibraryInfo *TLI) { 619 unsigned Opcode = UserInst->getOpcode(); 620 switch (Opcode) { 621 case Instruction::Load: { 622 LoadInst *LI = cast<LoadInst>(UserInst); 623 return (LI->getPointerOperand() == Scalar); 624 } 625 case Instruction::Store: { 626 StoreInst *SI = cast<StoreInst>(UserInst); 627 return (SI->getPointerOperand() == Scalar); 628 } 629 case Instruction::Call: { 630 CallInst *CI = cast<CallInst>(UserInst); 631 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 632 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 633 if (hasVectorInstrinsicScalarOpd(ID, i)) 634 return (CI->getArgOperand(i) == Scalar); 635 } 636 LLVM_FALLTHROUGH; 637 } 638 default: 639 return false; 640 } 641 } 642 643 /// \returns the AA location that is being access by the instruction. 644 static MemoryLocation getLocation(Instruction *I) { 645 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 646 return MemoryLocation::get(SI); 647 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 648 return MemoryLocation::get(LI); 649 return MemoryLocation(); 650 } 651 652 /// \returns True if the instruction is not a volatile or atomic load/store. 653 static bool isSimple(Instruction *I) { 654 if (LoadInst *LI = dyn_cast<LoadInst>(I)) 655 return LI->isSimple(); 656 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 657 return SI->isSimple(); 658 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I)) 659 return !MI->isVolatile(); 660 return true; 661 } 662 663 /// Shuffles \p Mask in accordance with the given \p SubMask. 664 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) { 665 if (SubMask.empty()) 666 return; 667 if (Mask.empty()) { 668 Mask.append(SubMask.begin(), SubMask.end()); 669 return; 670 } 671 SmallVector<int> NewMask(SubMask.size(), UndefMaskElem); 672 int TermValue = std::min(Mask.size(), SubMask.size()); 673 for (int I = 0, E = SubMask.size(); I < E; ++I) { 674 if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem || 675 Mask[SubMask[I]] >= TermValue) 676 continue; 677 NewMask[I] = Mask[SubMask[I]]; 678 } 679 Mask.swap(NewMask); 680 } 681 682 /// Order may have elements assigned special value (size) which is out of 683 /// bounds. Such indices only appear on places which correspond to undef values 684 /// (see canReuseExtract for details) and used in order to avoid undef values 685 /// have effect on operands ordering. 686 /// The first loop below simply finds all unused indices and then the next loop 687 /// nest assigns these indices for undef values positions. 688 /// As an example below Order has two undef positions and they have assigned 689 /// values 3 and 7 respectively: 690 /// before: 6 9 5 4 9 2 1 0 691 /// after: 6 3 5 4 7 2 1 0 692 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) { 693 const unsigned Sz = Order.size(); 694 SmallBitVector UnusedIndices(Sz, /*t=*/true); 695 SmallBitVector MaskedIndices(Sz); 696 for (unsigned I = 0; I < Sz; ++I) { 697 if (Order[I] < Sz) 698 UnusedIndices.reset(Order[I]); 699 else 700 MaskedIndices.set(I); 701 } 702 if (MaskedIndices.none()) 703 return; 704 assert(UnusedIndices.count() == MaskedIndices.count() && 705 "Non-synced masked/available indices."); 706 int Idx = UnusedIndices.find_first(); 707 int MIdx = MaskedIndices.find_first(); 708 while (MIdx >= 0) { 709 assert(Idx >= 0 && "Indices must be synced."); 710 Order[MIdx] = Idx; 711 Idx = UnusedIndices.find_next(Idx); 712 MIdx = MaskedIndices.find_next(MIdx); 713 } 714 } 715 716 namespace llvm { 717 718 static void inversePermutation(ArrayRef<unsigned> Indices, 719 SmallVectorImpl<int> &Mask) { 720 Mask.clear(); 721 const unsigned E = Indices.size(); 722 Mask.resize(E, UndefMaskElem); 723 for (unsigned I = 0; I < E; ++I) 724 Mask[Indices[I]] = I; 725 } 726 727 /// \returns inserting index of InsertElement or InsertValue instruction, 728 /// using Offset as base offset for index. 729 static Optional<unsigned> getInsertIndex(Value *InsertInst, 730 unsigned Offset = 0) { 731 int Index = Offset; 732 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) { 733 if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) { 734 auto *VT = cast<FixedVectorType>(IE->getType()); 735 if (CI->getValue().uge(VT->getNumElements())) 736 return None; 737 Index *= VT->getNumElements(); 738 Index += CI->getZExtValue(); 739 return Index; 740 } 741 return None; 742 } 743 744 auto *IV = cast<InsertValueInst>(InsertInst); 745 Type *CurrentType = IV->getType(); 746 for (unsigned I : IV->indices()) { 747 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 748 Index *= ST->getNumElements(); 749 CurrentType = ST->getElementType(I); 750 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 751 Index *= AT->getNumElements(); 752 CurrentType = AT->getElementType(); 753 } else { 754 return None; 755 } 756 Index += I; 757 } 758 return Index; 759 } 760 761 /// Reorders the list of scalars in accordance with the given \p Mask. 762 static void reorderScalars(SmallVectorImpl<Value *> &Scalars, 763 ArrayRef<int> Mask) { 764 assert(!Mask.empty() && "Expected non-empty mask."); 765 SmallVector<Value *> Prev(Scalars.size(), 766 UndefValue::get(Scalars.front()->getType())); 767 Prev.swap(Scalars); 768 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 769 if (Mask[I] != UndefMaskElem) 770 Scalars[Mask[I]] = Prev[I]; 771 } 772 773 /// Checks if the provided value does not require scheduling. It does not 774 /// require scheduling if this is not an instruction or it is an instruction 775 /// that does not read/write memory and all operands are either not instructions 776 /// or phi nodes or instructions from different blocks. 777 static bool areAllOperandsNonInsts(Value *V) { 778 auto *I = dyn_cast<Instruction>(V); 779 if (!I) 780 return true; 781 return !I->mayReadOrWriteMemory() && all_of(I->operands(), [I](Value *V) { 782 auto *IO = dyn_cast<Instruction>(V); 783 if (!IO) 784 return true; 785 return isa<PHINode>(IO) || IO->getParent() != I->getParent(); 786 }); 787 } 788 789 /// Checks if the provided value does not require scheduling. It does not 790 /// require scheduling if this is not an instruction or it is an instruction 791 /// that does not read/write memory and all users are phi nodes or instructions 792 /// from the different blocks. 793 static bool isUsedOutsideBlock(Value *V) { 794 auto *I = dyn_cast<Instruction>(V); 795 if (!I) 796 return true; 797 // Limits the number of uses to save compile time. 798 constexpr int UsesLimit = 8; 799 return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) && 800 all_of(I->users(), [I](User *U) { 801 auto *IU = dyn_cast<Instruction>(U); 802 if (!IU) 803 return true; 804 return IU->getParent() != I->getParent() || isa<PHINode>(IU); 805 }); 806 } 807 808 /// Checks if the specified value does not require scheduling. It does not 809 /// require scheduling if all operands and all users do not need to be scheduled 810 /// in the current basic block. 811 static bool doesNotNeedToBeScheduled(Value *V) { 812 return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V); 813 } 814 815 /// Checks if the specified array of instructions does not require scheduling. 816 /// It is so if all either instructions have operands that do not require 817 /// scheduling or their users do not require scheduling since they are phis or 818 /// in other basic blocks. 819 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) { 820 return !VL.empty() && 821 (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts)); 822 } 823 824 namespace slpvectorizer { 825 826 /// Bottom Up SLP Vectorizer. 827 class BoUpSLP { 828 struct TreeEntry; 829 struct ScheduleData; 830 831 public: 832 using ValueList = SmallVector<Value *, 8>; 833 using InstrList = SmallVector<Instruction *, 16>; 834 using ValueSet = SmallPtrSet<Value *, 16>; 835 using StoreList = SmallVector<StoreInst *, 8>; 836 using ExtraValueToDebugLocsMap = 837 MapVector<Value *, SmallVector<Instruction *, 2>>; 838 using OrdersType = SmallVector<unsigned, 4>; 839 840 BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti, 841 TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li, 842 DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB, 843 const DataLayout *DL, OptimizationRemarkEmitter *ORE) 844 : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li), 845 DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) { 846 CodeMetrics::collectEphemeralValues(F, AC, EphValues); 847 // Use the vector register size specified by the target unless overridden 848 // by a command-line option. 849 // TODO: It would be better to limit the vectorization factor based on 850 // data type rather than just register size. For example, x86 AVX has 851 // 256-bit registers, but it does not support integer operations 852 // at that width (that requires AVX2). 853 if (MaxVectorRegSizeOption.getNumOccurrences()) 854 MaxVecRegSize = MaxVectorRegSizeOption; 855 else 856 MaxVecRegSize = 857 TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector) 858 .getFixedSize(); 859 860 if (MinVectorRegSizeOption.getNumOccurrences()) 861 MinVecRegSize = MinVectorRegSizeOption; 862 else 863 MinVecRegSize = TTI->getMinVectorRegisterBitWidth(); 864 } 865 866 /// Vectorize the tree that starts with the elements in \p VL. 867 /// Returns the vectorized root. 868 Value *vectorizeTree(); 869 870 /// Vectorize the tree but with the list of externally used values \p 871 /// ExternallyUsedValues. Values in this MapVector can be replaced but the 872 /// generated extractvalue instructions. 873 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues); 874 875 /// \returns the cost incurred by unwanted spills and fills, caused by 876 /// holding live values over call sites. 877 InstructionCost getSpillCost() const; 878 879 /// \returns the vectorization cost of the subtree that starts at \p VL. 880 /// A negative number means that this is profitable. 881 InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None); 882 883 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for 884 /// the purpose of scheduling and extraction in the \p UserIgnoreLst. 885 void buildTree(ArrayRef<Value *> Roots, 886 ArrayRef<Value *> UserIgnoreLst = None); 887 888 /// Builds external uses of the vectorized scalars, i.e. the list of 889 /// vectorized scalars to be extracted, their lanes and their scalar users. \p 890 /// ExternallyUsedValues contains additional list of external uses to handle 891 /// vectorization of reductions. 892 void 893 buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {}); 894 895 /// Clear the internal data structures that are created by 'buildTree'. 896 void deleteTree() { 897 VectorizableTree.clear(); 898 ScalarToTreeEntry.clear(); 899 MustGather.clear(); 900 ExternalUses.clear(); 901 for (auto &Iter : BlocksSchedules) { 902 BlockScheduling *BS = Iter.second.get(); 903 BS->clear(); 904 } 905 MinBWs.clear(); 906 InstrElementSize.clear(); 907 } 908 909 unsigned getTreeSize() const { return VectorizableTree.size(); } 910 911 /// Perform LICM and CSE on the newly generated gather sequences. 912 void optimizeGatherSequence(); 913 914 /// Checks if the specified gather tree entry \p TE can be represented as a 915 /// shuffled vector entry + (possibly) permutation with other gathers. It 916 /// implements the checks only for possibly ordered scalars (Loads, 917 /// ExtractElement, ExtractValue), which can be part of the graph. 918 Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE); 919 920 /// Gets reordering data for the given tree entry. If the entry is vectorized 921 /// - just return ReorderIndices, otherwise check if the scalars can be 922 /// reordered and return the most optimal order. 923 /// \param TopToBottom If true, include the order of vectorized stores and 924 /// insertelement nodes, otherwise skip them. 925 Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom); 926 927 /// Reorders the current graph to the most profitable order starting from the 928 /// root node to the leaf nodes. The best order is chosen only from the nodes 929 /// of the same size (vectorization factor). Smaller nodes are considered 930 /// parts of subgraph with smaller VF and they are reordered independently. We 931 /// can make it because we still need to extend smaller nodes to the wider VF 932 /// and we can merge reordering shuffles with the widening shuffles. 933 void reorderTopToBottom(); 934 935 /// Reorders the current graph to the most profitable order starting from 936 /// leaves to the root. It allows to rotate small subgraphs and reduce the 937 /// number of reshuffles if the leaf nodes use the same order. In this case we 938 /// can merge the orders and just shuffle user node instead of shuffling its 939 /// operands. Plus, even the leaf nodes have different orders, it allows to 940 /// sink reordering in the graph closer to the root node and merge it later 941 /// during analysis. 942 void reorderBottomToTop(bool IgnoreReorder = false); 943 944 /// \return The vector element size in bits to use when vectorizing the 945 /// expression tree ending at \p V. If V is a store, the size is the width of 946 /// the stored value. Otherwise, the size is the width of the largest loaded 947 /// value reaching V. This method is used by the vectorizer to calculate 948 /// vectorization factors. 949 unsigned getVectorElementSize(Value *V); 950 951 /// Compute the minimum type sizes required to represent the entries in a 952 /// vectorizable tree. 953 void computeMinimumValueSizes(); 954 955 // \returns maximum vector register size as set by TTI or overridden by cl::opt. 956 unsigned getMaxVecRegSize() const { 957 return MaxVecRegSize; 958 } 959 960 // \returns minimum vector register size as set by cl::opt. 961 unsigned getMinVecRegSize() const { 962 return MinVecRegSize; 963 } 964 965 unsigned getMinVF(unsigned Sz) const { 966 return std::max(2U, getMinVecRegSize() / Sz); 967 } 968 969 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const { 970 unsigned MaxVF = MaxVFOption.getNumOccurrences() ? 971 MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode); 972 return MaxVF ? MaxVF : UINT_MAX; 973 } 974 975 /// Check if homogeneous aggregate is isomorphic to some VectorType. 976 /// Accepts homogeneous multidimensional aggregate of scalars/vectors like 977 /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> }, 978 /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on. 979 /// 980 /// \returns number of elements in vector if isomorphism exists, 0 otherwise. 981 unsigned canMapToVector(Type *T, const DataLayout &DL) const; 982 983 /// \returns True if the VectorizableTree is both tiny and not fully 984 /// vectorizable. We do not vectorize such trees. 985 bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const; 986 987 /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values 988 /// can be load combined in the backend. Load combining may not be allowed in 989 /// the IR optimizer, so we do not want to alter the pattern. For example, 990 /// partially transforming a scalar bswap() pattern into vector code is 991 /// effectively impossible for the backend to undo. 992 /// TODO: If load combining is allowed in the IR optimizer, this analysis 993 /// may not be necessary. 994 bool isLoadCombineReductionCandidate(RecurKind RdxKind) const; 995 996 /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values 997 /// can be load combined in the backend. Load combining may not be allowed in 998 /// the IR optimizer, so we do not want to alter the pattern. For example, 999 /// partially transforming a scalar bswap() pattern into vector code is 1000 /// effectively impossible for the backend to undo. 1001 /// TODO: If load combining is allowed in the IR optimizer, this analysis 1002 /// may not be necessary. 1003 bool isLoadCombineCandidate() const; 1004 1005 OptimizationRemarkEmitter *getORE() { return ORE; } 1006 1007 /// This structure holds any data we need about the edges being traversed 1008 /// during buildTree_rec(). We keep track of: 1009 /// (i) the user TreeEntry index, and 1010 /// (ii) the index of the edge. 1011 struct EdgeInfo { 1012 EdgeInfo() = default; 1013 EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx) 1014 : UserTE(UserTE), EdgeIdx(EdgeIdx) {} 1015 /// The user TreeEntry. 1016 TreeEntry *UserTE = nullptr; 1017 /// The operand index of the use. 1018 unsigned EdgeIdx = UINT_MAX; 1019 #ifndef NDEBUG 1020 friend inline raw_ostream &operator<<(raw_ostream &OS, 1021 const BoUpSLP::EdgeInfo &EI) { 1022 EI.dump(OS); 1023 return OS; 1024 } 1025 /// Debug print. 1026 void dump(raw_ostream &OS) const { 1027 OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null") 1028 << " EdgeIdx:" << EdgeIdx << "}"; 1029 } 1030 LLVM_DUMP_METHOD void dump() const { dump(dbgs()); } 1031 #endif 1032 }; 1033 1034 /// A helper data structure to hold the operands of a vector of instructions. 1035 /// This supports a fixed vector length for all operand vectors. 1036 class VLOperands { 1037 /// For each operand we need (i) the value, and (ii) the opcode that it 1038 /// would be attached to if the expression was in a left-linearized form. 1039 /// This is required to avoid illegal operand reordering. 1040 /// For example: 1041 /// \verbatim 1042 /// 0 Op1 1043 /// |/ 1044 /// Op1 Op2 Linearized + Op2 1045 /// \ / ----------> |/ 1046 /// - - 1047 /// 1048 /// Op1 - Op2 (0 + Op1) - Op2 1049 /// \endverbatim 1050 /// 1051 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'. 1052 /// 1053 /// Another way to think of this is to track all the operations across the 1054 /// path from the operand all the way to the root of the tree and to 1055 /// calculate the operation that corresponds to this path. For example, the 1056 /// path from Op2 to the root crosses the RHS of the '-', therefore the 1057 /// corresponding operation is a '-' (which matches the one in the 1058 /// linearized tree, as shown above). 1059 /// 1060 /// For lack of a better term, we refer to this operation as Accumulated 1061 /// Path Operation (APO). 1062 struct OperandData { 1063 OperandData() = default; 1064 OperandData(Value *V, bool APO, bool IsUsed) 1065 : V(V), APO(APO), IsUsed(IsUsed) {} 1066 /// The operand value. 1067 Value *V = nullptr; 1068 /// TreeEntries only allow a single opcode, or an alternate sequence of 1069 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the 1070 /// APO. It is set to 'true' if 'V' is attached to an inverse operation 1071 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise 1072 /// (e.g., Add/Mul) 1073 bool APO = false; 1074 /// Helper data for the reordering function. 1075 bool IsUsed = false; 1076 }; 1077 1078 /// During operand reordering, we are trying to select the operand at lane 1079 /// that matches best with the operand at the neighboring lane. Our 1080 /// selection is based on the type of value we are looking for. For example, 1081 /// if the neighboring lane has a load, we need to look for a load that is 1082 /// accessing a consecutive address. These strategies are summarized in the 1083 /// 'ReorderingMode' enumerator. 1084 enum class ReorderingMode { 1085 Load, ///< Matching loads to consecutive memory addresses 1086 Opcode, ///< Matching instructions based on opcode (same or alternate) 1087 Constant, ///< Matching constants 1088 Splat, ///< Matching the same instruction multiple times (broadcast) 1089 Failed, ///< We failed to create a vectorizable group 1090 }; 1091 1092 using OperandDataVec = SmallVector<OperandData, 2>; 1093 1094 /// A vector of operand vectors. 1095 SmallVector<OperandDataVec, 4> OpsVec; 1096 1097 const DataLayout &DL; 1098 ScalarEvolution &SE; 1099 const BoUpSLP &R; 1100 1101 /// \returns the operand data at \p OpIdx and \p Lane. 1102 OperandData &getData(unsigned OpIdx, unsigned Lane) { 1103 return OpsVec[OpIdx][Lane]; 1104 } 1105 1106 /// \returns the operand data at \p OpIdx and \p Lane. Const version. 1107 const OperandData &getData(unsigned OpIdx, unsigned Lane) const { 1108 return OpsVec[OpIdx][Lane]; 1109 } 1110 1111 /// Clears the used flag for all entries. 1112 void clearUsed() { 1113 for (unsigned OpIdx = 0, NumOperands = getNumOperands(); 1114 OpIdx != NumOperands; ++OpIdx) 1115 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes; 1116 ++Lane) 1117 OpsVec[OpIdx][Lane].IsUsed = false; 1118 } 1119 1120 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2. 1121 void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) { 1122 std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]); 1123 } 1124 1125 // The hard-coded scores listed here are not very important, though it shall 1126 // be higher for better matches to improve the resulting cost. When 1127 // computing the scores of matching one sub-tree with another, we are 1128 // basically counting the number of values that are matching. So even if all 1129 // scores are set to 1, we would still get a decent matching result. 1130 // However, sometimes we have to break ties. For example we may have to 1131 // choose between matching loads vs matching opcodes. This is what these 1132 // scores are helping us with: they provide the order of preference. Also, 1133 // this is important if the scalar is externally used or used in another 1134 // tree entry node in the different lane. 1135 1136 /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]). 1137 static const int ScoreConsecutiveLoads = 4; 1138 /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]). 1139 static const int ScoreReversedLoads = 3; 1140 /// ExtractElementInst from same vector and consecutive indexes. 1141 static const int ScoreConsecutiveExtracts = 4; 1142 /// ExtractElementInst from same vector and reversed indices. 1143 static const int ScoreReversedExtracts = 3; 1144 /// Constants. 1145 static const int ScoreConstants = 2; 1146 /// Instructions with the same opcode. 1147 static const int ScoreSameOpcode = 2; 1148 /// Instructions with alt opcodes (e.g, add + sub). 1149 static const int ScoreAltOpcodes = 1; 1150 /// Identical instructions (a.k.a. splat or broadcast). 1151 static const int ScoreSplat = 1; 1152 /// Matching with an undef is preferable to failing. 1153 static const int ScoreUndef = 1; 1154 /// Score for failing to find a decent match. 1155 static const int ScoreFail = 0; 1156 /// Score if all users are vectorized. 1157 static const int ScoreAllUserVectorized = 1; 1158 1159 /// \returns the score of placing \p V1 and \p V2 in consecutive lanes. 1160 /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p 1161 /// MainAltOps. 1162 static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL, 1163 ScalarEvolution &SE, int NumLanes, 1164 ArrayRef<Value *> MainAltOps) { 1165 if (V1 == V2) 1166 return VLOperands::ScoreSplat; 1167 1168 auto *LI1 = dyn_cast<LoadInst>(V1); 1169 auto *LI2 = dyn_cast<LoadInst>(V2); 1170 if (LI1 && LI2) { 1171 if (LI1->getParent() != LI2->getParent()) 1172 return VLOperands::ScoreFail; 1173 1174 Optional<int> Dist = getPointersDiff( 1175 LI1->getType(), LI1->getPointerOperand(), LI2->getType(), 1176 LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true); 1177 if (!Dist || *Dist == 0) 1178 return VLOperands::ScoreFail; 1179 // The distance is too large - still may be profitable to use masked 1180 // loads/gathers. 1181 if (std::abs(*Dist) > NumLanes / 2) 1182 return VLOperands::ScoreAltOpcodes; 1183 // This still will detect consecutive loads, but we might have "holes" 1184 // in some cases. It is ok for non-power-2 vectorization and may produce 1185 // better results. It should not affect current vectorization. 1186 return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads 1187 : VLOperands::ScoreReversedLoads; 1188 } 1189 1190 auto *C1 = dyn_cast<Constant>(V1); 1191 auto *C2 = dyn_cast<Constant>(V2); 1192 if (C1 && C2) 1193 return VLOperands::ScoreConstants; 1194 1195 // Extracts from consecutive indexes of the same vector better score as 1196 // the extracts could be optimized away. 1197 Value *EV1; 1198 ConstantInt *Ex1Idx; 1199 if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) { 1200 // Undefs are always profitable for extractelements. 1201 if (isa<UndefValue>(V2)) 1202 return VLOperands::ScoreConsecutiveExtracts; 1203 Value *EV2 = nullptr; 1204 ConstantInt *Ex2Idx = nullptr; 1205 if (match(V2, 1206 m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx), 1207 m_Undef())))) { 1208 // Undefs are always profitable for extractelements. 1209 if (!Ex2Idx) 1210 return VLOperands::ScoreConsecutiveExtracts; 1211 if (isUndefVector(EV2) && EV2->getType() == EV1->getType()) 1212 return VLOperands::ScoreConsecutiveExtracts; 1213 if (EV2 == EV1) { 1214 int Idx1 = Ex1Idx->getZExtValue(); 1215 int Idx2 = Ex2Idx->getZExtValue(); 1216 int Dist = Idx2 - Idx1; 1217 // The distance is too large - still may be profitable to use 1218 // shuffles. 1219 if (std::abs(Dist) == 0) 1220 return VLOperands::ScoreSplat; 1221 if (std::abs(Dist) > NumLanes / 2) 1222 return VLOperands::ScoreSameOpcode; 1223 return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts 1224 : VLOperands::ScoreReversedExtracts; 1225 } 1226 return VLOperands::ScoreAltOpcodes; 1227 } 1228 return VLOperands::ScoreFail; 1229 } 1230 1231 auto *I1 = dyn_cast<Instruction>(V1); 1232 auto *I2 = dyn_cast<Instruction>(V2); 1233 if (I1 && I2) { 1234 if (I1->getParent() != I2->getParent()) 1235 return VLOperands::ScoreFail; 1236 SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end()); 1237 Ops.push_back(I1); 1238 Ops.push_back(I2); 1239 InstructionsState S = getSameOpcode(Ops); 1240 // Note: Only consider instructions with <= 2 operands to avoid 1241 // complexity explosion. 1242 if (S.getOpcode() && 1243 (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() || 1244 !S.isAltShuffle()) && 1245 all_of(Ops, [&S](Value *V) { 1246 return cast<Instruction>(V)->getNumOperands() == 1247 S.MainOp->getNumOperands(); 1248 })) 1249 return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes 1250 : VLOperands::ScoreSameOpcode; 1251 } 1252 1253 if (isa<UndefValue>(V2)) 1254 return VLOperands::ScoreUndef; 1255 1256 return VLOperands::ScoreFail; 1257 } 1258 1259 /// \param Lane lane of the operands under analysis. 1260 /// \param OpIdx operand index in \p Lane lane we're looking the best 1261 /// candidate for. 1262 /// \param Idx operand index of the current candidate value. 1263 /// \returns The additional score due to possible broadcasting of the 1264 /// elements in the lane. It is more profitable to have power-of-2 unique 1265 /// elements in the lane, it will be vectorized with higher probability 1266 /// after removing duplicates. Currently the SLP vectorizer supports only 1267 /// vectorization of the power-of-2 number of unique scalars. 1268 int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { 1269 Value *IdxLaneV = getData(Idx, Lane).V; 1270 if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V) 1271 return 0; 1272 SmallPtrSet<Value *, 4> Uniques; 1273 for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) { 1274 if (Ln == Lane) 1275 continue; 1276 Value *OpIdxLnV = getData(OpIdx, Ln).V; 1277 if (!isa<Instruction>(OpIdxLnV)) 1278 return 0; 1279 Uniques.insert(OpIdxLnV); 1280 } 1281 int UniquesCount = Uniques.size(); 1282 int UniquesCntWithIdxLaneV = 1283 Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1; 1284 Value *OpIdxLaneV = getData(OpIdx, Lane).V; 1285 int UniquesCntWithOpIdxLaneV = 1286 Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1; 1287 if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV) 1288 return 0; 1289 return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) - 1290 UniquesCntWithOpIdxLaneV) - 1291 (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV); 1292 } 1293 1294 /// \param Lane lane of the operands under analysis. 1295 /// \param OpIdx operand index in \p Lane lane we're looking the best 1296 /// candidate for. 1297 /// \param Idx operand index of the current candidate value. 1298 /// \returns The additional score for the scalar which users are all 1299 /// vectorized. 1300 int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const { 1301 Value *IdxLaneV = getData(Idx, Lane).V; 1302 Value *OpIdxLaneV = getData(OpIdx, Lane).V; 1303 // Do not care about number of uses for vector-like instructions 1304 // (extractelement/extractvalue with constant indices), they are extracts 1305 // themselves and already externally used. Vectorization of such 1306 // instructions does not add extra extractelement instruction, just may 1307 // remove it. 1308 if (isVectorLikeInstWithConstOps(IdxLaneV) && 1309 isVectorLikeInstWithConstOps(OpIdxLaneV)) 1310 return VLOperands::ScoreAllUserVectorized; 1311 auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV); 1312 if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV)) 1313 return 0; 1314 return R.areAllUsersVectorized(IdxLaneI, None) 1315 ? VLOperands::ScoreAllUserVectorized 1316 : 0; 1317 } 1318 1319 /// Go through the operands of \p LHS and \p RHS recursively until \p 1320 /// MaxLevel, and return the cummulative score. For example: 1321 /// \verbatim 1322 /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1] 1323 /// \ / \ / \ / \ / 1324 /// + + + + 1325 /// G1 G2 G3 G4 1326 /// \endverbatim 1327 /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at 1328 /// each level recursively, accumulating the score. It starts from matching 1329 /// the additions at level 0, then moves on to the loads (level 1). The 1330 /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and 1331 /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while 1332 /// {A[0],C[0]} has a score of VLOperands::ScoreFail. 1333 /// Please note that the order of the operands does not matter, as we 1334 /// evaluate the score of all profitable combinations of operands. In 1335 /// other words the score of G1 and G4 is the same as G1 and G2. This 1336 /// heuristic is based on ideas described in: 1337 /// Look-ahead SLP: Auto-vectorization in the presence of commutative 1338 /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha, 1339 /// Luís F. W. Góes 1340 int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel, 1341 ArrayRef<Value *> MainAltOps) { 1342 1343 // Get the shallow score of V1 and V2. 1344 int ShallowScoreAtThisLevel = 1345 getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps); 1346 1347 // If reached MaxLevel, 1348 // or if V1 and V2 are not instructions, 1349 // or if they are SPLAT, 1350 // or if they are not consecutive, 1351 // or if profitable to vectorize loads or extractelements, early return 1352 // the current cost. 1353 auto *I1 = dyn_cast<Instruction>(LHS); 1354 auto *I2 = dyn_cast<Instruction>(RHS); 1355 if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 || 1356 ShallowScoreAtThisLevel == VLOperands::ScoreFail || 1357 (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) || 1358 (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) || 1359 (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) && 1360 ShallowScoreAtThisLevel)) 1361 return ShallowScoreAtThisLevel; 1362 assert(I1 && I2 && "Should have early exited."); 1363 1364 // Contains the I2 operand indexes that got matched with I1 operands. 1365 SmallSet<unsigned, 4> Op2Used; 1366 1367 // Recursion towards the operands of I1 and I2. We are trying all possible 1368 // operand pairs, and keeping track of the best score. 1369 for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands(); 1370 OpIdx1 != NumOperands1; ++OpIdx1) { 1371 // Try to pair op1I with the best operand of I2. 1372 int MaxTmpScore = 0; 1373 unsigned MaxOpIdx2 = 0; 1374 bool FoundBest = false; 1375 // If I2 is commutative try all combinations. 1376 unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1; 1377 unsigned ToIdx = isCommutative(I2) 1378 ? I2->getNumOperands() 1379 : std::min(I2->getNumOperands(), OpIdx1 + 1); 1380 assert(FromIdx <= ToIdx && "Bad index"); 1381 for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) { 1382 // Skip operands already paired with OpIdx1. 1383 if (Op2Used.count(OpIdx2)) 1384 continue; 1385 // Recursively calculate the cost at each level 1386 int TmpScore = 1387 getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2), 1388 CurrLevel + 1, MaxLevel, None); 1389 // Look for the best score. 1390 if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) { 1391 MaxTmpScore = TmpScore; 1392 MaxOpIdx2 = OpIdx2; 1393 FoundBest = true; 1394 } 1395 } 1396 if (FoundBest) { 1397 // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it. 1398 Op2Used.insert(MaxOpIdx2); 1399 ShallowScoreAtThisLevel += MaxTmpScore; 1400 } 1401 } 1402 return ShallowScoreAtThisLevel; 1403 } 1404 1405 /// Score scaling factor for fully compatible instructions but with 1406 /// different number of external uses. Allows better selection of the 1407 /// instructions with less external uses. 1408 static const int ScoreScaleFactor = 10; 1409 1410 /// \Returns the look-ahead score, which tells us how much the sub-trees 1411 /// rooted at \p LHS and \p RHS match, the more they match the higher the 1412 /// score. This helps break ties in an informed way when we cannot decide on 1413 /// the order of the operands by just considering the immediate 1414 /// predecessors. 1415 int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps, 1416 int Lane, unsigned OpIdx, unsigned Idx, 1417 bool &IsUsed) { 1418 int Score = 1419 getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps); 1420 if (Score) { 1421 int SplatScore = getSplatScore(Lane, OpIdx, Idx); 1422 if (Score <= -SplatScore) { 1423 // Set the minimum score for splat-like sequence to avoid setting 1424 // failed state. 1425 Score = 1; 1426 } else { 1427 Score += SplatScore; 1428 // Scale score to see the difference between different operands 1429 // and similar operands but all vectorized/not all vectorized 1430 // uses. It does not affect actual selection of the best 1431 // compatible operand in general, just allows to select the 1432 // operand with all vectorized uses. 1433 Score *= ScoreScaleFactor; 1434 Score += getExternalUseScore(Lane, OpIdx, Idx); 1435 IsUsed = true; 1436 } 1437 } 1438 return Score; 1439 } 1440 1441 /// Best defined scores per lanes between the passes. Used to choose the 1442 /// best operand (with the highest score) between the passes. 1443 /// The key - {Operand Index, Lane}. 1444 /// The value - the best score between the passes for the lane and the 1445 /// operand. 1446 SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8> 1447 BestScoresPerLanes; 1448 1449 // Search all operands in Ops[*][Lane] for the one that matches best 1450 // Ops[OpIdx][LastLane] and return its opreand index. 1451 // If no good match can be found, return None. 1452 Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane, 1453 ArrayRef<ReorderingMode> ReorderingModes, 1454 ArrayRef<Value *> MainAltOps) { 1455 unsigned NumOperands = getNumOperands(); 1456 1457 // The operand of the previous lane at OpIdx. 1458 Value *OpLastLane = getData(OpIdx, LastLane).V; 1459 1460 // Our strategy mode for OpIdx. 1461 ReorderingMode RMode = ReorderingModes[OpIdx]; 1462 if (RMode == ReorderingMode::Failed) 1463 return None; 1464 1465 // The linearized opcode of the operand at OpIdx, Lane. 1466 bool OpIdxAPO = getData(OpIdx, Lane).APO; 1467 1468 // The best operand index and its score. 1469 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we 1470 // are using the score to differentiate between the two. 1471 struct BestOpData { 1472 Optional<unsigned> Idx = None; 1473 unsigned Score = 0; 1474 } BestOp; 1475 BestOp.Score = 1476 BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0) 1477 .first->second; 1478 1479 // Track if the operand must be marked as used. If the operand is set to 1480 // Score 1 explicitly (because of non power-of-2 unique scalars, we may 1481 // want to reestimate the operands again on the following iterations). 1482 bool IsUsed = 1483 RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant; 1484 // Iterate through all unused operands and look for the best. 1485 for (unsigned Idx = 0; Idx != NumOperands; ++Idx) { 1486 // Get the operand at Idx and Lane. 1487 OperandData &OpData = getData(Idx, Lane); 1488 Value *Op = OpData.V; 1489 bool OpAPO = OpData.APO; 1490 1491 // Skip already selected operands. 1492 if (OpData.IsUsed) 1493 continue; 1494 1495 // Skip if we are trying to move the operand to a position with a 1496 // different opcode in the linearized tree form. This would break the 1497 // semantics. 1498 if (OpAPO != OpIdxAPO) 1499 continue; 1500 1501 // Look for an operand that matches the current mode. 1502 switch (RMode) { 1503 case ReorderingMode::Load: 1504 case ReorderingMode::Constant: 1505 case ReorderingMode::Opcode: { 1506 bool LeftToRight = Lane > LastLane; 1507 Value *OpLeft = (LeftToRight) ? OpLastLane : Op; 1508 Value *OpRight = (LeftToRight) ? Op : OpLastLane; 1509 int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane, 1510 OpIdx, Idx, IsUsed); 1511 if (Score > static_cast<int>(BestOp.Score)) { 1512 BestOp.Idx = Idx; 1513 BestOp.Score = Score; 1514 BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score; 1515 } 1516 break; 1517 } 1518 case ReorderingMode::Splat: 1519 if (Op == OpLastLane) 1520 BestOp.Idx = Idx; 1521 break; 1522 case ReorderingMode::Failed: 1523 llvm_unreachable("Not expected Failed reordering mode."); 1524 } 1525 } 1526 1527 if (BestOp.Idx) { 1528 getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed; 1529 return BestOp.Idx; 1530 } 1531 // If we could not find a good match return None. 1532 return None; 1533 } 1534 1535 /// Helper for reorderOperandVecs. 1536 /// \returns the lane that we should start reordering from. This is the one 1537 /// which has the least number of operands that can freely move about or 1538 /// less profitable because it already has the most optimal set of operands. 1539 unsigned getBestLaneToStartReordering() const { 1540 unsigned Min = UINT_MAX; 1541 unsigned SameOpNumber = 0; 1542 // std::pair<unsigned, unsigned> is used to implement a simple voting 1543 // algorithm and choose the lane with the least number of operands that 1544 // can freely move about or less profitable because it already has the 1545 // most optimal set of operands. The first unsigned is a counter for 1546 // voting, the second unsigned is the counter of lanes with instructions 1547 // with same/alternate opcodes and same parent basic block. 1548 MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap; 1549 // Try to be closer to the original results, if we have multiple lanes 1550 // with same cost. If 2 lanes have the same cost, use the one with the 1551 // lowest index. 1552 for (int I = getNumLanes(); I > 0; --I) { 1553 unsigned Lane = I - 1; 1554 OperandsOrderData NumFreeOpsHash = 1555 getMaxNumOperandsThatCanBeReordered(Lane); 1556 // Compare the number of operands that can move and choose the one with 1557 // the least number. 1558 if (NumFreeOpsHash.NumOfAPOs < Min) { 1559 Min = NumFreeOpsHash.NumOfAPOs; 1560 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; 1561 HashMap.clear(); 1562 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1563 } else if (NumFreeOpsHash.NumOfAPOs == Min && 1564 NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) { 1565 // Select the most optimal lane in terms of number of operands that 1566 // should be moved around. 1567 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent; 1568 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1569 } else if (NumFreeOpsHash.NumOfAPOs == Min && 1570 NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) { 1571 auto It = HashMap.find(NumFreeOpsHash.Hash); 1572 if (It == HashMap.end()) 1573 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane); 1574 else 1575 ++It->second.first; 1576 } 1577 } 1578 // Select the lane with the minimum counter. 1579 unsigned BestLane = 0; 1580 unsigned CntMin = UINT_MAX; 1581 for (const auto &Data : reverse(HashMap)) { 1582 if (Data.second.first < CntMin) { 1583 CntMin = Data.second.first; 1584 BestLane = Data.second.second; 1585 } 1586 } 1587 return BestLane; 1588 } 1589 1590 /// Data structure that helps to reorder operands. 1591 struct OperandsOrderData { 1592 /// The best number of operands with the same APOs, which can be 1593 /// reordered. 1594 unsigned NumOfAPOs = UINT_MAX; 1595 /// Number of operands with the same/alternate instruction opcode and 1596 /// parent. 1597 unsigned NumOpsWithSameOpcodeParent = 0; 1598 /// Hash for the actual operands ordering. 1599 /// Used to count operands, actually their position id and opcode 1600 /// value. It is used in the voting mechanism to find the lane with the 1601 /// least number of operands that can freely move about or less profitable 1602 /// because it already has the most optimal set of operands. Can be 1603 /// replaced with SmallVector<unsigned> instead but hash code is faster 1604 /// and requires less memory. 1605 unsigned Hash = 0; 1606 }; 1607 /// \returns the maximum number of operands that are allowed to be reordered 1608 /// for \p Lane and the number of compatible instructions(with the same 1609 /// parent/opcode). This is used as a heuristic for selecting the first lane 1610 /// to start operand reordering. 1611 OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const { 1612 unsigned CntTrue = 0; 1613 unsigned NumOperands = getNumOperands(); 1614 // Operands with the same APO can be reordered. We therefore need to count 1615 // how many of them we have for each APO, like this: Cnt[APO] = x. 1616 // Since we only have two APOs, namely true and false, we can avoid using 1617 // a map. Instead we can simply count the number of operands that 1618 // correspond to one of them (in this case the 'true' APO), and calculate 1619 // the other by subtracting it from the total number of operands. 1620 // Operands with the same instruction opcode and parent are more 1621 // profitable since we don't need to move them in many cases, with a high 1622 // probability such lane already can be vectorized effectively. 1623 bool AllUndefs = true; 1624 unsigned NumOpsWithSameOpcodeParent = 0; 1625 Instruction *OpcodeI = nullptr; 1626 BasicBlock *Parent = nullptr; 1627 unsigned Hash = 0; 1628 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1629 const OperandData &OpData = getData(OpIdx, Lane); 1630 if (OpData.APO) 1631 ++CntTrue; 1632 // Use Boyer-Moore majority voting for finding the majority opcode and 1633 // the number of times it occurs. 1634 if (auto *I = dyn_cast<Instruction>(OpData.V)) { 1635 if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() || 1636 I->getParent() != Parent) { 1637 if (NumOpsWithSameOpcodeParent == 0) { 1638 NumOpsWithSameOpcodeParent = 1; 1639 OpcodeI = I; 1640 Parent = I->getParent(); 1641 } else { 1642 --NumOpsWithSameOpcodeParent; 1643 } 1644 } else { 1645 ++NumOpsWithSameOpcodeParent; 1646 } 1647 } 1648 Hash = hash_combine( 1649 Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1))); 1650 AllUndefs = AllUndefs && isa<UndefValue>(OpData.V); 1651 } 1652 if (AllUndefs) 1653 return {}; 1654 OperandsOrderData Data; 1655 Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue); 1656 Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent; 1657 Data.Hash = Hash; 1658 return Data; 1659 } 1660 1661 /// Go through the instructions in VL and append their operands. 1662 void appendOperandsOfVL(ArrayRef<Value *> VL) { 1663 assert(!VL.empty() && "Bad VL"); 1664 assert((empty() || VL.size() == getNumLanes()) && 1665 "Expected same number of lanes"); 1666 assert(isa<Instruction>(VL[0]) && "Expected instruction"); 1667 unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands(); 1668 OpsVec.resize(NumOperands); 1669 unsigned NumLanes = VL.size(); 1670 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1671 OpsVec[OpIdx].resize(NumLanes); 1672 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 1673 assert(isa<Instruction>(VL[Lane]) && "Expected instruction"); 1674 // Our tree has just 3 nodes: the root and two operands. 1675 // It is therefore trivial to get the APO. We only need to check the 1676 // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or 1677 // RHS operand. The LHS operand of both add and sub is never attached 1678 // to an inversese operation in the linearized form, therefore its APO 1679 // is false. The RHS is true only if VL[Lane] is an inverse operation. 1680 1681 // Since operand reordering is performed on groups of commutative 1682 // operations or alternating sequences (e.g., +, -), we can safely 1683 // tell the inverse operations by checking commutativity. 1684 bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane])); 1685 bool APO = (OpIdx == 0) ? false : IsInverseOperation; 1686 OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx), 1687 APO, false}; 1688 } 1689 } 1690 } 1691 1692 /// \returns the number of operands. 1693 unsigned getNumOperands() const { return OpsVec.size(); } 1694 1695 /// \returns the number of lanes. 1696 unsigned getNumLanes() const { return OpsVec[0].size(); } 1697 1698 /// \returns the operand value at \p OpIdx and \p Lane. 1699 Value *getValue(unsigned OpIdx, unsigned Lane) const { 1700 return getData(OpIdx, Lane).V; 1701 } 1702 1703 /// \returns true if the data structure is empty. 1704 bool empty() const { return OpsVec.empty(); } 1705 1706 /// Clears the data. 1707 void clear() { OpsVec.clear(); } 1708 1709 /// \Returns true if there are enough operands identical to \p Op to fill 1710 /// the whole vector. 1711 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow. 1712 bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) { 1713 bool OpAPO = getData(OpIdx, Lane).APO; 1714 for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) { 1715 if (Ln == Lane) 1716 continue; 1717 // This is set to true if we found a candidate for broadcast at Lane. 1718 bool FoundCandidate = false; 1719 for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) { 1720 OperandData &Data = getData(OpI, Ln); 1721 if (Data.APO != OpAPO || Data.IsUsed) 1722 continue; 1723 if (Data.V == Op) { 1724 FoundCandidate = true; 1725 Data.IsUsed = true; 1726 break; 1727 } 1728 } 1729 if (!FoundCandidate) 1730 return false; 1731 } 1732 return true; 1733 } 1734 1735 public: 1736 /// Initialize with all the operands of the instruction vector \p RootVL. 1737 VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL, 1738 ScalarEvolution &SE, const BoUpSLP &R) 1739 : DL(DL), SE(SE), R(R) { 1740 // Append all the operands of RootVL. 1741 appendOperandsOfVL(RootVL); 1742 } 1743 1744 /// \Returns a value vector with the operands across all lanes for the 1745 /// opearnd at \p OpIdx. 1746 ValueList getVL(unsigned OpIdx) const { 1747 ValueList OpVL(OpsVec[OpIdx].size()); 1748 assert(OpsVec[OpIdx].size() == getNumLanes() && 1749 "Expected same num of lanes across all operands"); 1750 for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane) 1751 OpVL[Lane] = OpsVec[OpIdx][Lane].V; 1752 return OpVL; 1753 } 1754 1755 // Performs operand reordering for 2 or more operands. 1756 // The original operands are in OrigOps[OpIdx][Lane]. 1757 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'. 1758 void reorder() { 1759 unsigned NumOperands = getNumOperands(); 1760 unsigned NumLanes = getNumLanes(); 1761 // Each operand has its own mode. We are using this mode to help us select 1762 // the instructions for each lane, so that they match best with the ones 1763 // we have selected so far. 1764 SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands); 1765 1766 // This is a greedy single-pass algorithm. We are going over each lane 1767 // once and deciding on the best order right away with no back-tracking. 1768 // However, in order to increase its effectiveness, we start with the lane 1769 // that has operands that can move the least. For example, given the 1770 // following lanes: 1771 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd 1772 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st 1773 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd 1774 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th 1775 // we will start at Lane 1, since the operands of the subtraction cannot 1776 // be reordered. Then we will visit the rest of the lanes in a circular 1777 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3. 1778 1779 // Find the first lane that we will start our search from. 1780 unsigned FirstLane = getBestLaneToStartReordering(); 1781 1782 // Initialize the modes. 1783 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1784 Value *OpLane0 = getValue(OpIdx, FirstLane); 1785 // Keep track if we have instructions with all the same opcode on one 1786 // side. 1787 if (isa<LoadInst>(OpLane0)) 1788 ReorderingModes[OpIdx] = ReorderingMode::Load; 1789 else if (isa<Instruction>(OpLane0)) { 1790 // Check if OpLane0 should be broadcast. 1791 if (shouldBroadcast(OpLane0, OpIdx, FirstLane)) 1792 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1793 else 1794 ReorderingModes[OpIdx] = ReorderingMode::Opcode; 1795 } 1796 else if (isa<Constant>(OpLane0)) 1797 ReorderingModes[OpIdx] = ReorderingMode::Constant; 1798 else if (isa<Argument>(OpLane0)) 1799 // Our best hope is a Splat. It may save some cost in some cases. 1800 ReorderingModes[OpIdx] = ReorderingMode::Splat; 1801 else 1802 // NOTE: This should be unreachable. 1803 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1804 } 1805 1806 // Check that we don't have same operands. No need to reorder if operands 1807 // are just perfect diamond or shuffled diamond match. Do not do it only 1808 // for possible broadcasts or non-power of 2 number of scalars (just for 1809 // now). 1810 auto &&SkipReordering = [this]() { 1811 SmallPtrSet<Value *, 4> UniqueValues; 1812 ArrayRef<OperandData> Op0 = OpsVec.front(); 1813 for (const OperandData &Data : Op0) 1814 UniqueValues.insert(Data.V); 1815 for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) { 1816 if (any_of(Op, [&UniqueValues](const OperandData &Data) { 1817 return !UniqueValues.contains(Data.V); 1818 })) 1819 return false; 1820 } 1821 // TODO: Check if we can remove a check for non-power-2 number of 1822 // scalars after full support of non-power-2 vectorization. 1823 return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size()); 1824 }; 1825 1826 // If the initial strategy fails for any of the operand indexes, then we 1827 // perform reordering again in a second pass. This helps avoid assigning 1828 // high priority to the failed strategy, and should improve reordering for 1829 // the non-failed operand indexes. 1830 for (int Pass = 0; Pass != 2; ++Pass) { 1831 // Check if no need to reorder operands since they're are perfect or 1832 // shuffled diamond match. 1833 // Need to to do it to avoid extra external use cost counting for 1834 // shuffled matches, which may cause regressions. 1835 if (SkipReordering()) 1836 break; 1837 // Skip the second pass if the first pass did not fail. 1838 bool StrategyFailed = false; 1839 // Mark all operand data as free to use. 1840 clearUsed(); 1841 // We keep the original operand order for the FirstLane, so reorder the 1842 // rest of the lanes. We are visiting the nodes in a circular fashion, 1843 // using FirstLane as the center point and increasing the radius 1844 // distance. 1845 SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands); 1846 for (unsigned I = 0; I < NumOperands; ++I) 1847 MainAltOps[I].push_back(getData(I, FirstLane).V); 1848 1849 for (unsigned Distance = 1; Distance != NumLanes; ++Distance) { 1850 // Visit the lane on the right and then the lane on the left. 1851 for (int Direction : {+1, -1}) { 1852 int Lane = FirstLane + Direction * Distance; 1853 if (Lane < 0 || Lane >= (int)NumLanes) 1854 continue; 1855 int LastLane = Lane - Direction; 1856 assert(LastLane >= 0 && LastLane < (int)NumLanes && 1857 "Out of bounds"); 1858 // Look for a good match for each operand. 1859 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) { 1860 // Search for the operand that matches SortedOps[OpIdx][Lane-1]. 1861 Optional<unsigned> BestIdx = getBestOperand( 1862 OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]); 1863 // By not selecting a value, we allow the operands that follow to 1864 // select a better matching value. We will get a non-null value in 1865 // the next run of getBestOperand(). 1866 if (BestIdx) { 1867 // Swap the current operand with the one returned by 1868 // getBestOperand(). 1869 swap(OpIdx, BestIdx.getValue(), Lane); 1870 } else { 1871 // We failed to find a best operand, set mode to 'Failed'. 1872 ReorderingModes[OpIdx] = ReorderingMode::Failed; 1873 // Enable the second pass. 1874 StrategyFailed = true; 1875 } 1876 // Try to get the alternate opcode and follow it during analysis. 1877 if (MainAltOps[OpIdx].size() != 2) { 1878 OperandData &AltOp = getData(OpIdx, Lane); 1879 InstructionsState OpS = 1880 getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V}); 1881 if (OpS.getOpcode() && OpS.isAltShuffle()) 1882 MainAltOps[OpIdx].push_back(AltOp.V); 1883 } 1884 } 1885 } 1886 } 1887 // Skip second pass if the strategy did not fail. 1888 if (!StrategyFailed) 1889 break; 1890 } 1891 } 1892 1893 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1894 LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) { 1895 switch (RMode) { 1896 case ReorderingMode::Load: 1897 return "Load"; 1898 case ReorderingMode::Opcode: 1899 return "Opcode"; 1900 case ReorderingMode::Constant: 1901 return "Constant"; 1902 case ReorderingMode::Splat: 1903 return "Splat"; 1904 case ReorderingMode::Failed: 1905 return "Failed"; 1906 } 1907 llvm_unreachable("Unimplemented Reordering Type"); 1908 } 1909 1910 LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode, 1911 raw_ostream &OS) { 1912 return OS << getModeStr(RMode); 1913 } 1914 1915 /// Debug print. 1916 LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) { 1917 printMode(RMode, dbgs()); 1918 } 1919 1920 friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) { 1921 return printMode(RMode, OS); 1922 } 1923 1924 LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const { 1925 const unsigned Indent = 2; 1926 unsigned Cnt = 0; 1927 for (const OperandDataVec &OpDataVec : OpsVec) { 1928 OS << "Operand " << Cnt++ << "\n"; 1929 for (const OperandData &OpData : OpDataVec) { 1930 OS.indent(Indent) << "{"; 1931 if (Value *V = OpData.V) 1932 OS << *V; 1933 else 1934 OS << "null"; 1935 OS << ", APO:" << OpData.APO << "}\n"; 1936 } 1937 OS << "\n"; 1938 } 1939 return OS; 1940 } 1941 1942 /// Debug print. 1943 LLVM_DUMP_METHOD void dump() const { print(dbgs()); } 1944 #endif 1945 }; 1946 1947 /// Checks if the instruction is marked for deletion. 1948 bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); } 1949 1950 /// Marks values operands for later deletion by replacing them with Undefs. 1951 void eraseInstructions(ArrayRef<Value *> AV); 1952 1953 ~BoUpSLP(); 1954 1955 private: 1956 /// Check if the operands on the edges \p Edges of the \p UserTE allows 1957 /// reordering (i.e. the operands can be reordered because they have only one 1958 /// user and reordarable). 1959 /// \param NonVectorized List of all gather nodes that require reordering 1960 /// (e.g., gather of extractlements or partially vectorizable loads). 1961 /// \param GatherOps List of gather operand nodes for \p UserTE that require 1962 /// reordering, subset of \p NonVectorized. 1963 bool 1964 canReorderOperands(TreeEntry *UserTE, 1965 SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges, 1966 ArrayRef<TreeEntry *> ReorderableGathers, 1967 SmallVectorImpl<TreeEntry *> &GatherOps); 1968 1969 /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph, 1970 /// if any. If it is not vectorized (gather node), returns nullptr. 1971 TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) { 1972 ArrayRef<Value *> VL = UserTE->getOperand(OpIdx); 1973 TreeEntry *TE = nullptr; 1974 const auto *It = find_if(VL, [this, &TE](Value *V) { 1975 TE = getTreeEntry(V); 1976 return TE; 1977 }); 1978 if (It != VL.end() && TE->isSame(VL)) 1979 return TE; 1980 return nullptr; 1981 } 1982 1983 /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph, 1984 /// if any. If it is not vectorized (gather node), returns nullptr. 1985 const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE, 1986 unsigned OpIdx) const { 1987 return const_cast<BoUpSLP *>(this)->getVectorizedOperand( 1988 const_cast<TreeEntry *>(UserTE), OpIdx); 1989 } 1990 1991 /// Checks if all users of \p I are the part of the vectorization tree. 1992 bool areAllUsersVectorized(Instruction *I, 1993 ArrayRef<Value *> VectorizedVals) const; 1994 1995 /// \returns the cost of the vectorizable entry. 1996 InstructionCost getEntryCost(const TreeEntry *E, 1997 ArrayRef<Value *> VectorizedVals); 1998 1999 /// This is the recursive part of buildTree. 2000 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth, 2001 const EdgeInfo &EI); 2002 2003 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can 2004 /// be vectorized to use the original vector (or aggregate "bitcast" to a 2005 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise 2006 /// returns false, setting \p CurrentOrder to either an empty vector or a 2007 /// non-identity permutation that allows to reuse extract instructions. 2008 bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 2009 SmallVectorImpl<unsigned> &CurrentOrder) const; 2010 2011 /// Vectorize a single entry in the tree. 2012 Value *vectorizeTree(TreeEntry *E); 2013 2014 /// Vectorize a single entry in the tree, starting in \p VL. 2015 Value *vectorizeTree(ArrayRef<Value *> VL); 2016 2017 /// Create a new vector from a list of scalar values. Produces a sequence 2018 /// which exploits values reused across lanes, and arranges the inserts 2019 /// for ease of later optimization. 2020 Value *createBuildVector(ArrayRef<Value *> VL); 2021 2022 /// \returns the scalarization cost for this type. Scalarization in this 2023 /// context means the creation of vectors from a group of scalars. If \p 2024 /// NeedToShuffle is true, need to add a cost of reshuffling some of the 2025 /// vector elements. 2026 InstructionCost getGatherCost(FixedVectorType *Ty, 2027 const APInt &ShuffledIndices, 2028 bool NeedToShuffle) const; 2029 2030 /// Checks if the gathered \p VL can be represented as shuffle(s) of previous 2031 /// tree entries. 2032 /// \returns ShuffleKind, if gathered values can be represented as shuffles of 2033 /// previous tree entries. \p Mask is filled with the shuffle mask. 2034 Optional<TargetTransformInfo::ShuffleKind> 2035 isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 2036 SmallVectorImpl<const TreeEntry *> &Entries); 2037 2038 /// \returns the scalarization cost for this list of values. Assuming that 2039 /// this subtree gets vectorized, we may need to extract the values from the 2040 /// roots. This method calculates the cost of extracting the values. 2041 InstructionCost getGatherCost(ArrayRef<Value *> VL) const; 2042 2043 /// Set the Builder insert point to one after the last instruction in 2044 /// the bundle 2045 void setInsertPointAfterBundle(const TreeEntry *E); 2046 2047 /// \returns a vector from a collection of scalars in \p VL. 2048 Value *gather(ArrayRef<Value *> VL); 2049 2050 /// \returns whether the VectorizableTree is fully vectorizable and will 2051 /// be beneficial even the tree height is tiny. 2052 bool isFullyVectorizableTinyTree(bool ForReduction) const; 2053 2054 /// Reorder commutative or alt operands to get better probability of 2055 /// generating vectorized code. 2056 static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 2057 SmallVectorImpl<Value *> &Left, 2058 SmallVectorImpl<Value *> &Right, 2059 const DataLayout &DL, 2060 ScalarEvolution &SE, 2061 const BoUpSLP &R); 2062 struct TreeEntry { 2063 using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>; 2064 TreeEntry(VecTreeTy &Container) : Container(Container) {} 2065 2066 /// \returns true if the scalars in VL are equal to this entry. 2067 bool isSame(ArrayRef<Value *> VL) const { 2068 auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) { 2069 if (Mask.size() != VL.size() && VL.size() == Scalars.size()) 2070 return std::equal(VL.begin(), VL.end(), Scalars.begin()); 2071 return VL.size() == Mask.size() && 2072 std::equal(VL.begin(), VL.end(), Mask.begin(), 2073 [Scalars](Value *V, int Idx) { 2074 return (isa<UndefValue>(V) && 2075 Idx == UndefMaskElem) || 2076 (Idx != UndefMaskElem && V == Scalars[Idx]); 2077 }); 2078 }; 2079 if (!ReorderIndices.empty()) { 2080 // TODO: implement matching if the nodes are just reordered, still can 2081 // treat the vector as the same if the list of scalars matches VL 2082 // directly, without reordering. 2083 SmallVector<int> Mask; 2084 inversePermutation(ReorderIndices, Mask); 2085 if (VL.size() == Scalars.size()) 2086 return IsSame(Scalars, Mask); 2087 if (VL.size() == ReuseShuffleIndices.size()) { 2088 ::addMask(Mask, ReuseShuffleIndices); 2089 return IsSame(Scalars, Mask); 2090 } 2091 return false; 2092 } 2093 return IsSame(Scalars, ReuseShuffleIndices); 2094 } 2095 2096 /// \returns true if current entry has same operands as \p TE. 2097 bool hasEqualOperands(const TreeEntry &TE) const { 2098 if (TE.getNumOperands() != getNumOperands()) 2099 return false; 2100 SmallBitVector Used(getNumOperands()); 2101 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) { 2102 unsigned PrevCount = Used.count(); 2103 for (unsigned K = 0; K < E; ++K) { 2104 if (Used.test(K)) 2105 continue; 2106 if (getOperand(K) == TE.getOperand(I)) { 2107 Used.set(K); 2108 break; 2109 } 2110 } 2111 // Check if we actually found the matching operand. 2112 if (PrevCount == Used.count()) 2113 return false; 2114 } 2115 return true; 2116 } 2117 2118 /// \return Final vectorization factor for the node. Defined by the total 2119 /// number of vectorized scalars, including those, used several times in the 2120 /// entry and counted in the \a ReuseShuffleIndices, if any. 2121 unsigned getVectorFactor() const { 2122 if (!ReuseShuffleIndices.empty()) 2123 return ReuseShuffleIndices.size(); 2124 return Scalars.size(); 2125 }; 2126 2127 /// A vector of scalars. 2128 ValueList Scalars; 2129 2130 /// The Scalars are vectorized into this value. It is initialized to Null. 2131 Value *VectorizedValue = nullptr; 2132 2133 /// Do we need to gather this sequence or vectorize it 2134 /// (either with vector instruction or with scatter/gather 2135 /// intrinsics for store/load)? 2136 enum EntryState { Vectorize, ScatterVectorize, NeedToGather }; 2137 EntryState State; 2138 2139 /// Does this sequence require some shuffling? 2140 SmallVector<int, 4> ReuseShuffleIndices; 2141 2142 /// Does this entry require reordering? 2143 SmallVector<unsigned, 4> ReorderIndices; 2144 2145 /// Points back to the VectorizableTree. 2146 /// 2147 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has 2148 /// to be a pointer and needs to be able to initialize the child iterator. 2149 /// Thus we need a reference back to the container to translate the indices 2150 /// to entries. 2151 VecTreeTy &Container; 2152 2153 /// The TreeEntry index containing the user of this entry. We can actually 2154 /// have multiple users so the data structure is not truly a tree. 2155 SmallVector<EdgeInfo, 1> UserTreeIndices; 2156 2157 /// The index of this treeEntry in VectorizableTree. 2158 int Idx = -1; 2159 2160 private: 2161 /// The operands of each instruction in each lane Operands[op_index][lane]. 2162 /// Note: This helps avoid the replication of the code that performs the 2163 /// reordering of operands during buildTree_rec() and vectorizeTree(). 2164 SmallVector<ValueList, 2> Operands; 2165 2166 /// The main/alternate instruction. 2167 Instruction *MainOp = nullptr; 2168 Instruction *AltOp = nullptr; 2169 2170 public: 2171 /// Set this bundle's \p OpIdx'th operand to \p OpVL. 2172 void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) { 2173 if (Operands.size() < OpIdx + 1) 2174 Operands.resize(OpIdx + 1); 2175 assert(Operands[OpIdx].empty() && "Already resized?"); 2176 assert(OpVL.size() <= Scalars.size() && 2177 "Number of operands is greater than the number of scalars."); 2178 Operands[OpIdx].resize(OpVL.size()); 2179 copy(OpVL, Operands[OpIdx].begin()); 2180 } 2181 2182 /// Set the operands of this bundle in their original order. 2183 void setOperandsInOrder() { 2184 assert(Operands.empty() && "Already initialized?"); 2185 auto *I0 = cast<Instruction>(Scalars[0]); 2186 Operands.resize(I0->getNumOperands()); 2187 unsigned NumLanes = Scalars.size(); 2188 for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands(); 2189 OpIdx != NumOperands; ++OpIdx) { 2190 Operands[OpIdx].resize(NumLanes); 2191 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) { 2192 auto *I = cast<Instruction>(Scalars[Lane]); 2193 assert(I->getNumOperands() == NumOperands && 2194 "Expected same number of operands"); 2195 Operands[OpIdx][Lane] = I->getOperand(OpIdx); 2196 } 2197 } 2198 } 2199 2200 /// Reorders operands of the node to the given mask \p Mask. 2201 void reorderOperands(ArrayRef<int> Mask) { 2202 for (ValueList &Operand : Operands) 2203 reorderScalars(Operand, Mask); 2204 } 2205 2206 /// \returns the \p OpIdx operand of this TreeEntry. 2207 ValueList &getOperand(unsigned OpIdx) { 2208 assert(OpIdx < Operands.size() && "Off bounds"); 2209 return Operands[OpIdx]; 2210 } 2211 2212 /// \returns the \p OpIdx operand of this TreeEntry. 2213 ArrayRef<Value *> getOperand(unsigned OpIdx) const { 2214 assert(OpIdx < Operands.size() && "Off bounds"); 2215 return Operands[OpIdx]; 2216 } 2217 2218 /// \returns the number of operands. 2219 unsigned getNumOperands() const { return Operands.size(); } 2220 2221 /// \return the single \p OpIdx operand. 2222 Value *getSingleOperand(unsigned OpIdx) const { 2223 assert(OpIdx < Operands.size() && "Off bounds"); 2224 assert(!Operands[OpIdx].empty() && "No operand available"); 2225 return Operands[OpIdx][0]; 2226 } 2227 2228 /// Some of the instructions in the list have alternate opcodes. 2229 bool isAltShuffle() const { return MainOp != AltOp; } 2230 2231 bool isOpcodeOrAlt(Instruction *I) const { 2232 unsigned CheckedOpcode = I->getOpcode(); 2233 return (getOpcode() == CheckedOpcode || 2234 getAltOpcode() == CheckedOpcode); 2235 } 2236 2237 /// Chooses the correct key for scheduling data. If \p Op has the same (or 2238 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is 2239 /// \p OpValue. 2240 Value *isOneOf(Value *Op) const { 2241 auto *I = dyn_cast<Instruction>(Op); 2242 if (I && isOpcodeOrAlt(I)) 2243 return Op; 2244 return MainOp; 2245 } 2246 2247 void setOperations(const InstructionsState &S) { 2248 MainOp = S.MainOp; 2249 AltOp = S.AltOp; 2250 } 2251 2252 Instruction *getMainOp() const { 2253 return MainOp; 2254 } 2255 2256 Instruction *getAltOp() const { 2257 return AltOp; 2258 } 2259 2260 /// The main/alternate opcodes for the list of instructions. 2261 unsigned getOpcode() const { 2262 return MainOp ? MainOp->getOpcode() : 0; 2263 } 2264 2265 unsigned getAltOpcode() const { 2266 return AltOp ? AltOp->getOpcode() : 0; 2267 } 2268 2269 /// When ReuseReorderShuffleIndices is empty it just returns position of \p 2270 /// V within vector of Scalars. Otherwise, try to remap on its reuse index. 2271 int findLaneForValue(Value *V) const { 2272 unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V)); 2273 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 2274 if (!ReorderIndices.empty()) 2275 FoundLane = ReorderIndices[FoundLane]; 2276 assert(FoundLane < Scalars.size() && "Couldn't find extract lane"); 2277 if (!ReuseShuffleIndices.empty()) { 2278 FoundLane = std::distance(ReuseShuffleIndices.begin(), 2279 find(ReuseShuffleIndices, FoundLane)); 2280 } 2281 return FoundLane; 2282 } 2283 2284 #ifndef NDEBUG 2285 /// Debug printer. 2286 LLVM_DUMP_METHOD void dump() const { 2287 dbgs() << Idx << ".\n"; 2288 for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) { 2289 dbgs() << "Operand " << OpI << ":\n"; 2290 for (const Value *V : Operands[OpI]) 2291 dbgs().indent(2) << *V << "\n"; 2292 } 2293 dbgs() << "Scalars: \n"; 2294 for (Value *V : Scalars) 2295 dbgs().indent(2) << *V << "\n"; 2296 dbgs() << "State: "; 2297 switch (State) { 2298 case Vectorize: 2299 dbgs() << "Vectorize\n"; 2300 break; 2301 case ScatterVectorize: 2302 dbgs() << "ScatterVectorize\n"; 2303 break; 2304 case NeedToGather: 2305 dbgs() << "NeedToGather\n"; 2306 break; 2307 } 2308 dbgs() << "MainOp: "; 2309 if (MainOp) 2310 dbgs() << *MainOp << "\n"; 2311 else 2312 dbgs() << "NULL\n"; 2313 dbgs() << "AltOp: "; 2314 if (AltOp) 2315 dbgs() << *AltOp << "\n"; 2316 else 2317 dbgs() << "NULL\n"; 2318 dbgs() << "VectorizedValue: "; 2319 if (VectorizedValue) 2320 dbgs() << *VectorizedValue << "\n"; 2321 else 2322 dbgs() << "NULL\n"; 2323 dbgs() << "ReuseShuffleIndices: "; 2324 if (ReuseShuffleIndices.empty()) 2325 dbgs() << "Empty"; 2326 else 2327 for (int ReuseIdx : ReuseShuffleIndices) 2328 dbgs() << ReuseIdx << ", "; 2329 dbgs() << "\n"; 2330 dbgs() << "ReorderIndices: "; 2331 for (unsigned ReorderIdx : ReorderIndices) 2332 dbgs() << ReorderIdx << ", "; 2333 dbgs() << "\n"; 2334 dbgs() << "UserTreeIndices: "; 2335 for (const auto &EInfo : UserTreeIndices) 2336 dbgs() << EInfo << ", "; 2337 dbgs() << "\n"; 2338 } 2339 #endif 2340 }; 2341 2342 #ifndef NDEBUG 2343 void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost, 2344 InstructionCost VecCost, 2345 InstructionCost ScalarCost) const { 2346 dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump(); 2347 dbgs() << "SLP: Costs:\n"; 2348 dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n"; 2349 dbgs() << "SLP: VectorCost = " << VecCost << "\n"; 2350 dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n"; 2351 dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = " << 2352 ReuseShuffleCost + VecCost - ScalarCost << "\n"; 2353 } 2354 #endif 2355 2356 /// Create a new VectorizableTree entry. 2357 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle, 2358 const InstructionsState &S, 2359 const EdgeInfo &UserTreeIdx, 2360 ArrayRef<int> ReuseShuffleIndices = None, 2361 ArrayRef<unsigned> ReorderIndices = None) { 2362 TreeEntry::EntryState EntryState = 2363 Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather; 2364 return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx, 2365 ReuseShuffleIndices, ReorderIndices); 2366 } 2367 2368 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, 2369 TreeEntry::EntryState EntryState, 2370 Optional<ScheduleData *> Bundle, 2371 const InstructionsState &S, 2372 const EdgeInfo &UserTreeIdx, 2373 ArrayRef<int> ReuseShuffleIndices = None, 2374 ArrayRef<unsigned> ReorderIndices = None) { 2375 assert(((!Bundle && EntryState == TreeEntry::NeedToGather) || 2376 (Bundle && EntryState != TreeEntry::NeedToGather)) && 2377 "Need to vectorize gather entry?"); 2378 VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree)); 2379 TreeEntry *Last = VectorizableTree.back().get(); 2380 Last->Idx = VectorizableTree.size() - 1; 2381 Last->State = EntryState; 2382 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(), 2383 ReuseShuffleIndices.end()); 2384 if (ReorderIndices.empty()) { 2385 Last->Scalars.assign(VL.begin(), VL.end()); 2386 Last->setOperations(S); 2387 } else { 2388 // Reorder scalars and build final mask. 2389 Last->Scalars.assign(VL.size(), nullptr); 2390 transform(ReorderIndices, Last->Scalars.begin(), 2391 [VL](unsigned Idx) -> Value * { 2392 if (Idx >= VL.size()) 2393 return UndefValue::get(VL.front()->getType()); 2394 return VL[Idx]; 2395 }); 2396 InstructionsState S = getSameOpcode(Last->Scalars); 2397 Last->setOperations(S); 2398 Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end()); 2399 } 2400 if (Last->State != TreeEntry::NeedToGather) { 2401 for (Value *V : VL) { 2402 assert(!getTreeEntry(V) && "Scalar already in tree!"); 2403 ScalarToTreeEntry[V] = Last; 2404 } 2405 // Update the scheduler bundle to point to this TreeEntry. 2406 ScheduleData *BundleMember = Bundle.getValue(); 2407 assert((BundleMember || isa<PHINode>(S.MainOp) || 2408 isVectorLikeInstWithConstOps(S.MainOp) || 2409 doesNotNeedToSchedule(VL)) && 2410 "Bundle and VL out of sync"); 2411 if (BundleMember) { 2412 for (Value *V : VL) { 2413 if (doesNotNeedToBeScheduled(V)) 2414 continue; 2415 assert(BundleMember && "Unexpected end of bundle."); 2416 BundleMember->TE = Last; 2417 BundleMember = BundleMember->NextInBundle; 2418 } 2419 } 2420 assert(!BundleMember && "Bundle and VL out of sync"); 2421 } else { 2422 MustGather.insert(VL.begin(), VL.end()); 2423 } 2424 2425 if (UserTreeIdx.UserTE) 2426 Last->UserTreeIndices.push_back(UserTreeIdx); 2427 2428 return Last; 2429 } 2430 2431 /// -- Vectorization State -- 2432 /// Holds all of the tree entries. 2433 TreeEntry::VecTreeTy VectorizableTree; 2434 2435 #ifndef NDEBUG 2436 /// Debug printer. 2437 LLVM_DUMP_METHOD void dumpVectorizableTree() const { 2438 for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) { 2439 VectorizableTree[Id]->dump(); 2440 dbgs() << "\n"; 2441 } 2442 } 2443 #endif 2444 2445 TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); } 2446 2447 const TreeEntry *getTreeEntry(Value *V) const { 2448 return ScalarToTreeEntry.lookup(V); 2449 } 2450 2451 /// Maps a specific scalar to its tree entry. 2452 SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry; 2453 2454 /// Maps a value to the proposed vectorizable size. 2455 SmallDenseMap<Value *, unsigned> InstrElementSize; 2456 2457 /// A list of scalars that we found that we need to keep as scalars. 2458 ValueSet MustGather; 2459 2460 /// This POD struct describes one external user in the vectorized tree. 2461 struct ExternalUser { 2462 ExternalUser(Value *S, llvm::User *U, int L) 2463 : Scalar(S), User(U), Lane(L) {} 2464 2465 // Which scalar in our function. 2466 Value *Scalar; 2467 2468 // Which user that uses the scalar. 2469 llvm::User *User; 2470 2471 // Which lane does the scalar belong to. 2472 int Lane; 2473 }; 2474 using UserList = SmallVector<ExternalUser, 16>; 2475 2476 /// Checks if two instructions may access the same memory. 2477 /// 2478 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it 2479 /// is invariant in the calling loop. 2480 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1, 2481 Instruction *Inst2) { 2482 // First check if the result is already in the cache. 2483 AliasCacheKey key = std::make_pair(Inst1, Inst2); 2484 Optional<bool> &result = AliasCache[key]; 2485 if (result.hasValue()) { 2486 return result.getValue(); 2487 } 2488 bool aliased = true; 2489 if (Loc1.Ptr && isSimple(Inst1)) 2490 aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1)); 2491 // Store the result in the cache. 2492 result = aliased; 2493 return aliased; 2494 } 2495 2496 using AliasCacheKey = std::pair<Instruction *, Instruction *>; 2497 2498 /// Cache for alias results. 2499 /// TODO: consider moving this to the AliasAnalysis itself. 2500 DenseMap<AliasCacheKey, Optional<bool>> AliasCache; 2501 2502 // Cache for pointerMayBeCaptured calls inside AA. This is preserved 2503 // globally through SLP because we don't perform any action which 2504 // invalidates capture results. 2505 BatchAAResults BatchAA; 2506 2507 /// Removes an instruction from its block and eventually deletes it. 2508 /// It's like Instruction::eraseFromParent() except that the actual deletion 2509 /// is delayed until BoUpSLP is destructed. 2510 /// This is required to ensure that there are no incorrect collisions in the 2511 /// AliasCache, which can happen if a new instruction is allocated at the 2512 /// same address as a previously deleted instruction. 2513 void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) { 2514 auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first; 2515 It->getSecond() = It->getSecond() && ReplaceOpsWithUndef; 2516 } 2517 2518 /// Temporary store for deleted instructions. Instructions will be deleted 2519 /// eventually when the BoUpSLP is destructed. 2520 DenseMap<Instruction *, bool> DeletedInstructions; 2521 2522 /// A list of values that need to extracted out of the tree. 2523 /// This list holds pairs of (Internal Scalar : External User). External User 2524 /// can be nullptr, it means that this Internal Scalar will be used later, 2525 /// after vectorization. 2526 UserList ExternalUses; 2527 2528 /// Values used only by @llvm.assume calls. 2529 SmallPtrSet<const Value *, 32> EphValues; 2530 2531 /// Holds all of the instructions that we gathered. 2532 SetVector<Instruction *> GatherShuffleSeq; 2533 2534 /// A list of blocks that we are going to CSE. 2535 SetVector<BasicBlock *> CSEBlocks; 2536 2537 /// Contains all scheduling relevant data for an instruction. 2538 /// A ScheduleData either represents a single instruction or a member of an 2539 /// instruction bundle (= a group of instructions which is combined into a 2540 /// vector instruction). 2541 struct ScheduleData { 2542 // The initial value for the dependency counters. It means that the 2543 // dependencies are not calculated yet. 2544 enum { InvalidDeps = -1 }; 2545 2546 ScheduleData() = default; 2547 2548 void init(int BlockSchedulingRegionID, Value *OpVal) { 2549 FirstInBundle = this; 2550 NextInBundle = nullptr; 2551 NextLoadStore = nullptr; 2552 IsScheduled = false; 2553 SchedulingRegionID = BlockSchedulingRegionID; 2554 clearDependencies(); 2555 OpValue = OpVal; 2556 TE = nullptr; 2557 } 2558 2559 /// Verify basic self consistency properties 2560 void verify() { 2561 if (hasValidDependencies()) { 2562 assert(UnscheduledDeps <= Dependencies && "invariant"); 2563 } else { 2564 assert(UnscheduledDeps == Dependencies && "invariant"); 2565 } 2566 2567 if (IsScheduled) { 2568 assert(isSchedulingEntity() && 2569 "unexpected scheduled state"); 2570 for (const ScheduleData *BundleMember = this; BundleMember; 2571 BundleMember = BundleMember->NextInBundle) { 2572 assert(BundleMember->hasValidDependencies() && 2573 BundleMember->UnscheduledDeps == 0 && 2574 "unexpected scheduled state"); 2575 assert((BundleMember == this || !BundleMember->IsScheduled) && 2576 "only bundle is marked scheduled"); 2577 } 2578 } 2579 2580 assert(Inst->getParent() == FirstInBundle->Inst->getParent() && 2581 "all bundle members must be in same basic block"); 2582 } 2583 2584 /// Returns true if the dependency information has been calculated. 2585 /// Note that depenendency validity can vary between instructions within 2586 /// a single bundle. 2587 bool hasValidDependencies() const { return Dependencies != InvalidDeps; } 2588 2589 /// Returns true for single instructions and for bundle representatives 2590 /// (= the head of a bundle). 2591 bool isSchedulingEntity() const { return FirstInBundle == this; } 2592 2593 /// Returns true if it represents an instruction bundle and not only a 2594 /// single instruction. 2595 bool isPartOfBundle() const { 2596 return NextInBundle != nullptr || FirstInBundle != this || TE; 2597 } 2598 2599 /// Returns true if it is ready for scheduling, i.e. it has no more 2600 /// unscheduled depending instructions/bundles. 2601 bool isReady() const { 2602 assert(isSchedulingEntity() && 2603 "can't consider non-scheduling entity for ready list"); 2604 return unscheduledDepsInBundle() == 0 && !IsScheduled; 2605 } 2606 2607 /// Modifies the number of unscheduled dependencies for this instruction, 2608 /// and returns the number of remaining dependencies for the containing 2609 /// bundle. 2610 int incrementUnscheduledDeps(int Incr) { 2611 assert(hasValidDependencies() && 2612 "increment of unscheduled deps would be meaningless"); 2613 UnscheduledDeps += Incr; 2614 return FirstInBundle->unscheduledDepsInBundle(); 2615 } 2616 2617 /// Sets the number of unscheduled dependencies to the number of 2618 /// dependencies. 2619 void resetUnscheduledDeps() { 2620 UnscheduledDeps = Dependencies; 2621 } 2622 2623 /// Clears all dependency information. 2624 void clearDependencies() { 2625 Dependencies = InvalidDeps; 2626 resetUnscheduledDeps(); 2627 MemoryDependencies.clear(); 2628 ControlDependencies.clear(); 2629 } 2630 2631 int unscheduledDepsInBundle() const { 2632 assert(isSchedulingEntity() && "only meaningful on the bundle"); 2633 int Sum = 0; 2634 for (const ScheduleData *BundleMember = this; BundleMember; 2635 BundleMember = BundleMember->NextInBundle) { 2636 if (BundleMember->UnscheduledDeps == InvalidDeps) 2637 return InvalidDeps; 2638 Sum += BundleMember->UnscheduledDeps; 2639 } 2640 return Sum; 2641 } 2642 2643 void dump(raw_ostream &os) const { 2644 if (!isSchedulingEntity()) { 2645 os << "/ " << *Inst; 2646 } else if (NextInBundle) { 2647 os << '[' << *Inst; 2648 ScheduleData *SD = NextInBundle; 2649 while (SD) { 2650 os << ';' << *SD->Inst; 2651 SD = SD->NextInBundle; 2652 } 2653 os << ']'; 2654 } else { 2655 os << *Inst; 2656 } 2657 } 2658 2659 Instruction *Inst = nullptr; 2660 2661 /// Opcode of the current instruction in the schedule data. 2662 Value *OpValue = nullptr; 2663 2664 /// The TreeEntry that this instruction corresponds to. 2665 TreeEntry *TE = nullptr; 2666 2667 /// Points to the head in an instruction bundle (and always to this for 2668 /// single instructions). 2669 ScheduleData *FirstInBundle = nullptr; 2670 2671 /// Single linked list of all instructions in a bundle. Null if it is a 2672 /// single instruction. 2673 ScheduleData *NextInBundle = nullptr; 2674 2675 /// Single linked list of all memory instructions (e.g. load, store, call) 2676 /// in the block - until the end of the scheduling region. 2677 ScheduleData *NextLoadStore = nullptr; 2678 2679 /// The dependent memory instructions. 2680 /// This list is derived on demand in calculateDependencies(). 2681 SmallVector<ScheduleData *, 4> MemoryDependencies; 2682 2683 /// List of instructions which this instruction could be control dependent 2684 /// on. Allowing such nodes to be scheduled below this one could introduce 2685 /// a runtime fault which didn't exist in the original program. 2686 /// ex: this is a load or udiv following a readonly call which inf loops 2687 SmallVector<ScheduleData *, 4> ControlDependencies; 2688 2689 /// This ScheduleData is in the current scheduling region if this matches 2690 /// the current SchedulingRegionID of BlockScheduling. 2691 int SchedulingRegionID = 0; 2692 2693 /// Used for getting a "good" final ordering of instructions. 2694 int SchedulingPriority = 0; 2695 2696 /// The number of dependencies. Constitutes of the number of users of the 2697 /// instruction plus the number of dependent memory instructions (if any). 2698 /// This value is calculated on demand. 2699 /// If InvalidDeps, the number of dependencies is not calculated yet. 2700 int Dependencies = InvalidDeps; 2701 2702 /// The number of dependencies minus the number of dependencies of scheduled 2703 /// instructions. As soon as this is zero, the instruction/bundle gets ready 2704 /// for scheduling. 2705 /// Note that this is negative as long as Dependencies is not calculated. 2706 int UnscheduledDeps = InvalidDeps; 2707 2708 /// True if this instruction is scheduled (or considered as scheduled in the 2709 /// dry-run). 2710 bool IsScheduled = false; 2711 }; 2712 2713 #ifndef NDEBUG 2714 friend inline raw_ostream &operator<<(raw_ostream &os, 2715 const BoUpSLP::ScheduleData &SD) { 2716 SD.dump(os); 2717 return os; 2718 } 2719 #endif 2720 2721 friend struct GraphTraits<BoUpSLP *>; 2722 friend struct DOTGraphTraits<BoUpSLP *>; 2723 2724 /// Contains all scheduling data for a basic block. 2725 /// It does not schedules instructions, which are not memory read/write 2726 /// instructions and their operands are either constants, or arguments, or 2727 /// phis, or instructions from others blocks, or their users are phis or from 2728 /// the other blocks. The resulting vector instructions can be placed at the 2729 /// beginning of the basic block without scheduling (if operands does not need 2730 /// to be scheduled) or at the end of the block (if users are outside of the 2731 /// block). It allows to save some compile time and memory used by the 2732 /// compiler. 2733 /// ScheduleData is assigned for each instruction in between the boundaries of 2734 /// the tree entry, even for those, which are not part of the graph. It is 2735 /// required to correctly follow the dependencies between the instructions and 2736 /// their correct scheduling. The ScheduleData is not allocated for the 2737 /// instructions, which do not require scheduling, like phis, nodes with 2738 /// extractelements/insertelements only or nodes with instructions, with 2739 /// uses/operands outside of the block. 2740 struct BlockScheduling { 2741 BlockScheduling(BasicBlock *BB) 2742 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {} 2743 2744 void clear() { 2745 ReadyInsts.clear(); 2746 ScheduleStart = nullptr; 2747 ScheduleEnd = nullptr; 2748 FirstLoadStoreInRegion = nullptr; 2749 LastLoadStoreInRegion = nullptr; 2750 2751 // Reduce the maximum schedule region size by the size of the 2752 // previous scheduling run. 2753 ScheduleRegionSizeLimit -= ScheduleRegionSize; 2754 if (ScheduleRegionSizeLimit < MinScheduleRegionSize) 2755 ScheduleRegionSizeLimit = MinScheduleRegionSize; 2756 ScheduleRegionSize = 0; 2757 2758 // Make a new scheduling region, i.e. all existing ScheduleData is not 2759 // in the new region yet. 2760 ++SchedulingRegionID; 2761 } 2762 2763 ScheduleData *getScheduleData(Instruction *I) { 2764 if (BB != I->getParent()) 2765 // Avoid lookup if can't possibly be in map. 2766 return nullptr; 2767 ScheduleData *SD = ScheduleDataMap.lookup(I); 2768 if (SD && isInSchedulingRegion(SD)) 2769 return SD; 2770 return nullptr; 2771 } 2772 2773 ScheduleData *getScheduleData(Value *V) { 2774 if (auto *I = dyn_cast<Instruction>(V)) 2775 return getScheduleData(I); 2776 return nullptr; 2777 } 2778 2779 ScheduleData *getScheduleData(Value *V, Value *Key) { 2780 if (V == Key) 2781 return getScheduleData(V); 2782 auto I = ExtraScheduleDataMap.find(V); 2783 if (I != ExtraScheduleDataMap.end()) { 2784 ScheduleData *SD = I->second.lookup(Key); 2785 if (SD && isInSchedulingRegion(SD)) 2786 return SD; 2787 } 2788 return nullptr; 2789 } 2790 2791 bool isInSchedulingRegion(ScheduleData *SD) const { 2792 return SD->SchedulingRegionID == SchedulingRegionID; 2793 } 2794 2795 /// Marks an instruction as scheduled and puts all dependent ready 2796 /// instructions into the ready-list. 2797 template <typename ReadyListType> 2798 void schedule(ScheduleData *SD, ReadyListType &ReadyList) { 2799 SD->IsScheduled = true; 2800 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n"); 2801 2802 for (ScheduleData *BundleMember = SD; BundleMember; 2803 BundleMember = BundleMember->NextInBundle) { 2804 if (BundleMember->Inst != BundleMember->OpValue) 2805 continue; 2806 2807 // Handle the def-use chain dependencies. 2808 2809 // Decrement the unscheduled counter and insert to ready list if ready. 2810 auto &&DecrUnsched = [this, &ReadyList](Instruction *I) { 2811 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) { 2812 if (OpDef && OpDef->hasValidDependencies() && 2813 OpDef->incrementUnscheduledDeps(-1) == 0) { 2814 // There are no more unscheduled dependencies after 2815 // decrementing, so we can put the dependent instruction 2816 // into the ready list. 2817 ScheduleData *DepBundle = OpDef->FirstInBundle; 2818 assert(!DepBundle->IsScheduled && 2819 "already scheduled bundle gets ready"); 2820 ReadyList.insert(DepBundle); 2821 LLVM_DEBUG(dbgs() 2822 << "SLP: gets ready (def): " << *DepBundle << "\n"); 2823 } 2824 }); 2825 }; 2826 2827 // If BundleMember is a vector bundle, its operands may have been 2828 // reordered during buildTree(). We therefore need to get its operands 2829 // through the TreeEntry. 2830 if (TreeEntry *TE = BundleMember->TE) { 2831 // Need to search for the lane since the tree entry can be reordered. 2832 int Lane = std::distance(TE->Scalars.begin(), 2833 find(TE->Scalars, BundleMember->Inst)); 2834 assert(Lane >= 0 && "Lane not set"); 2835 2836 // Since vectorization tree is being built recursively this assertion 2837 // ensures that the tree entry has all operands set before reaching 2838 // this code. Couple of exceptions known at the moment are extracts 2839 // where their second (immediate) operand is not added. Since 2840 // immediates do not affect scheduler behavior this is considered 2841 // okay. 2842 auto *In = BundleMember->Inst; 2843 assert(In && 2844 (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) || 2845 In->getNumOperands() == TE->getNumOperands()) && 2846 "Missed TreeEntry operands?"); 2847 (void)In; // fake use to avoid build failure when assertions disabled 2848 2849 for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands(); 2850 OpIdx != NumOperands; ++OpIdx) 2851 if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane])) 2852 DecrUnsched(I); 2853 } else { 2854 // If BundleMember is a stand-alone instruction, no operand reordering 2855 // has taken place, so we directly access its operands. 2856 for (Use &U : BundleMember->Inst->operands()) 2857 if (auto *I = dyn_cast<Instruction>(U.get())) 2858 DecrUnsched(I); 2859 } 2860 // Handle the memory dependencies. 2861 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) { 2862 if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) { 2863 // There are no more unscheduled dependencies after decrementing, 2864 // so we can put the dependent instruction into the ready list. 2865 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle; 2866 assert(!DepBundle->IsScheduled && 2867 "already scheduled bundle gets ready"); 2868 ReadyList.insert(DepBundle); 2869 LLVM_DEBUG(dbgs() 2870 << "SLP: gets ready (mem): " << *DepBundle << "\n"); 2871 } 2872 } 2873 // Handle the control dependencies. 2874 for (ScheduleData *DepSD : BundleMember->ControlDependencies) { 2875 if (DepSD->incrementUnscheduledDeps(-1) == 0) { 2876 // There are no more unscheduled dependencies after decrementing, 2877 // so we can put the dependent instruction into the ready list. 2878 ScheduleData *DepBundle = DepSD->FirstInBundle; 2879 assert(!DepBundle->IsScheduled && 2880 "already scheduled bundle gets ready"); 2881 ReadyList.insert(DepBundle); 2882 LLVM_DEBUG(dbgs() 2883 << "SLP: gets ready (ctl): " << *DepBundle << "\n"); 2884 } 2885 } 2886 2887 } 2888 } 2889 2890 /// Verify basic self consistency properties of the data structure. 2891 void verify() { 2892 if (!ScheduleStart) 2893 return; 2894 2895 assert(ScheduleStart->getParent() == ScheduleEnd->getParent() && 2896 ScheduleStart->comesBefore(ScheduleEnd) && 2897 "Not a valid scheduling region?"); 2898 2899 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 2900 auto *SD = getScheduleData(I); 2901 if (!SD) 2902 continue; 2903 assert(isInSchedulingRegion(SD) && 2904 "primary schedule data not in window?"); 2905 assert(isInSchedulingRegion(SD->FirstInBundle) && 2906 "entire bundle in window!"); 2907 (void)SD; 2908 doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); }); 2909 } 2910 2911 for (auto *SD : ReadyInsts) { 2912 assert(SD->isSchedulingEntity() && SD->isReady() && 2913 "item in ready list not ready?"); 2914 (void)SD; 2915 } 2916 } 2917 2918 void doForAllOpcodes(Value *V, 2919 function_ref<void(ScheduleData *SD)> Action) { 2920 if (ScheduleData *SD = getScheduleData(V)) 2921 Action(SD); 2922 auto I = ExtraScheduleDataMap.find(V); 2923 if (I != ExtraScheduleDataMap.end()) 2924 for (auto &P : I->second) 2925 if (isInSchedulingRegion(P.second)) 2926 Action(P.second); 2927 } 2928 2929 /// Put all instructions into the ReadyList which are ready for scheduling. 2930 template <typename ReadyListType> 2931 void initialFillReadyList(ReadyListType &ReadyList) { 2932 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 2933 doForAllOpcodes(I, [&](ScheduleData *SD) { 2934 if (SD->isSchedulingEntity() && SD->isReady()) { 2935 ReadyList.insert(SD); 2936 LLVM_DEBUG(dbgs() 2937 << "SLP: initially in ready list: " << *SD << "\n"); 2938 } 2939 }); 2940 } 2941 } 2942 2943 /// Build a bundle from the ScheduleData nodes corresponding to the 2944 /// scalar instruction for each lane. 2945 ScheduleData *buildBundle(ArrayRef<Value *> VL); 2946 2947 /// Checks if a bundle of instructions can be scheduled, i.e. has no 2948 /// cyclic dependencies. This is only a dry-run, no instructions are 2949 /// actually moved at this stage. 2950 /// \returns the scheduling bundle. The returned Optional value is non-None 2951 /// if \p VL is allowed to be scheduled. 2952 Optional<ScheduleData *> 2953 tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 2954 const InstructionsState &S); 2955 2956 /// Un-bundles a group of instructions. 2957 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue); 2958 2959 /// Allocates schedule data chunk. 2960 ScheduleData *allocateScheduleDataChunks(); 2961 2962 /// Extends the scheduling region so that V is inside the region. 2963 /// \returns true if the region size is within the limit. 2964 bool extendSchedulingRegion(Value *V, const InstructionsState &S); 2965 2966 /// Initialize the ScheduleData structures for new instructions in the 2967 /// scheduling region. 2968 void initScheduleData(Instruction *FromI, Instruction *ToI, 2969 ScheduleData *PrevLoadStore, 2970 ScheduleData *NextLoadStore); 2971 2972 /// Updates the dependency information of a bundle and of all instructions/ 2973 /// bundles which depend on the original bundle. 2974 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList, 2975 BoUpSLP *SLP); 2976 2977 /// Sets all instruction in the scheduling region to un-scheduled. 2978 void resetSchedule(); 2979 2980 BasicBlock *BB; 2981 2982 /// Simple memory allocation for ScheduleData. 2983 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks; 2984 2985 /// The size of a ScheduleData array in ScheduleDataChunks. 2986 int ChunkSize; 2987 2988 /// The allocator position in the current chunk, which is the last entry 2989 /// of ScheduleDataChunks. 2990 int ChunkPos; 2991 2992 /// Attaches ScheduleData to Instruction. 2993 /// Note that the mapping survives during all vectorization iterations, i.e. 2994 /// ScheduleData structures are recycled. 2995 DenseMap<Instruction *, ScheduleData *> ScheduleDataMap; 2996 2997 /// Attaches ScheduleData to Instruction with the leading key. 2998 DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>> 2999 ExtraScheduleDataMap; 3000 3001 /// The ready-list for scheduling (only used for the dry-run). 3002 SetVector<ScheduleData *> ReadyInsts; 3003 3004 /// The first instruction of the scheduling region. 3005 Instruction *ScheduleStart = nullptr; 3006 3007 /// The first instruction _after_ the scheduling region. 3008 Instruction *ScheduleEnd = nullptr; 3009 3010 /// The first memory accessing instruction in the scheduling region 3011 /// (can be null). 3012 ScheduleData *FirstLoadStoreInRegion = nullptr; 3013 3014 /// The last memory accessing instruction in the scheduling region 3015 /// (can be null). 3016 ScheduleData *LastLoadStoreInRegion = nullptr; 3017 3018 /// The current size of the scheduling region. 3019 int ScheduleRegionSize = 0; 3020 3021 /// The maximum size allowed for the scheduling region. 3022 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget; 3023 3024 /// The ID of the scheduling region. For a new vectorization iteration this 3025 /// is incremented which "removes" all ScheduleData from the region. 3026 /// Make sure that the initial SchedulingRegionID is greater than the 3027 /// initial SchedulingRegionID in ScheduleData (which is 0). 3028 int SchedulingRegionID = 1; 3029 }; 3030 3031 /// Attaches the BlockScheduling structures to basic blocks. 3032 MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules; 3033 3034 /// Performs the "real" scheduling. Done before vectorization is actually 3035 /// performed in a basic block. 3036 void scheduleBlock(BlockScheduling *BS); 3037 3038 /// List of users to ignore during scheduling and that don't need extracting. 3039 ArrayRef<Value *> UserIgnoreList; 3040 3041 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of 3042 /// sorted SmallVectors of unsigned. 3043 struct OrdersTypeDenseMapInfo { 3044 static OrdersType getEmptyKey() { 3045 OrdersType V; 3046 V.push_back(~1U); 3047 return V; 3048 } 3049 3050 static OrdersType getTombstoneKey() { 3051 OrdersType V; 3052 V.push_back(~2U); 3053 return V; 3054 } 3055 3056 static unsigned getHashValue(const OrdersType &V) { 3057 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end())); 3058 } 3059 3060 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) { 3061 return LHS == RHS; 3062 } 3063 }; 3064 3065 // Analysis and block reference. 3066 Function *F; 3067 ScalarEvolution *SE; 3068 TargetTransformInfo *TTI; 3069 TargetLibraryInfo *TLI; 3070 LoopInfo *LI; 3071 DominatorTree *DT; 3072 AssumptionCache *AC; 3073 DemandedBits *DB; 3074 const DataLayout *DL; 3075 OptimizationRemarkEmitter *ORE; 3076 3077 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt. 3078 unsigned MinVecRegSize; // Set by cl::opt (default: 128). 3079 3080 /// Instruction builder to construct the vectorized tree. 3081 IRBuilder<> Builder; 3082 3083 /// A map of scalar integer values to the smallest bit width with which they 3084 /// can legally be represented. The values map to (width, signed) pairs, 3085 /// where "width" indicates the minimum bit width and "signed" is True if the 3086 /// value must be signed-extended, rather than zero-extended, back to its 3087 /// original width. 3088 MapVector<Value *, std::pair<uint64_t, bool>> MinBWs; 3089 }; 3090 3091 } // end namespace slpvectorizer 3092 3093 template <> struct GraphTraits<BoUpSLP *> { 3094 using TreeEntry = BoUpSLP::TreeEntry; 3095 3096 /// NodeRef has to be a pointer per the GraphWriter. 3097 using NodeRef = TreeEntry *; 3098 3099 using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy; 3100 3101 /// Add the VectorizableTree to the index iterator to be able to return 3102 /// TreeEntry pointers. 3103 struct ChildIteratorType 3104 : public iterator_adaptor_base< 3105 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> { 3106 ContainerTy &VectorizableTree; 3107 3108 ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W, 3109 ContainerTy &VT) 3110 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {} 3111 3112 NodeRef operator*() { return I->UserTE; } 3113 }; 3114 3115 static NodeRef getEntryNode(BoUpSLP &R) { 3116 return R.VectorizableTree[0].get(); 3117 } 3118 3119 static ChildIteratorType child_begin(NodeRef N) { 3120 return {N->UserTreeIndices.begin(), N->Container}; 3121 } 3122 3123 static ChildIteratorType child_end(NodeRef N) { 3124 return {N->UserTreeIndices.end(), N->Container}; 3125 } 3126 3127 /// For the node iterator we just need to turn the TreeEntry iterator into a 3128 /// TreeEntry* iterator so that it dereferences to NodeRef. 3129 class nodes_iterator { 3130 using ItTy = ContainerTy::iterator; 3131 ItTy It; 3132 3133 public: 3134 nodes_iterator(const ItTy &It2) : It(It2) {} 3135 NodeRef operator*() { return It->get(); } 3136 nodes_iterator operator++() { 3137 ++It; 3138 return *this; 3139 } 3140 bool operator!=(const nodes_iterator &N2) const { return N2.It != It; } 3141 }; 3142 3143 static nodes_iterator nodes_begin(BoUpSLP *R) { 3144 return nodes_iterator(R->VectorizableTree.begin()); 3145 } 3146 3147 static nodes_iterator nodes_end(BoUpSLP *R) { 3148 return nodes_iterator(R->VectorizableTree.end()); 3149 } 3150 3151 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); } 3152 }; 3153 3154 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits { 3155 using TreeEntry = BoUpSLP::TreeEntry; 3156 3157 DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {} 3158 3159 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) { 3160 std::string Str; 3161 raw_string_ostream OS(Str); 3162 if (isSplat(Entry->Scalars)) 3163 OS << "<splat> "; 3164 for (auto V : Entry->Scalars) { 3165 OS << *V; 3166 if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) { 3167 return EU.Scalar == V; 3168 })) 3169 OS << " <extract>"; 3170 OS << "\n"; 3171 } 3172 return Str; 3173 } 3174 3175 static std::string getNodeAttributes(const TreeEntry *Entry, 3176 const BoUpSLP *) { 3177 if (Entry->State == TreeEntry::NeedToGather) 3178 return "color=red"; 3179 return ""; 3180 } 3181 }; 3182 3183 } // end namespace llvm 3184 3185 BoUpSLP::~BoUpSLP() { 3186 for (const auto &Pair : DeletedInstructions) { 3187 // Replace operands of ignored instructions with Undefs in case if they were 3188 // marked for deletion. 3189 if (Pair.getSecond()) { 3190 Value *Undef = UndefValue::get(Pair.getFirst()->getType()); 3191 Pair.getFirst()->replaceAllUsesWith(Undef); 3192 } 3193 Pair.getFirst()->dropAllReferences(); 3194 } 3195 for (const auto &Pair : DeletedInstructions) { 3196 assert(Pair.getFirst()->use_empty() && 3197 "trying to erase instruction with users."); 3198 Pair.getFirst()->eraseFromParent(); 3199 } 3200 #ifdef EXPENSIVE_CHECKS 3201 // If we could guarantee that this call is not extremely slow, we could 3202 // remove the ifdef limitation (see PR47712). 3203 assert(!verifyFunction(*F, &dbgs())); 3204 #endif 3205 } 3206 3207 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) { 3208 for (auto *V : AV) { 3209 if (auto *I = dyn_cast<Instruction>(V)) 3210 eraseInstruction(I, /*ReplaceOpsWithUndef=*/true); 3211 }; 3212 } 3213 3214 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses 3215 /// contains original mask for the scalars reused in the node. Procedure 3216 /// transform this mask in accordance with the given \p Mask. 3217 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) { 3218 assert(!Mask.empty() && Reuses.size() == Mask.size() && 3219 "Expected non-empty mask."); 3220 SmallVector<int> Prev(Reuses.begin(), Reuses.end()); 3221 Prev.swap(Reuses); 3222 for (unsigned I = 0, E = Prev.size(); I < E; ++I) 3223 if (Mask[I] != UndefMaskElem) 3224 Reuses[Mask[I]] = Prev[I]; 3225 } 3226 3227 /// Reorders the given \p Order according to the given \p Mask. \p Order - is 3228 /// the original order of the scalars. Procedure transforms the provided order 3229 /// in accordance with the given \p Mask. If the resulting \p Order is just an 3230 /// identity order, \p Order is cleared. 3231 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) { 3232 assert(!Mask.empty() && "Expected non-empty mask."); 3233 SmallVector<int> MaskOrder; 3234 if (Order.empty()) { 3235 MaskOrder.resize(Mask.size()); 3236 std::iota(MaskOrder.begin(), MaskOrder.end(), 0); 3237 } else { 3238 inversePermutation(Order, MaskOrder); 3239 } 3240 reorderReuses(MaskOrder, Mask); 3241 if (ShuffleVectorInst::isIdentityMask(MaskOrder)) { 3242 Order.clear(); 3243 return; 3244 } 3245 Order.assign(Mask.size(), Mask.size()); 3246 for (unsigned I = 0, E = Mask.size(); I < E; ++I) 3247 if (MaskOrder[I] != UndefMaskElem) 3248 Order[MaskOrder[I]] = I; 3249 fixupOrderingIndices(Order); 3250 } 3251 3252 Optional<BoUpSLP::OrdersType> 3253 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) { 3254 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only."); 3255 unsigned NumScalars = TE.Scalars.size(); 3256 OrdersType CurrentOrder(NumScalars, NumScalars); 3257 SmallVector<int> Positions; 3258 SmallBitVector UsedPositions(NumScalars); 3259 const TreeEntry *STE = nullptr; 3260 // Try to find all gathered scalars that are gets vectorized in other 3261 // vectorize node. Here we can have only one single tree vector node to 3262 // correctly identify order of the gathered scalars. 3263 for (unsigned I = 0; I < NumScalars; ++I) { 3264 Value *V = TE.Scalars[I]; 3265 if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V)) 3266 continue; 3267 if (const auto *LocalSTE = getTreeEntry(V)) { 3268 if (!STE) 3269 STE = LocalSTE; 3270 else if (STE != LocalSTE) 3271 // Take the order only from the single vector node. 3272 return None; 3273 unsigned Lane = 3274 std::distance(STE->Scalars.begin(), find(STE->Scalars, V)); 3275 if (Lane >= NumScalars) 3276 return None; 3277 if (CurrentOrder[Lane] != NumScalars) { 3278 if (Lane != I) 3279 continue; 3280 UsedPositions.reset(CurrentOrder[Lane]); 3281 } 3282 // The partial identity (where only some elements of the gather node are 3283 // in the identity order) is good. 3284 CurrentOrder[Lane] = I; 3285 UsedPositions.set(I); 3286 } 3287 } 3288 // Need to keep the order if we have a vector entry and at least 2 scalars or 3289 // the vectorized entry has just 2 scalars. 3290 if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) { 3291 auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) { 3292 for (unsigned I = 0; I < NumScalars; ++I) 3293 if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars) 3294 return false; 3295 return true; 3296 }; 3297 if (IsIdentityOrder(CurrentOrder)) { 3298 CurrentOrder.clear(); 3299 return CurrentOrder; 3300 } 3301 auto *It = CurrentOrder.begin(); 3302 for (unsigned I = 0; I < NumScalars;) { 3303 if (UsedPositions.test(I)) { 3304 ++I; 3305 continue; 3306 } 3307 if (*It == NumScalars) { 3308 *It = I; 3309 ++I; 3310 } 3311 ++It; 3312 } 3313 return CurrentOrder; 3314 } 3315 return None; 3316 } 3317 3318 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE, 3319 bool TopToBottom) { 3320 // No need to reorder if need to shuffle reuses, still need to shuffle the 3321 // node. 3322 if (!TE.ReuseShuffleIndices.empty()) 3323 return None; 3324 if (TE.State == TreeEntry::Vectorize && 3325 (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) || 3326 (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) && 3327 !TE.isAltShuffle()) 3328 return TE.ReorderIndices; 3329 if (TE.State == TreeEntry::NeedToGather) { 3330 // TODO: add analysis of other gather nodes with extractelement 3331 // instructions and other values/instructions, not only undefs. 3332 if (((TE.getOpcode() == Instruction::ExtractElement && 3333 !TE.isAltShuffle()) || 3334 (all_of(TE.Scalars, 3335 [](Value *V) { 3336 return isa<UndefValue, ExtractElementInst>(V); 3337 }) && 3338 any_of(TE.Scalars, 3339 [](Value *V) { return isa<ExtractElementInst>(V); }))) && 3340 all_of(TE.Scalars, 3341 [](Value *V) { 3342 auto *EE = dyn_cast<ExtractElementInst>(V); 3343 return !EE || isa<FixedVectorType>(EE->getVectorOperandType()); 3344 }) && 3345 allSameType(TE.Scalars)) { 3346 // Check that gather of extractelements can be represented as 3347 // just a shuffle of a single vector. 3348 OrdersType CurrentOrder; 3349 bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder); 3350 if (Reuse || !CurrentOrder.empty()) { 3351 if (!CurrentOrder.empty()) 3352 fixupOrderingIndices(CurrentOrder); 3353 return CurrentOrder; 3354 } 3355 } 3356 if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE)) 3357 return CurrentOrder; 3358 } 3359 return None; 3360 } 3361 3362 void BoUpSLP::reorderTopToBottom() { 3363 // Maps VF to the graph nodes. 3364 DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries; 3365 // ExtractElement gather nodes which can be vectorized and need to handle 3366 // their ordering. 3367 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3368 // Find all reorderable nodes with the given VF. 3369 // Currently the are vectorized stores,loads,extracts + some gathering of 3370 // extracts. 3371 for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders]( 3372 const std::unique_ptr<TreeEntry> &TE) { 3373 if (Optional<OrdersType> CurrentOrder = 3374 getReorderingData(*TE, /*TopToBottom=*/true)) { 3375 // Do not include ordering for nodes used in the alt opcode vectorization, 3376 // better to reorder them during bottom-to-top stage. If follow the order 3377 // here, it causes reordering of the whole graph though actually it is 3378 // profitable just to reorder the subgraph that starts from the alternate 3379 // opcode vectorization node. Such nodes already end-up with the shuffle 3380 // instruction and it is just enough to change this shuffle rather than 3381 // rotate the scalars for the whole graph. 3382 unsigned Cnt = 0; 3383 const TreeEntry *UserTE = TE.get(); 3384 while (UserTE && Cnt < RecursionMaxDepth) { 3385 if (UserTE->UserTreeIndices.size() != 1) 3386 break; 3387 if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) { 3388 return EI.UserTE->State == TreeEntry::Vectorize && 3389 EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0; 3390 })) 3391 return; 3392 if (UserTE->UserTreeIndices.empty()) 3393 UserTE = nullptr; 3394 else 3395 UserTE = UserTE->UserTreeIndices.back().UserTE; 3396 ++Cnt; 3397 } 3398 VFToOrderedEntries[TE->Scalars.size()].insert(TE.get()); 3399 if (TE->State != TreeEntry::Vectorize) 3400 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3401 } 3402 }); 3403 3404 // Reorder the graph nodes according to their vectorization factor. 3405 for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1; 3406 VF /= 2) { 3407 auto It = VFToOrderedEntries.find(VF); 3408 if (It == VFToOrderedEntries.end()) 3409 continue; 3410 // Try to find the most profitable order. We just are looking for the most 3411 // used order and reorder scalar elements in the nodes according to this 3412 // mostly used order. 3413 ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef(); 3414 // All operands are reordered and used only in this node - propagate the 3415 // most used order to the user node. 3416 MapVector<OrdersType, unsigned, 3417 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3418 OrdersUses; 3419 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3420 for (const TreeEntry *OpTE : OrderedEntries) { 3421 // No need to reorder this nodes, still need to extend and to use shuffle, 3422 // just need to merge reordering shuffle and the reuse shuffle. 3423 if (!OpTE->ReuseShuffleIndices.empty()) 3424 continue; 3425 // Count number of orders uses. 3426 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3427 if (OpTE->State == TreeEntry::NeedToGather) 3428 return GathersToOrders.find(OpTE)->second; 3429 return OpTE->ReorderIndices; 3430 }(); 3431 // Stores actually store the mask, not the order, need to invert. 3432 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3433 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3434 SmallVector<int> Mask; 3435 inversePermutation(Order, Mask); 3436 unsigned E = Order.size(); 3437 OrdersType CurrentOrder(E, E); 3438 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3439 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3440 }); 3441 fixupOrderingIndices(CurrentOrder); 3442 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second; 3443 } else { 3444 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second; 3445 } 3446 } 3447 // Set order of the user node. 3448 if (OrdersUses.empty()) 3449 continue; 3450 // Choose the most used order. 3451 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3452 unsigned Cnt = OrdersUses.front().second; 3453 for (const auto &Pair : drop_begin(OrdersUses)) { 3454 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3455 BestOrder = Pair.first; 3456 Cnt = Pair.second; 3457 } 3458 } 3459 // Set order of the user node. 3460 if (BestOrder.empty()) 3461 continue; 3462 SmallVector<int> Mask; 3463 inversePermutation(BestOrder, Mask); 3464 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3465 unsigned E = BestOrder.size(); 3466 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3467 return I < E ? static_cast<int>(I) : UndefMaskElem; 3468 }); 3469 // Do an actual reordering, if profitable. 3470 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 3471 // Just do the reordering for the nodes with the given VF. 3472 if (TE->Scalars.size() != VF) { 3473 if (TE->ReuseShuffleIndices.size() == VF) { 3474 // Need to reorder the reuses masks of the operands with smaller VF to 3475 // be able to find the match between the graph nodes and scalar 3476 // operands of the given node during vectorization/cost estimation. 3477 assert(all_of(TE->UserTreeIndices, 3478 [VF, &TE](const EdgeInfo &EI) { 3479 return EI.UserTE->Scalars.size() == VF || 3480 EI.UserTE->Scalars.size() == 3481 TE->Scalars.size(); 3482 }) && 3483 "All users must be of VF size."); 3484 // Update ordering of the operands with the smaller VF than the given 3485 // one. 3486 reorderReuses(TE->ReuseShuffleIndices, Mask); 3487 } 3488 continue; 3489 } 3490 if (TE->State == TreeEntry::Vectorize && 3491 isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst, 3492 InsertElementInst>(TE->getMainOp()) && 3493 !TE->isAltShuffle()) { 3494 // Build correct orders for extract{element,value}, loads and 3495 // stores. 3496 reorderOrder(TE->ReorderIndices, Mask); 3497 if (isa<InsertElementInst, StoreInst>(TE->getMainOp())) 3498 TE->reorderOperands(Mask); 3499 } else { 3500 // Reorder the node and its operands. 3501 TE->reorderOperands(Mask); 3502 assert(TE->ReorderIndices.empty() && 3503 "Expected empty reorder sequence."); 3504 reorderScalars(TE->Scalars, Mask); 3505 } 3506 if (!TE->ReuseShuffleIndices.empty()) { 3507 // Apply reversed order to keep the original ordering of the reused 3508 // elements to avoid extra reorder indices shuffling. 3509 OrdersType CurrentOrder; 3510 reorderOrder(CurrentOrder, MaskOrder); 3511 SmallVector<int> NewReuses; 3512 inversePermutation(CurrentOrder, NewReuses); 3513 addMask(NewReuses, TE->ReuseShuffleIndices); 3514 TE->ReuseShuffleIndices.swap(NewReuses); 3515 } 3516 } 3517 } 3518 } 3519 3520 bool BoUpSLP::canReorderOperands( 3521 TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges, 3522 ArrayRef<TreeEntry *> ReorderableGathers, 3523 SmallVectorImpl<TreeEntry *> &GatherOps) { 3524 for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) { 3525 if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) { 3526 return OpData.first == I && 3527 OpData.second->State == TreeEntry::Vectorize; 3528 })) 3529 continue; 3530 if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) { 3531 // Do not reorder if operand node is used by many user nodes. 3532 if (any_of(TE->UserTreeIndices, 3533 [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; })) 3534 return false; 3535 // Add the node to the list of the ordered nodes with the identity 3536 // order. 3537 Edges.emplace_back(I, TE); 3538 continue; 3539 } 3540 ArrayRef<Value *> VL = UserTE->getOperand(I); 3541 TreeEntry *Gather = nullptr; 3542 if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) { 3543 assert(TE->State != TreeEntry::Vectorize && 3544 "Only non-vectorized nodes are expected."); 3545 if (TE->isSame(VL)) { 3546 Gather = TE; 3547 return true; 3548 } 3549 return false; 3550 }) > 1) 3551 return false; 3552 if (Gather) 3553 GatherOps.push_back(Gather); 3554 } 3555 return true; 3556 } 3557 3558 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) { 3559 SetVector<TreeEntry *> OrderedEntries; 3560 DenseMap<const TreeEntry *, OrdersType> GathersToOrders; 3561 // Find all reorderable leaf nodes with the given VF. 3562 // Currently the are vectorized loads,extracts without alternate operands + 3563 // some gathering of extracts. 3564 SmallVector<TreeEntry *> NonVectorized; 3565 for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders, 3566 &NonVectorized]( 3567 const std::unique_ptr<TreeEntry> &TE) { 3568 if (TE->State != TreeEntry::Vectorize) 3569 NonVectorized.push_back(TE.get()); 3570 if (Optional<OrdersType> CurrentOrder = 3571 getReorderingData(*TE, /*TopToBottom=*/false)) { 3572 OrderedEntries.insert(TE.get()); 3573 if (TE->State != TreeEntry::Vectorize) 3574 GathersToOrders.try_emplace(TE.get(), *CurrentOrder); 3575 } 3576 }); 3577 3578 // 1. Propagate order to the graph nodes, which use only reordered nodes. 3579 // I.e., if the node has operands, that are reordered, try to make at least 3580 // one operand order in the natural order and reorder others + reorder the 3581 // user node itself. 3582 SmallPtrSet<const TreeEntry *, 4> Visited; 3583 while (!OrderedEntries.empty()) { 3584 // 1. Filter out only reordered nodes. 3585 // 2. If the entry has multiple uses - skip it and jump to the next node. 3586 MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users; 3587 SmallVector<TreeEntry *> Filtered; 3588 for (TreeEntry *TE : OrderedEntries) { 3589 if (!(TE->State == TreeEntry::Vectorize || 3590 (TE->State == TreeEntry::NeedToGather && 3591 GathersToOrders.count(TE))) || 3592 TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() || 3593 !all_of(drop_begin(TE->UserTreeIndices), 3594 [TE](const EdgeInfo &EI) { 3595 return EI.UserTE == TE->UserTreeIndices.front().UserTE; 3596 }) || 3597 !Visited.insert(TE).second) { 3598 Filtered.push_back(TE); 3599 continue; 3600 } 3601 // Build a map between user nodes and their operands order to speedup 3602 // search. The graph currently does not provide this dependency directly. 3603 for (EdgeInfo &EI : TE->UserTreeIndices) { 3604 TreeEntry *UserTE = EI.UserTE; 3605 auto It = Users.find(UserTE); 3606 if (It == Users.end()) 3607 It = Users.insert({UserTE, {}}).first; 3608 It->second.emplace_back(EI.EdgeIdx, TE); 3609 } 3610 } 3611 // Erase filtered entries. 3612 for_each(Filtered, 3613 [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); }); 3614 for (auto &Data : Users) { 3615 // Check that operands are used only in the User node. 3616 SmallVector<TreeEntry *> GatherOps; 3617 if (!canReorderOperands(Data.first, Data.second, NonVectorized, 3618 GatherOps)) { 3619 for_each(Data.second, 3620 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3621 OrderedEntries.remove(Op.second); 3622 }); 3623 continue; 3624 } 3625 // All operands are reordered and used only in this node - propagate the 3626 // most used order to the user node. 3627 MapVector<OrdersType, unsigned, 3628 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>> 3629 OrdersUses; 3630 // Do the analysis for each tree entry only once, otherwise the order of 3631 // the same node my be considered several times, though might be not 3632 // profitable. 3633 SmallPtrSet<const TreeEntry *, 4> VisitedOps; 3634 SmallPtrSet<const TreeEntry *, 4> VisitedUsers; 3635 for (const auto &Op : Data.second) { 3636 TreeEntry *OpTE = Op.second; 3637 if (!VisitedOps.insert(OpTE).second) 3638 continue; 3639 if (!OpTE->ReuseShuffleIndices.empty() || 3640 (IgnoreReorder && OpTE == VectorizableTree.front().get())) 3641 continue; 3642 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & { 3643 if (OpTE->State == TreeEntry::NeedToGather) 3644 return GathersToOrders.find(OpTE)->second; 3645 return OpTE->ReorderIndices; 3646 }(); 3647 unsigned NumOps = count_if( 3648 Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) { 3649 return P.second == OpTE; 3650 }); 3651 // Stores actually store the mask, not the order, need to invert. 3652 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() && 3653 OpTE->getOpcode() == Instruction::Store && !Order.empty()) { 3654 SmallVector<int> Mask; 3655 inversePermutation(Order, Mask); 3656 unsigned E = Order.size(); 3657 OrdersType CurrentOrder(E, E); 3658 transform(Mask, CurrentOrder.begin(), [E](int Idx) { 3659 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx); 3660 }); 3661 fixupOrderingIndices(CurrentOrder); 3662 OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second += 3663 NumOps; 3664 } else { 3665 OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps; 3666 } 3667 auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0)); 3668 const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders]( 3669 const TreeEntry *TE) { 3670 if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() || 3671 (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) || 3672 (IgnoreReorder && TE->Idx == 0)) 3673 return true; 3674 if (TE->State == TreeEntry::NeedToGather) { 3675 auto It = GathersToOrders.find(TE); 3676 if (It != GathersToOrders.end()) 3677 return !It->second.empty(); 3678 return true; 3679 } 3680 return false; 3681 }; 3682 for (const EdgeInfo &EI : OpTE->UserTreeIndices) { 3683 TreeEntry *UserTE = EI.UserTE; 3684 if (!VisitedUsers.insert(UserTE).second) 3685 continue; 3686 // May reorder user node if it requires reordering, has reused 3687 // scalars, is an alternate op vectorize node or its op nodes require 3688 // reordering. 3689 if (AllowsReordering(UserTE)) 3690 continue; 3691 // Check if users allow reordering. 3692 // Currently look up just 1 level of operands to avoid increase of 3693 // the compile time. 3694 // Profitable to reorder if definitely more operands allow 3695 // reordering rather than those with natural order. 3696 ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE]; 3697 if (static_cast<unsigned>(count_if( 3698 Ops, [UserTE, &AllowsReordering]( 3699 const std::pair<unsigned, TreeEntry *> &Op) { 3700 return AllowsReordering(Op.second) && 3701 all_of(Op.second->UserTreeIndices, 3702 [UserTE](const EdgeInfo &EI) { 3703 return EI.UserTE == UserTE; 3704 }); 3705 })) <= Ops.size() / 2) 3706 ++Res.first->second; 3707 } 3708 } 3709 // If no orders - skip current nodes and jump to the next one, if any. 3710 if (OrdersUses.empty()) { 3711 for_each(Data.second, 3712 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3713 OrderedEntries.remove(Op.second); 3714 }); 3715 continue; 3716 } 3717 // Choose the best order. 3718 ArrayRef<unsigned> BestOrder = OrdersUses.front().first; 3719 unsigned Cnt = OrdersUses.front().second; 3720 for (const auto &Pair : drop_begin(OrdersUses)) { 3721 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) { 3722 BestOrder = Pair.first; 3723 Cnt = Pair.second; 3724 } 3725 } 3726 // Set order of the user node (reordering of operands and user nodes). 3727 if (BestOrder.empty()) { 3728 for_each(Data.second, 3729 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) { 3730 OrderedEntries.remove(Op.second); 3731 }); 3732 continue; 3733 } 3734 // Erase operands from OrderedEntries list and adjust their orders. 3735 VisitedOps.clear(); 3736 SmallVector<int> Mask; 3737 inversePermutation(BestOrder, Mask); 3738 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem); 3739 unsigned E = BestOrder.size(); 3740 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) { 3741 return I < E ? static_cast<int>(I) : UndefMaskElem; 3742 }); 3743 for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) { 3744 TreeEntry *TE = Op.second; 3745 OrderedEntries.remove(TE); 3746 if (!VisitedOps.insert(TE).second) 3747 continue; 3748 if (TE->ReuseShuffleIndices.size() == BestOrder.size()) { 3749 // Just reorder reuses indices. 3750 reorderReuses(TE->ReuseShuffleIndices, Mask); 3751 continue; 3752 } 3753 // Gathers are processed separately. 3754 if (TE->State != TreeEntry::Vectorize) 3755 continue; 3756 assert((BestOrder.size() == TE->ReorderIndices.size() || 3757 TE->ReorderIndices.empty()) && 3758 "Non-matching sizes of user/operand entries."); 3759 reorderOrder(TE->ReorderIndices, Mask); 3760 } 3761 // For gathers just need to reorder its scalars. 3762 for (TreeEntry *Gather : GatherOps) { 3763 assert(Gather->ReorderIndices.empty() && 3764 "Unexpected reordering of gathers."); 3765 if (!Gather->ReuseShuffleIndices.empty()) { 3766 // Just reorder reuses indices. 3767 reorderReuses(Gather->ReuseShuffleIndices, Mask); 3768 continue; 3769 } 3770 reorderScalars(Gather->Scalars, Mask); 3771 OrderedEntries.remove(Gather); 3772 } 3773 // Reorder operands of the user node and set the ordering for the user 3774 // node itself. 3775 if (Data.first->State != TreeEntry::Vectorize || 3776 !isa<ExtractElementInst, ExtractValueInst, LoadInst>( 3777 Data.first->getMainOp()) || 3778 Data.first->isAltShuffle()) 3779 Data.first->reorderOperands(Mask); 3780 if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) || 3781 Data.first->isAltShuffle()) { 3782 reorderScalars(Data.first->Scalars, Mask); 3783 reorderOrder(Data.first->ReorderIndices, MaskOrder); 3784 if (Data.first->ReuseShuffleIndices.empty() && 3785 !Data.first->ReorderIndices.empty() && 3786 !Data.first->isAltShuffle()) { 3787 // Insert user node to the list to try to sink reordering deeper in 3788 // the graph. 3789 OrderedEntries.insert(Data.first); 3790 } 3791 } else { 3792 reorderOrder(Data.first->ReorderIndices, Mask); 3793 } 3794 } 3795 } 3796 // If the reordering is unnecessary, just remove the reorder. 3797 if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() && 3798 VectorizableTree.front()->ReuseShuffleIndices.empty()) 3799 VectorizableTree.front()->ReorderIndices.clear(); 3800 } 3801 3802 void BoUpSLP::buildExternalUses( 3803 const ExtraValueToDebugLocsMap &ExternallyUsedValues) { 3804 // Collect the values that we need to extract from the tree. 3805 for (auto &TEPtr : VectorizableTree) { 3806 TreeEntry *Entry = TEPtr.get(); 3807 3808 // No need to handle users of gathered values. 3809 if (Entry->State == TreeEntry::NeedToGather) 3810 continue; 3811 3812 // For each lane: 3813 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 3814 Value *Scalar = Entry->Scalars[Lane]; 3815 int FoundLane = Entry->findLaneForValue(Scalar); 3816 3817 // Check if the scalar is externally used as an extra arg. 3818 auto ExtI = ExternallyUsedValues.find(Scalar); 3819 if (ExtI != ExternallyUsedValues.end()) { 3820 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane " 3821 << Lane << " from " << *Scalar << ".\n"); 3822 ExternalUses.emplace_back(Scalar, nullptr, FoundLane); 3823 } 3824 for (User *U : Scalar->users()) { 3825 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n"); 3826 3827 Instruction *UserInst = dyn_cast<Instruction>(U); 3828 if (!UserInst) 3829 continue; 3830 3831 if (isDeleted(UserInst)) 3832 continue; 3833 3834 // Skip in-tree scalars that become vectors 3835 if (TreeEntry *UseEntry = getTreeEntry(U)) { 3836 Value *UseScalar = UseEntry->Scalars[0]; 3837 // Some in-tree scalars will remain as scalar in vectorized 3838 // instructions. If that is the case, the one in Lane 0 will 3839 // be used. 3840 if (UseScalar != U || 3841 UseEntry->State == TreeEntry::ScatterVectorize || 3842 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) { 3843 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U 3844 << ".\n"); 3845 assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state"); 3846 continue; 3847 } 3848 } 3849 3850 // Ignore users in the user ignore list. 3851 if (is_contained(UserIgnoreList, UserInst)) 3852 continue; 3853 3854 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane " 3855 << Lane << " from " << *Scalar << ".\n"); 3856 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane)); 3857 } 3858 } 3859 } 3860 } 3861 3862 void BoUpSLP::buildTree(ArrayRef<Value *> Roots, 3863 ArrayRef<Value *> UserIgnoreLst) { 3864 deleteTree(); 3865 UserIgnoreList = UserIgnoreLst; 3866 if (!allSameType(Roots)) 3867 return; 3868 buildTree_rec(Roots, 0, EdgeInfo()); 3869 } 3870 3871 namespace { 3872 /// Tracks the state we can represent the loads in the given sequence. 3873 enum class LoadsState { Gather, Vectorize, ScatterVectorize }; 3874 } // anonymous namespace 3875 3876 /// Checks if the given array of loads can be represented as a vectorized, 3877 /// scatter or just simple gather. 3878 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0, 3879 const TargetTransformInfo &TTI, 3880 const DataLayout &DL, ScalarEvolution &SE, 3881 SmallVectorImpl<unsigned> &Order, 3882 SmallVectorImpl<Value *> &PointerOps) { 3883 // Check that a vectorized load would load the same memory as a scalar 3884 // load. For example, we don't want to vectorize loads that are smaller 3885 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 3886 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 3887 // from such a struct, we read/write packed bits disagreeing with the 3888 // unvectorized version. 3889 Type *ScalarTy = VL0->getType(); 3890 3891 if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy)) 3892 return LoadsState::Gather; 3893 3894 // Make sure all loads in the bundle are simple - we can't vectorize 3895 // atomic or volatile loads. 3896 PointerOps.clear(); 3897 PointerOps.resize(VL.size()); 3898 auto *POIter = PointerOps.begin(); 3899 for (Value *V : VL) { 3900 auto *L = cast<LoadInst>(V); 3901 if (!L->isSimple()) 3902 return LoadsState::Gather; 3903 *POIter = L->getPointerOperand(); 3904 ++POIter; 3905 } 3906 3907 Order.clear(); 3908 // Check the order of pointer operands. 3909 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) { 3910 Value *Ptr0; 3911 Value *PtrN; 3912 if (Order.empty()) { 3913 Ptr0 = PointerOps.front(); 3914 PtrN = PointerOps.back(); 3915 } else { 3916 Ptr0 = PointerOps[Order.front()]; 3917 PtrN = PointerOps[Order.back()]; 3918 } 3919 Optional<int> Diff = 3920 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE); 3921 // Check that the sorted loads are consecutive. 3922 if (static_cast<unsigned>(*Diff) == VL.size() - 1) 3923 return LoadsState::Vectorize; 3924 Align CommonAlignment = cast<LoadInst>(VL0)->getAlign(); 3925 for (Value *V : VL) 3926 CommonAlignment = 3927 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 3928 if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()), 3929 CommonAlignment)) 3930 return LoadsState::ScatterVectorize; 3931 } 3932 3933 return LoadsState::Gather; 3934 } 3935 3936 /// \return true if the specified list of values has only one instruction that 3937 /// requires scheduling, false otherwise. 3938 #ifndef NDEBUG 3939 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) { 3940 Value *NeedsScheduling = nullptr; 3941 for (Value *V : VL) { 3942 if (doesNotNeedToBeScheduled(V)) 3943 continue; 3944 if (!NeedsScheduling) { 3945 NeedsScheduling = V; 3946 continue; 3947 } 3948 return false; 3949 } 3950 return NeedsScheduling; 3951 } 3952 #endif 3953 3954 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth, 3955 const EdgeInfo &UserTreeIdx) { 3956 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!"); 3957 3958 SmallVector<int> ReuseShuffleIndicies; 3959 SmallVector<Value *> UniqueValues; 3960 auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues, 3961 &UserTreeIdx, 3962 this](const InstructionsState &S) { 3963 // Check that every instruction appears once in this bundle. 3964 DenseMap<Value *, unsigned> UniquePositions; 3965 for (Value *V : VL) { 3966 if (isConstant(V)) { 3967 ReuseShuffleIndicies.emplace_back( 3968 isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size()); 3969 UniqueValues.emplace_back(V); 3970 continue; 3971 } 3972 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 3973 ReuseShuffleIndicies.emplace_back(Res.first->second); 3974 if (Res.second) 3975 UniqueValues.emplace_back(V); 3976 } 3977 size_t NumUniqueScalarValues = UniqueValues.size(); 3978 if (NumUniqueScalarValues == VL.size()) { 3979 ReuseShuffleIndicies.clear(); 3980 } else { 3981 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n"); 3982 if (NumUniqueScalarValues <= 1 || 3983 (UniquePositions.size() == 1 && all_of(UniqueValues, 3984 [](Value *V) { 3985 return isa<UndefValue>(V) || 3986 !isConstant(V); 3987 })) || 3988 !llvm::isPowerOf2_32(NumUniqueScalarValues)) { 3989 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n"); 3990 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 3991 return false; 3992 } 3993 VL = UniqueValues; 3994 } 3995 return true; 3996 }; 3997 3998 InstructionsState S = getSameOpcode(VL); 3999 if (Depth == RecursionMaxDepth) { 4000 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n"); 4001 if (TryToFindDuplicates(S)) 4002 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4003 ReuseShuffleIndicies); 4004 return; 4005 } 4006 4007 // Don't handle scalable vectors 4008 if (S.getOpcode() == Instruction::ExtractElement && 4009 isa<ScalableVectorType>( 4010 cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) { 4011 LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n"); 4012 if (TryToFindDuplicates(S)) 4013 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4014 ReuseShuffleIndicies); 4015 return; 4016 } 4017 4018 // Don't handle vectors. 4019 if (S.OpValue->getType()->isVectorTy() && 4020 !isa<InsertElementInst>(S.OpValue)) { 4021 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n"); 4022 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4023 return; 4024 } 4025 4026 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue)) 4027 if (SI->getValueOperand()->getType()->isVectorTy()) { 4028 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n"); 4029 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4030 return; 4031 } 4032 4033 // If all of the operands are identical or constant we have a simple solution. 4034 // If we deal with insert/extract instructions, they all must have constant 4035 // indices, otherwise we should gather them, not try to vectorize. 4036 if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() || 4037 (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) && 4038 !all_of(VL, isVectorLikeInstWithConstOps))) { 4039 LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n"); 4040 if (TryToFindDuplicates(S)) 4041 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4042 ReuseShuffleIndicies); 4043 return; 4044 } 4045 4046 // We now know that this is a vector of instructions of the same type from 4047 // the same block. 4048 4049 // Don't vectorize ephemeral values. 4050 for (Value *V : VL) { 4051 if (EphValues.count(V)) { 4052 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 4053 << ") is ephemeral.\n"); 4054 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4055 return; 4056 } 4057 } 4058 4059 // Check if this is a duplicate of another entry. 4060 if (TreeEntry *E = getTreeEntry(S.OpValue)) { 4061 LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n"); 4062 if (!E->isSame(VL)) { 4063 LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n"); 4064 if (TryToFindDuplicates(S)) 4065 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4066 ReuseShuffleIndicies); 4067 return; 4068 } 4069 // Record the reuse of the tree node. FIXME, currently this is only used to 4070 // properly draw the graph rather than for the actual vectorization. 4071 E->UserTreeIndices.push_back(UserTreeIdx); 4072 LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue 4073 << ".\n"); 4074 return; 4075 } 4076 4077 // Check that none of the instructions in the bundle are already in the tree. 4078 for (Value *V : VL) { 4079 auto *I = dyn_cast<Instruction>(V); 4080 if (!I) 4081 continue; 4082 if (getTreeEntry(I)) { 4083 LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V 4084 << ") is already in tree.\n"); 4085 if (TryToFindDuplicates(S)) 4086 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4087 ReuseShuffleIndicies); 4088 return; 4089 } 4090 } 4091 4092 // The reduction nodes (stored in UserIgnoreList) also should stay scalar. 4093 for (Value *V : VL) { 4094 if (is_contained(UserIgnoreList, V)) { 4095 LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n"); 4096 if (TryToFindDuplicates(S)) 4097 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4098 ReuseShuffleIndicies); 4099 return; 4100 } 4101 } 4102 4103 // Check that all of the users of the scalars that we want to vectorize are 4104 // schedulable. 4105 auto *VL0 = cast<Instruction>(S.OpValue); 4106 BasicBlock *BB = VL0->getParent(); 4107 4108 if (!DT->isReachableFromEntry(BB)) { 4109 // Don't go into unreachable blocks. They may contain instructions with 4110 // dependency cycles which confuse the final scheduling. 4111 LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n"); 4112 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4113 return; 4114 } 4115 4116 // Check that every instruction appears once in this bundle. 4117 if (!TryToFindDuplicates(S)) 4118 return; 4119 4120 auto &BSRef = BlocksSchedules[BB]; 4121 if (!BSRef) 4122 BSRef = std::make_unique<BlockScheduling>(BB); 4123 4124 BlockScheduling &BS = *BSRef; 4125 4126 Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S); 4127 #ifdef EXPENSIVE_CHECKS 4128 // Make sure we didn't break any internal invariants 4129 BS.verify(); 4130 #endif 4131 if (!Bundle) { 4132 LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n"); 4133 assert((!BS.getScheduleData(VL0) || 4134 !BS.getScheduleData(VL0)->isPartOfBundle()) && 4135 "tryScheduleBundle should cancelScheduling on failure"); 4136 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4137 ReuseShuffleIndicies); 4138 return; 4139 } 4140 LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n"); 4141 4142 unsigned ShuffleOrOp = S.isAltShuffle() ? 4143 (unsigned) Instruction::ShuffleVector : S.getOpcode(); 4144 switch (ShuffleOrOp) { 4145 case Instruction::PHI: { 4146 auto *PH = cast<PHINode>(VL0); 4147 4148 // Check for terminator values (e.g. invoke). 4149 for (Value *V : VL) 4150 for (Value *Incoming : cast<PHINode>(V)->incoming_values()) { 4151 Instruction *Term = dyn_cast<Instruction>(Incoming); 4152 if (Term && Term->isTerminator()) { 4153 LLVM_DEBUG(dbgs() 4154 << "SLP: Need to swizzle PHINodes (terminator use).\n"); 4155 BS.cancelScheduling(VL, VL0); 4156 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4157 ReuseShuffleIndicies); 4158 return; 4159 } 4160 } 4161 4162 TreeEntry *TE = 4163 newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies); 4164 LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n"); 4165 4166 // Keeps the reordered operands to avoid code duplication. 4167 SmallVector<ValueList, 2> OperandsVec; 4168 for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) { 4169 if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) { 4170 ValueList Operands(VL.size(), PoisonValue::get(PH->getType())); 4171 TE->setOperand(I, Operands); 4172 OperandsVec.push_back(Operands); 4173 continue; 4174 } 4175 ValueList Operands; 4176 // Prepare the operand vector. 4177 for (Value *V : VL) 4178 Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock( 4179 PH->getIncomingBlock(I))); 4180 TE->setOperand(I, Operands); 4181 OperandsVec.push_back(Operands); 4182 } 4183 for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx) 4184 buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx}); 4185 return; 4186 } 4187 case Instruction::ExtractValue: 4188 case Instruction::ExtractElement: { 4189 OrdersType CurrentOrder; 4190 bool Reuse = canReuseExtract(VL, VL0, CurrentOrder); 4191 if (Reuse) { 4192 LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n"); 4193 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4194 ReuseShuffleIndicies); 4195 // This is a special case, as it does not gather, but at the same time 4196 // we are not extending buildTree_rec() towards the operands. 4197 ValueList Op0; 4198 Op0.assign(VL.size(), VL0->getOperand(0)); 4199 VectorizableTree.back()->setOperand(0, Op0); 4200 return; 4201 } 4202 if (!CurrentOrder.empty()) { 4203 LLVM_DEBUG({ 4204 dbgs() << "SLP: Reusing or shuffling of reordered extract sequence " 4205 "with order"; 4206 for (unsigned Idx : CurrentOrder) 4207 dbgs() << " " << Idx; 4208 dbgs() << "\n"; 4209 }); 4210 fixupOrderingIndices(CurrentOrder); 4211 // Insert new order with initial value 0, if it does not exist, 4212 // otherwise return the iterator to the existing one. 4213 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4214 ReuseShuffleIndicies, CurrentOrder); 4215 // This is a special case, as it does not gather, but at the same time 4216 // we are not extending buildTree_rec() towards the operands. 4217 ValueList Op0; 4218 Op0.assign(VL.size(), VL0->getOperand(0)); 4219 VectorizableTree.back()->setOperand(0, Op0); 4220 return; 4221 } 4222 LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n"); 4223 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4224 ReuseShuffleIndicies); 4225 BS.cancelScheduling(VL, VL0); 4226 return; 4227 } 4228 case Instruction::InsertElement: { 4229 assert(ReuseShuffleIndicies.empty() && "All inserts should be unique"); 4230 4231 // Check that we have a buildvector and not a shuffle of 2 or more 4232 // different vectors. 4233 ValueSet SourceVectors; 4234 for (Value *V : VL) { 4235 SourceVectors.insert(cast<Instruction>(V)->getOperand(0)); 4236 assert(getInsertIndex(V) != None && "Non-constant or undef index?"); 4237 } 4238 4239 if (count_if(VL, [&SourceVectors](Value *V) { 4240 return !SourceVectors.contains(V); 4241 }) >= 2) { 4242 // Found 2nd source vector - cancel. 4243 LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with " 4244 "different source vectors.\n"); 4245 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx); 4246 BS.cancelScheduling(VL, VL0); 4247 return; 4248 } 4249 4250 auto OrdCompare = [](const std::pair<int, int> &P1, 4251 const std::pair<int, int> &P2) { 4252 return P1.first > P2.first; 4253 }; 4254 PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>, 4255 decltype(OrdCompare)> 4256 Indices(OrdCompare); 4257 for (int I = 0, E = VL.size(); I < E; ++I) { 4258 unsigned Idx = *getInsertIndex(VL[I]); 4259 Indices.emplace(Idx, I); 4260 } 4261 OrdersType CurrentOrder(VL.size(), VL.size()); 4262 bool IsIdentity = true; 4263 for (int I = 0, E = VL.size(); I < E; ++I) { 4264 CurrentOrder[Indices.top().second] = I; 4265 IsIdentity &= Indices.top().second == I; 4266 Indices.pop(); 4267 } 4268 if (IsIdentity) 4269 CurrentOrder.clear(); 4270 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4271 None, CurrentOrder); 4272 LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n"); 4273 4274 constexpr int NumOps = 2; 4275 ValueList VectorOperands[NumOps]; 4276 for (int I = 0; I < NumOps; ++I) { 4277 for (Value *V : VL) 4278 VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I)); 4279 4280 TE->setOperand(I, VectorOperands[I]); 4281 } 4282 buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1}); 4283 return; 4284 } 4285 case Instruction::Load: { 4286 // Check that a vectorized load would load the same memory as a scalar 4287 // load. For example, we don't want to vectorize loads that are smaller 4288 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM 4289 // treats loading/storing it as an i8 struct. If we vectorize loads/stores 4290 // from such a struct, we read/write packed bits disagreeing with the 4291 // unvectorized version. 4292 SmallVector<Value *> PointerOps; 4293 OrdersType CurrentOrder; 4294 TreeEntry *TE = nullptr; 4295 switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder, 4296 PointerOps)) { 4297 case LoadsState::Vectorize: 4298 if (CurrentOrder.empty()) { 4299 // Original loads are consecutive and does not require reordering. 4300 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4301 ReuseShuffleIndicies); 4302 LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n"); 4303 } else { 4304 fixupOrderingIndices(CurrentOrder); 4305 // Need to reorder. 4306 TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4307 ReuseShuffleIndicies, CurrentOrder); 4308 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n"); 4309 } 4310 TE->setOperandsInOrder(); 4311 break; 4312 case LoadsState::ScatterVectorize: 4313 // Vectorizing non-consecutive loads with `llvm.masked.gather`. 4314 TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S, 4315 UserTreeIdx, ReuseShuffleIndicies); 4316 TE->setOperandsInOrder(); 4317 buildTree_rec(PointerOps, Depth + 1, {TE, 0}); 4318 LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n"); 4319 break; 4320 case LoadsState::Gather: 4321 BS.cancelScheduling(VL, VL0); 4322 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4323 ReuseShuffleIndicies); 4324 #ifndef NDEBUG 4325 Type *ScalarTy = VL0->getType(); 4326 if (DL->getTypeSizeInBits(ScalarTy) != 4327 DL->getTypeAllocSizeInBits(ScalarTy)) 4328 LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n"); 4329 else if (any_of(VL, [](Value *V) { 4330 return !cast<LoadInst>(V)->isSimple(); 4331 })) 4332 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n"); 4333 else 4334 LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n"); 4335 #endif // NDEBUG 4336 break; 4337 } 4338 return; 4339 } 4340 case Instruction::ZExt: 4341 case Instruction::SExt: 4342 case Instruction::FPToUI: 4343 case Instruction::FPToSI: 4344 case Instruction::FPExt: 4345 case Instruction::PtrToInt: 4346 case Instruction::IntToPtr: 4347 case Instruction::SIToFP: 4348 case Instruction::UIToFP: 4349 case Instruction::Trunc: 4350 case Instruction::FPTrunc: 4351 case Instruction::BitCast: { 4352 Type *SrcTy = VL0->getOperand(0)->getType(); 4353 for (Value *V : VL) { 4354 Type *Ty = cast<Instruction>(V)->getOperand(0)->getType(); 4355 if (Ty != SrcTy || !isValidElementType(Ty)) { 4356 BS.cancelScheduling(VL, VL0); 4357 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4358 ReuseShuffleIndicies); 4359 LLVM_DEBUG(dbgs() 4360 << "SLP: Gathering casts with different src types.\n"); 4361 return; 4362 } 4363 } 4364 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4365 ReuseShuffleIndicies); 4366 LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n"); 4367 4368 TE->setOperandsInOrder(); 4369 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4370 ValueList Operands; 4371 // Prepare the operand vector. 4372 for (Value *V : VL) 4373 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4374 4375 buildTree_rec(Operands, Depth + 1, {TE, i}); 4376 } 4377 return; 4378 } 4379 case Instruction::ICmp: 4380 case Instruction::FCmp: { 4381 // Check that all of the compares have the same predicate. 4382 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 4383 CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0); 4384 Type *ComparedTy = VL0->getOperand(0)->getType(); 4385 for (Value *V : VL) { 4386 CmpInst *Cmp = cast<CmpInst>(V); 4387 if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) || 4388 Cmp->getOperand(0)->getType() != ComparedTy) { 4389 BS.cancelScheduling(VL, VL0); 4390 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4391 ReuseShuffleIndicies); 4392 LLVM_DEBUG(dbgs() 4393 << "SLP: Gathering cmp with different predicate.\n"); 4394 return; 4395 } 4396 } 4397 4398 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4399 ReuseShuffleIndicies); 4400 LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n"); 4401 4402 ValueList Left, Right; 4403 if (cast<CmpInst>(VL0)->isCommutative()) { 4404 // Commutative predicate - collect + sort operands of the instructions 4405 // so that each side is more likely to have the same opcode. 4406 assert(P0 == SwapP0 && "Commutative Predicate mismatch"); 4407 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4408 } else { 4409 // Collect operands - commute if it uses the swapped predicate. 4410 for (Value *V : VL) { 4411 auto *Cmp = cast<CmpInst>(V); 4412 Value *LHS = Cmp->getOperand(0); 4413 Value *RHS = Cmp->getOperand(1); 4414 if (Cmp->getPredicate() != P0) 4415 std::swap(LHS, RHS); 4416 Left.push_back(LHS); 4417 Right.push_back(RHS); 4418 } 4419 } 4420 TE->setOperand(0, Left); 4421 TE->setOperand(1, Right); 4422 buildTree_rec(Left, Depth + 1, {TE, 0}); 4423 buildTree_rec(Right, Depth + 1, {TE, 1}); 4424 return; 4425 } 4426 case Instruction::Select: 4427 case Instruction::FNeg: 4428 case Instruction::Add: 4429 case Instruction::FAdd: 4430 case Instruction::Sub: 4431 case Instruction::FSub: 4432 case Instruction::Mul: 4433 case Instruction::FMul: 4434 case Instruction::UDiv: 4435 case Instruction::SDiv: 4436 case Instruction::FDiv: 4437 case Instruction::URem: 4438 case Instruction::SRem: 4439 case Instruction::FRem: 4440 case Instruction::Shl: 4441 case Instruction::LShr: 4442 case Instruction::AShr: 4443 case Instruction::And: 4444 case Instruction::Or: 4445 case Instruction::Xor: { 4446 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4447 ReuseShuffleIndicies); 4448 LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n"); 4449 4450 // Sort operands of the instructions so that each side is more likely to 4451 // have the same opcode. 4452 if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) { 4453 ValueList Left, Right; 4454 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4455 TE->setOperand(0, Left); 4456 TE->setOperand(1, Right); 4457 buildTree_rec(Left, Depth + 1, {TE, 0}); 4458 buildTree_rec(Right, Depth + 1, {TE, 1}); 4459 return; 4460 } 4461 4462 TE->setOperandsInOrder(); 4463 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4464 ValueList Operands; 4465 // Prepare the operand vector. 4466 for (Value *V : VL) 4467 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4468 4469 buildTree_rec(Operands, Depth + 1, {TE, i}); 4470 } 4471 return; 4472 } 4473 case Instruction::GetElementPtr: { 4474 // We don't combine GEPs with complicated (nested) indexing. 4475 for (Value *V : VL) { 4476 if (cast<Instruction>(V)->getNumOperands() != 2) { 4477 LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n"); 4478 BS.cancelScheduling(VL, VL0); 4479 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4480 ReuseShuffleIndicies); 4481 return; 4482 } 4483 } 4484 4485 // We can't combine several GEPs into one vector if they operate on 4486 // different types. 4487 Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType(); 4488 for (Value *V : VL) { 4489 Type *CurTy = cast<GEPOperator>(V)->getSourceElementType(); 4490 if (Ty0 != CurTy) { 4491 LLVM_DEBUG(dbgs() 4492 << "SLP: not-vectorizable GEP (different types).\n"); 4493 BS.cancelScheduling(VL, VL0); 4494 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4495 ReuseShuffleIndicies); 4496 return; 4497 } 4498 } 4499 4500 // We don't combine GEPs with non-constant indexes. 4501 Type *Ty1 = VL0->getOperand(1)->getType(); 4502 for (Value *V : VL) { 4503 auto Op = cast<Instruction>(V)->getOperand(1); 4504 if (!isa<ConstantInt>(Op) || 4505 (Op->getType() != Ty1 && 4506 Op->getType()->getScalarSizeInBits() > 4507 DL->getIndexSizeInBits( 4508 V->getType()->getPointerAddressSpace()))) { 4509 LLVM_DEBUG(dbgs() 4510 << "SLP: not-vectorizable GEP (non-constant indexes).\n"); 4511 BS.cancelScheduling(VL, VL0); 4512 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4513 ReuseShuffleIndicies); 4514 return; 4515 } 4516 } 4517 4518 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4519 ReuseShuffleIndicies); 4520 LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n"); 4521 SmallVector<ValueList, 2> Operands(2); 4522 // Prepare the operand vector for pointer operands. 4523 for (Value *V : VL) 4524 Operands.front().push_back( 4525 cast<GetElementPtrInst>(V)->getPointerOperand()); 4526 TE->setOperand(0, Operands.front()); 4527 // Need to cast all indices to the same type before vectorization to 4528 // avoid crash. 4529 // Required to be able to find correct matches between different gather 4530 // nodes and reuse the vectorized values rather than trying to gather them 4531 // again. 4532 int IndexIdx = 1; 4533 Type *VL0Ty = VL0->getOperand(IndexIdx)->getType(); 4534 Type *Ty = all_of(VL, 4535 [VL0Ty, IndexIdx](Value *V) { 4536 return VL0Ty == cast<GetElementPtrInst>(V) 4537 ->getOperand(IndexIdx) 4538 ->getType(); 4539 }) 4540 ? VL0Ty 4541 : DL->getIndexType(cast<GetElementPtrInst>(VL0) 4542 ->getPointerOperandType() 4543 ->getScalarType()); 4544 // Prepare the operand vector. 4545 for (Value *V : VL) { 4546 auto *Op = cast<Instruction>(V)->getOperand(IndexIdx); 4547 auto *CI = cast<ConstantInt>(Op); 4548 Operands.back().push_back(ConstantExpr::getIntegerCast( 4549 CI, Ty, CI->getValue().isSignBitSet())); 4550 } 4551 TE->setOperand(IndexIdx, Operands.back()); 4552 4553 for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I) 4554 buildTree_rec(Operands[I], Depth + 1, {TE, I}); 4555 return; 4556 } 4557 case Instruction::Store: { 4558 // Check if the stores are consecutive or if we need to swizzle them. 4559 llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType(); 4560 // Avoid types that are padded when being allocated as scalars, while 4561 // being packed together in a vector (such as i1). 4562 if (DL->getTypeSizeInBits(ScalarTy) != 4563 DL->getTypeAllocSizeInBits(ScalarTy)) { 4564 BS.cancelScheduling(VL, VL0); 4565 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4566 ReuseShuffleIndicies); 4567 LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n"); 4568 return; 4569 } 4570 // Make sure all stores in the bundle are simple - we can't vectorize 4571 // atomic or volatile stores. 4572 SmallVector<Value *, 4> PointerOps(VL.size()); 4573 ValueList Operands(VL.size()); 4574 auto POIter = PointerOps.begin(); 4575 auto OIter = Operands.begin(); 4576 for (Value *V : VL) { 4577 auto *SI = cast<StoreInst>(V); 4578 if (!SI->isSimple()) { 4579 BS.cancelScheduling(VL, VL0); 4580 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4581 ReuseShuffleIndicies); 4582 LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n"); 4583 return; 4584 } 4585 *POIter = SI->getPointerOperand(); 4586 *OIter = SI->getValueOperand(); 4587 ++POIter; 4588 ++OIter; 4589 } 4590 4591 OrdersType CurrentOrder; 4592 // Check the order of pointer operands. 4593 if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) { 4594 Value *Ptr0; 4595 Value *PtrN; 4596 if (CurrentOrder.empty()) { 4597 Ptr0 = PointerOps.front(); 4598 PtrN = PointerOps.back(); 4599 } else { 4600 Ptr0 = PointerOps[CurrentOrder.front()]; 4601 PtrN = PointerOps[CurrentOrder.back()]; 4602 } 4603 Optional<int> Dist = 4604 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE); 4605 // Check that the sorted pointer operands are consecutive. 4606 if (static_cast<unsigned>(*Dist) == VL.size() - 1) { 4607 if (CurrentOrder.empty()) { 4608 // Original stores are consecutive and does not require reordering. 4609 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, 4610 UserTreeIdx, ReuseShuffleIndicies); 4611 TE->setOperandsInOrder(); 4612 buildTree_rec(Operands, Depth + 1, {TE, 0}); 4613 LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n"); 4614 } else { 4615 fixupOrderingIndices(CurrentOrder); 4616 TreeEntry *TE = 4617 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4618 ReuseShuffleIndicies, CurrentOrder); 4619 TE->setOperandsInOrder(); 4620 buildTree_rec(Operands, Depth + 1, {TE, 0}); 4621 LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n"); 4622 } 4623 return; 4624 } 4625 } 4626 4627 BS.cancelScheduling(VL, VL0); 4628 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4629 ReuseShuffleIndicies); 4630 LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n"); 4631 return; 4632 } 4633 case Instruction::Call: { 4634 // Check if the calls are all to the same vectorizable intrinsic or 4635 // library function. 4636 CallInst *CI = cast<CallInst>(VL0); 4637 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4638 4639 VFShape Shape = VFShape::get( 4640 *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())), 4641 false /*HasGlobalPred*/); 4642 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 4643 4644 if (!VecFunc && !isTriviallyVectorizable(ID)) { 4645 BS.cancelScheduling(VL, VL0); 4646 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4647 ReuseShuffleIndicies); 4648 LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n"); 4649 return; 4650 } 4651 Function *F = CI->getCalledFunction(); 4652 unsigned NumArgs = CI->arg_size(); 4653 SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr); 4654 for (unsigned j = 0; j != NumArgs; ++j) 4655 if (hasVectorInstrinsicScalarOpd(ID, j)) 4656 ScalarArgs[j] = CI->getArgOperand(j); 4657 for (Value *V : VL) { 4658 CallInst *CI2 = dyn_cast<CallInst>(V); 4659 if (!CI2 || CI2->getCalledFunction() != F || 4660 getVectorIntrinsicIDForCall(CI2, TLI) != ID || 4661 (VecFunc && 4662 VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) || 4663 !CI->hasIdenticalOperandBundleSchema(*CI2)) { 4664 BS.cancelScheduling(VL, VL0); 4665 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4666 ReuseShuffleIndicies); 4667 LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V 4668 << "\n"); 4669 return; 4670 } 4671 // Some intrinsics have scalar arguments and should be same in order for 4672 // them to be vectorized. 4673 for (unsigned j = 0; j != NumArgs; ++j) { 4674 if (hasVectorInstrinsicScalarOpd(ID, j)) { 4675 Value *A1J = CI2->getArgOperand(j); 4676 if (ScalarArgs[j] != A1J) { 4677 BS.cancelScheduling(VL, VL0); 4678 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4679 ReuseShuffleIndicies); 4680 LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI 4681 << " argument " << ScalarArgs[j] << "!=" << A1J 4682 << "\n"); 4683 return; 4684 } 4685 } 4686 } 4687 // Verify that the bundle operands are identical between the two calls. 4688 if (CI->hasOperandBundles() && 4689 !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(), 4690 CI->op_begin() + CI->getBundleOperandsEndIndex(), 4691 CI2->op_begin() + CI2->getBundleOperandsStartIndex())) { 4692 BS.cancelScheduling(VL, VL0); 4693 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4694 ReuseShuffleIndicies); 4695 LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:" 4696 << *CI << "!=" << *V << '\n'); 4697 return; 4698 } 4699 } 4700 4701 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4702 ReuseShuffleIndicies); 4703 TE->setOperandsInOrder(); 4704 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) { 4705 // For scalar operands no need to to create an entry since no need to 4706 // vectorize it. 4707 if (hasVectorInstrinsicScalarOpd(ID, i)) 4708 continue; 4709 ValueList Operands; 4710 // Prepare the operand vector. 4711 for (Value *V : VL) { 4712 auto *CI2 = cast<CallInst>(V); 4713 Operands.push_back(CI2->getArgOperand(i)); 4714 } 4715 buildTree_rec(Operands, Depth + 1, {TE, i}); 4716 } 4717 return; 4718 } 4719 case Instruction::ShuffleVector: { 4720 // If this is not an alternate sequence of opcode like add-sub 4721 // then do not vectorize this instruction. 4722 if (!S.isAltShuffle()) { 4723 BS.cancelScheduling(VL, VL0); 4724 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4725 ReuseShuffleIndicies); 4726 LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n"); 4727 return; 4728 } 4729 TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx, 4730 ReuseShuffleIndicies); 4731 LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n"); 4732 4733 // Reorder operands if reordering would enable vectorization. 4734 auto *CI = dyn_cast<CmpInst>(VL0); 4735 if (isa<BinaryOperator>(VL0) || CI) { 4736 ValueList Left, Right; 4737 if (!CI || all_of(VL, [](Value *V) { 4738 return cast<CmpInst>(V)->isCommutative(); 4739 })) { 4740 reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this); 4741 } else { 4742 CmpInst::Predicate P0 = CI->getPredicate(); 4743 CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate(); 4744 assert(P0 != AltP0 && 4745 "Expected different main/alternate predicates."); 4746 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 4747 Value *BaseOp0 = VL0->getOperand(0); 4748 Value *BaseOp1 = VL0->getOperand(1); 4749 // Collect operands - commute if it uses the swapped predicate or 4750 // alternate operation. 4751 for (Value *V : VL) { 4752 auto *Cmp = cast<CmpInst>(V); 4753 Value *LHS = Cmp->getOperand(0); 4754 Value *RHS = Cmp->getOperand(1); 4755 CmpInst::Predicate CurrentPred = Cmp->getPredicate(); 4756 if (P0 == AltP0Swapped) { 4757 if (CI != Cmp && S.AltOp != Cmp && 4758 ((P0 == CurrentPred && 4759 !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) || 4760 (AltP0 == CurrentPred && 4761 areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)))) 4762 std::swap(LHS, RHS); 4763 } else if (P0 != CurrentPred && AltP0 != CurrentPred) { 4764 std::swap(LHS, RHS); 4765 } 4766 Left.push_back(LHS); 4767 Right.push_back(RHS); 4768 } 4769 } 4770 TE->setOperand(0, Left); 4771 TE->setOperand(1, Right); 4772 buildTree_rec(Left, Depth + 1, {TE, 0}); 4773 buildTree_rec(Right, Depth + 1, {TE, 1}); 4774 return; 4775 } 4776 4777 TE->setOperandsInOrder(); 4778 for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) { 4779 ValueList Operands; 4780 // Prepare the operand vector. 4781 for (Value *V : VL) 4782 Operands.push_back(cast<Instruction>(V)->getOperand(i)); 4783 4784 buildTree_rec(Operands, Depth + 1, {TE, i}); 4785 } 4786 return; 4787 } 4788 default: 4789 BS.cancelScheduling(VL, VL0); 4790 newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx, 4791 ReuseShuffleIndicies); 4792 LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n"); 4793 return; 4794 } 4795 } 4796 4797 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const { 4798 unsigned N = 1; 4799 Type *EltTy = T; 4800 4801 while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) || 4802 isa<VectorType>(EltTy)) { 4803 if (auto *ST = dyn_cast<StructType>(EltTy)) { 4804 // Check that struct is homogeneous. 4805 for (const auto *Ty : ST->elements()) 4806 if (Ty != *ST->element_begin()) 4807 return 0; 4808 N *= ST->getNumElements(); 4809 EltTy = *ST->element_begin(); 4810 } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) { 4811 N *= AT->getNumElements(); 4812 EltTy = AT->getElementType(); 4813 } else { 4814 auto *VT = cast<FixedVectorType>(EltTy); 4815 N *= VT->getNumElements(); 4816 EltTy = VT->getElementType(); 4817 } 4818 } 4819 4820 if (!isValidElementType(EltTy)) 4821 return 0; 4822 uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N)); 4823 if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T)) 4824 return 0; 4825 return N; 4826 } 4827 4828 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue, 4829 SmallVectorImpl<unsigned> &CurrentOrder) const { 4830 const auto *It = find_if(VL, [](Value *V) { 4831 return isa<ExtractElementInst, ExtractValueInst>(V); 4832 }); 4833 assert(It != VL.end() && "Expected at least one extract instruction."); 4834 auto *E0 = cast<Instruction>(*It); 4835 assert(all_of(VL, 4836 [](Value *V) { 4837 return isa<UndefValue, ExtractElementInst, ExtractValueInst>( 4838 V); 4839 }) && 4840 "Invalid opcode"); 4841 // Check if all of the extracts come from the same vector and from the 4842 // correct offset. 4843 Value *Vec = E0->getOperand(0); 4844 4845 CurrentOrder.clear(); 4846 4847 // We have to extract from a vector/aggregate with the same number of elements. 4848 unsigned NElts; 4849 if (E0->getOpcode() == Instruction::ExtractValue) { 4850 const DataLayout &DL = E0->getModule()->getDataLayout(); 4851 NElts = canMapToVector(Vec->getType(), DL); 4852 if (!NElts) 4853 return false; 4854 // Check if load can be rewritten as load of vector. 4855 LoadInst *LI = dyn_cast<LoadInst>(Vec); 4856 if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size())) 4857 return false; 4858 } else { 4859 NElts = cast<FixedVectorType>(Vec->getType())->getNumElements(); 4860 } 4861 4862 if (NElts != VL.size()) 4863 return false; 4864 4865 // Check that all of the indices extract from the correct offset. 4866 bool ShouldKeepOrder = true; 4867 unsigned E = VL.size(); 4868 // Assign to all items the initial value E + 1 so we can check if the extract 4869 // instruction index was used already. 4870 // Also, later we can check that all the indices are used and we have a 4871 // consecutive access in the extract instructions, by checking that no 4872 // element of CurrentOrder still has value E + 1. 4873 CurrentOrder.assign(E, E); 4874 unsigned I = 0; 4875 for (; I < E; ++I) { 4876 auto *Inst = dyn_cast<Instruction>(VL[I]); 4877 if (!Inst) 4878 continue; 4879 if (Inst->getOperand(0) != Vec) 4880 break; 4881 if (auto *EE = dyn_cast<ExtractElementInst>(Inst)) 4882 if (isa<UndefValue>(EE->getIndexOperand())) 4883 continue; 4884 Optional<unsigned> Idx = getExtractIndex(Inst); 4885 if (!Idx) 4886 break; 4887 const unsigned ExtIdx = *Idx; 4888 if (ExtIdx != I) { 4889 if (ExtIdx >= E || CurrentOrder[ExtIdx] != E) 4890 break; 4891 ShouldKeepOrder = false; 4892 CurrentOrder[ExtIdx] = I; 4893 } else { 4894 if (CurrentOrder[I] != E) 4895 break; 4896 CurrentOrder[I] = I; 4897 } 4898 } 4899 if (I < E) { 4900 CurrentOrder.clear(); 4901 return false; 4902 } 4903 if (ShouldKeepOrder) 4904 CurrentOrder.clear(); 4905 4906 return ShouldKeepOrder; 4907 } 4908 4909 bool BoUpSLP::areAllUsersVectorized(Instruction *I, 4910 ArrayRef<Value *> VectorizedVals) const { 4911 return (I->hasOneUse() && is_contained(VectorizedVals, I)) || 4912 all_of(I->users(), [this](User *U) { 4913 return ScalarToTreeEntry.count(U) > 0 || 4914 isVectorLikeInstWithConstOps(U) || 4915 (isa<ExtractElementInst>(U) && MustGather.contains(U)); 4916 }); 4917 } 4918 4919 static std::pair<InstructionCost, InstructionCost> 4920 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy, 4921 TargetTransformInfo *TTI, TargetLibraryInfo *TLI) { 4922 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 4923 4924 // Calculate the cost of the scalar and vector calls. 4925 SmallVector<Type *, 4> VecTys; 4926 for (Use &Arg : CI->args()) 4927 VecTys.push_back( 4928 FixedVectorType::get(Arg->getType(), VecTy->getNumElements())); 4929 FastMathFlags FMF; 4930 if (auto *FPCI = dyn_cast<FPMathOperator>(CI)) 4931 FMF = FPCI->getFastMathFlags(); 4932 SmallVector<const Value *> Arguments(CI->args()); 4933 IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF, 4934 dyn_cast<IntrinsicInst>(CI)); 4935 auto IntrinsicCost = 4936 TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput); 4937 4938 auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 4939 VecTy->getNumElements())), 4940 false /*HasGlobalPred*/); 4941 Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape); 4942 auto LibCost = IntrinsicCost; 4943 if (!CI->isNoBuiltin() && VecFunc) { 4944 // Calculate the cost of the vector library call. 4945 // If the corresponding vector call is cheaper, return its cost. 4946 LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys, 4947 TTI::TCK_RecipThroughput); 4948 } 4949 return {IntrinsicCost, LibCost}; 4950 } 4951 4952 /// Compute the cost of creating a vector of type \p VecTy containing the 4953 /// extracted values from \p VL. 4954 static InstructionCost 4955 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy, 4956 TargetTransformInfo::ShuffleKind ShuffleKind, 4957 ArrayRef<int> Mask, TargetTransformInfo &TTI) { 4958 unsigned NumOfParts = TTI.getNumberOfParts(VecTy); 4959 4960 if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts || 4961 VecTy->getNumElements() < NumOfParts) 4962 return TTI.getShuffleCost(ShuffleKind, VecTy, Mask); 4963 4964 bool AllConsecutive = true; 4965 unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts; 4966 unsigned Idx = -1; 4967 InstructionCost Cost = 0; 4968 4969 // Process extracts in blocks of EltsPerVector to check if the source vector 4970 // operand can be re-used directly. If not, add the cost of creating a shuffle 4971 // to extract the values into a vector register. 4972 for (auto *V : VL) { 4973 ++Idx; 4974 4975 // Need to exclude undefs from analysis. 4976 if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem) 4977 continue; 4978 4979 // Reached the start of a new vector registers. 4980 if (Idx % EltsPerVector == 0) { 4981 AllConsecutive = true; 4982 continue; 4983 } 4984 4985 // Check all extracts for a vector register on the target directly 4986 // extract values in order. 4987 unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V)); 4988 if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) { 4989 unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1])); 4990 AllConsecutive &= PrevIdx + 1 == CurrentIdx && 4991 CurrentIdx % EltsPerVector == Idx % EltsPerVector; 4992 } 4993 4994 if (AllConsecutive) 4995 continue; 4996 4997 // Skip all indices, except for the last index per vector block. 4998 if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size()) 4999 continue; 5000 5001 // If we have a series of extracts which are not consecutive and hence 5002 // cannot re-use the source vector register directly, compute the shuffle 5003 // cost to extract the a vector with EltsPerVector elements. 5004 Cost += TTI.getShuffleCost( 5005 TargetTransformInfo::SK_PermuteSingleSrc, 5006 FixedVectorType::get(VecTy->getElementType(), EltsPerVector)); 5007 } 5008 return Cost; 5009 } 5010 5011 /// Build shuffle mask for shuffle graph entries and lists of main and alternate 5012 /// operations operands. 5013 static void 5014 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices, 5015 ArrayRef<int> ReusesIndices, 5016 const function_ref<bool(Instruction *)> IsAltOp, 5017 SmallVectorImpl<int> &Mask, 5018 SmallVectorImpl<Value *> *OpScalars = nullptr, 5019 SmallVectorImpl<Value *> *AltScalars = nullptr) { 5020 unsigned Sz = VL.size(); 5021 Mask.assign(Sz, UndefMaskElem); 5022 SmallVector<int> OrderMask; 5023 if (!ReorderIndices.empty()) 5024 inversePermutation(ReorderIndices, OrderMask); 5025 for (unsigned I = 0; I < Sz; ++I) { 5026 unsigned Idx = I; 5027 if (!ReorderIndices.empty()) 5028 Idx = OrderMask[I]; 5029 auto *OpInst = cast<Instruction>(VL[Idx]); 5030 if (IsAltOp(OpInst)) { 5031 Mask[I] = Sz + Idx; 5032 if (AltScalars) 5033 AltScalars->push_back(OpInst); 5034 } else { 5035 Mask[I] = Idx; 5036 if (OpScalars) 5037 OpScalars->push_back(OpInst); 5038 } 5039 } 5040 if (!ReusesIndices.empty()) { 5041 SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem); 5042 transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) { 5043 return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem; 5044 }); 5045 Mask.swap(NewMask); 5046 } 5047 } 5048 5049 /// Checks if the specified instruction \p I is an alternate operation for the 5050 /// given \p MainOp and \p AltOp instructions. 5051 static bool isAlternateInstruction(const Instruction *I, 5052 const Instruction *MainOp, 5053 const Instruction *AltOp) { 5054 if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) { 5055 auto *AltCI0 = cast<CmpInst>(AltOp); 5056 auto *CI = cast<CmpInst>(I); 5057 CmpInst::Predicate P0 = CI0->getPredicate(); 5058 CmpInst::Predicate AltP0 = AltCI0->getPredicate(); 5059 assert(P0 != AltP0 && "Expected different main/alternate predicates."); 5060 CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0); 5061 CmpInst::Predicate CurrentPred = CI->getPredicate(); 5062 if (P0 == AltP0Swapped) 5063 return I == AltCI0 || 5064 (I != MainOp && 5065 !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1), 5066 CI->getOperand(0), CI->getOperand(1))); 5067 return AltP0 == CurrentPred || AltP0Swapped == CurrentPred; 5068 } 5069 return I->getOpcode() == AltOp->getOpcode(); 5070 } 5071 5072 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E, 5073 ArrayRef<Value *> VectorizedVals) { 5074 ArrayRef<Value*> VL = E->Scalars; 5075 5076 Type *ScalarTy = VL[0]->getType(); 5077 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 5078 ScalarTy = SI->getValueOperand()->getType(); 5079 else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0])) 5080 ScalarTy = CI->getOperand(0)->getType(); 5081 else if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 5082 ScalarTy = IE->getOperand(1)->getType(); 5083 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 5084 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 5085 5086 // If we have computed a smaller type for the expression, update VecTy so 5087 // that the costs will be accurate. 5088 if (MinBWs.count(VL[0])) 5089 VecTy = FixedVectorType::get( 5090 IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size()); 5091 unsigned EntryVF = E->getVectorFactor(); 5092 auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF); 5093 5094 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 5095 // FIXME: it tries to fix a problem with MSVC buildbots. 5096 TargetTransformInfo &TTIRef = *TTI; 5097 auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy, 5098 VectorizedVals, E](InstructionCost &Cost) { 5099 DenseMap<Value *, int> ExtractVectorsTys; 5100 SmallPtrSet<Value *, 4> CheckedExtracts; 5101 for (auto *V : VL) { 5102 if (isa<UndefValue>(V)) 5103 continue; 5104 // If all users of instruction are going to be vectorized and this 5105 // instruction itself is not going to be vectorized, consider this 5106 // instruction as dead and remove its cost from the final cost of the 5107 // vectorized tree. 5108 // Also, avoid adjusting the cost for extractelements with multiple uses 5109 // in different graph entries. 5110 const TreeEntry *VE = getTreeEntry(V); 5111 if (!CheckedExtracts.insert(V).second || 5112 !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) || 5113 (VE && VE != E)) 5114 continue; 5115 auto *EE = cast<ExtractElementInst>(V); 5116 Optional<unsigned> EEIdx = getExtractIndex(EE); 5117 if (!EEIdx) 5118 continue; 5119 unsigned Idx = *EEIdx; 5120 if (TTIRef.getNumberOfParts(VecTy) != 5121 TTIRef.getNumberOfParts(EE->getVectorOperandType())) { 5122 auto It = 5123 ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first; 5124 It->getSecond() = std::min<int>(It->second, Idx); 5125 } 5126 // Take credit for instruction that will become dead. 5127 if (EE->hasOneUse()) { 5128 Instruction *Ext = EE->user_back(); 5129 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 5130 all_of(Ext->users(), 5131 [](User *U) { return isa<GetElementPtrInst>(U); })) { 5132 // Use getExtractWithExtendCost() to calculate the cost of 5133 // extractelement/ext pair. 5134 Cost -= 5135 TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(), 5136 EE->getVectorOperandType(), Idx); 5137 // Add back the cost of s|zext which is subtracted separately. 5138 Cost += TTIRef.getCastInstrCost( 5139 Ext->getOpcode(), Ext->getType(), EE->getType(), 5140 TTI::getCastContextHint(Ext), CostKind, Ext); 5141 continue; 5142 } 5143 } 5144 Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement, 5145 EE->getVectorOperandType(), Idx); 5146 } 5147 // Add a cost for subvector extracts/inserts if required. 5148 for (const auto &Data : ExtractVectorsTys) { 5149 auto *EEVTy = cast<FixedVectorType>(Data.first->getType()); 5150 unsigned NumElts = VecTy->getNumElements(); 5151 if (Data.second % NumElts == 0) 5152 continue; 5153 if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) { 5154 unsigned Idx = (Data.second / NumElts) * NumElts; 5155 unsigned EENumElts = EEVTy->getNumElements(); 5156 if (Idx + NumElts <= EENumElts) { 5157 Cost += 5158 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 5159 EEVTy, None, Idx, VecTy); 5160 } else { 5161 // Need to round up the subvector type vectorization factor to avoid a 5162 // crash in cost model functions. Make SubVT so that Idx + VF of SubVT 5163 // <= EENumElts. 5164 auto *SubVT = 5165 FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx); 5166 Cost += 5167 TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector, 5168 EEVTy, None, Idx, SubVT); 5169 } 5170 } else { 5171 Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector, 5172 VecTy, None, 0, EEVTy); 5173 } 5174 } 5175 }; 5176 if (E->State == TreeEntry::NeedToGather) { 5177 if (allConstant(VL)) 5178 return 0; 5179 if (isa<InsertElementInst>(VL[0])) 5180 return InstructionCost::getInvalid(); 5181 SmallVector<int> Mask; 5182 SmallVector<const TreeEntry *> Entries; 5183 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 5184 isGatherShuffledEntry(E, Mask, Entries); 5185 if (Shuffle.hasValue()) { 5186 InstructionCost GatherCost = 0; 5187 if (ShuffleVectorInst::isIdentityMask(Mask)) { 5188 // Perfect match in the graph, will reuse the previously vectorized 5189 // node. Cost is 0. 5190 LLVM_DEBUG( 5191 dbgs() 5192 << "SLP: perfect diamond match for gather bundle that starts with " 5193 << *VL.front() << ".\n"); 5194 if (NeedToShuffleReuses) 5195 GatherCost = 5196 TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 5197 FinalVecTy, E->ReuseShuffleIndices); 5198 } else { 5199 LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size() 5200 << " entries for bundle that starts with " 5201 << *VL.front() << ".\n"); 5202 // Detected that instead of gather we can emit a shuffle of single/two 5203 // previously vectorized nodes. Add the cost of the permutation rather 5204 // than gather. 5205 ::addMask(Mask, E->ReuseShuffleIndices); 5206 GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask); 5207 } 5208 return GatherCost; 5209 } 5210 if ((E->getOpcode() == Instruction::ExtractElement || 5211 all_of(E->Scalars, 5212 [](Value *V) { 5213 return isa<ExtractElementInst, UndefValue>(V); 5214 })) && 5215 allSameType(VL)) { 5216 // Check that gather of extractelements can be represented as just a 5217 // shuffle of a single/two vectors the scalars are extracted from. 5218 SmallVector<int> Mask; 5219 Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = 5220 isFixedVectorShuffle(VL, Mask); 5221 if (ShuffleKind.hasValue()) { 5222 // Found the bunch of extractelement instructions that must be gathered 5223 // into a vector and can be represented as a permutation elements in a 5224 // single input vector or of 2 input vectors. 5225 InstructionCost Cost = 5226 computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI); 5227 AdjustExtractsCost(Cost); 5228 if (NeedToShuffleReuses) 5229 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, 5230 FinalVecTy, E->ReuseShuffleIndices); 5231 return Cost; 5232 } 5233 } 5234 if (isSplat(VL)) { 5235 // Found the broadcasting of the single scalar, calculate the cost as the 5236 // broadcast. 5237 assert(VecTy == FinalVecTy && 5238 "No reused scalars expected for broadcast."); 5239 return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy); 5240 } 5241 InstructionCost ReuseShuffleCost = 0; 5242 if (NeedToShuffleReuses) 5243 ReuseShuffleCost = TTI->getShuffleCost( 5244 TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices); 5245 // Improve gather cost for gather of loads, if we can group some of the 5246 // loads into vector loads. 5247 if (VL.size() > 2 && E->getOpcode() == Instruction::Load && 5248 !E->isAltShuffle()) { 5249 BoUpSLP::ValueSet VectorizedLoads; 5250 unsigned StartIdx = 0; 5251 unsigned VF = VL.size() / 2; 5252 unsigned VectorizedCnt = 0; 5253 unsigned ScatterVectorizeCnt = 0; 5254 const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType()); 5255 for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) { 5256 for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End; 5257 Cnt += VF) { 5258 ArrayRef<Value *> Slice = VL.slice(Cnt, VF); 5259 if (!VectorizedLoads.count(Slice.front()) && 5260 !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) { 5261 SmallVector<Value *> PointerOps; 5262 OrdersType CurrentOrder; 5263 LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL, 5264 *SE, CurrentOrder, PointerOps); 5265 switch (LS) { 5266 case LoadsState::Vectorize: 5267 case LoadsState::ScatterVectorize: 5268 // Mark the vectorized loads so that we don't vectorize them 5269 // again. 5270 if (LS == LoadsState::Vectorize) 5271 ++VectorizedCnt; 5272 else 5273 ++ScatterVectorizeCnt; 5274 VectorizedLoads.insert(Slice.begin(), Slice.end()); 5275 // If we vectorized initial block, no need to try to vectorize it 5276 // again. 5277 if (Cnt == StartIdx) 5278 StartIdx += VF; 5279 break; 5280 case LoadsState::Gather: 5281 break; 5282 } 5283 } 5284 } 5285 // Check if the whole array was vectorized already - exit. 5286 if (StartIdx >= VL.size()) 5287 break; 5288 // Found vectorizable parts - exit. 5289 if (!VectorizedLoads.empty()) 5290 break; 5291 } 5292 if (!VectorizedLoads.empty()) { 5293 InstructionCost GatherCost = 0; 5294 unsigned NumParts = TTI->getNumberOfParts(VecTy); 5295 bool NeedInsertSubvectorAnalysis = 5296 !NumParts || (VL.size() / VF) > NumParts; 5297 // Get the cost for gathered loads. 5298 for (unsigned I = 0, End = VL.size(); I < End; I += VF) { 5299 if (VectorizedLoads.contains(VL[I])) 5300 continue; 5301 GatherCost += getGatherCost(VL.slice(I, VF)); 5302 } 5303 // The cost for vectorized loads. 5304 InstructionCost ScalarsCost = 0; 5305 for (Value *V : VectorizedLoads) { 5306 auto *LI = cast<LoadInst>(V); 5307 ScalarsCost += TTI->getMemoryOpCost( 5308 Instruction::Load, LI->getType(), LI->getAlign(), 5309 LI->getPointerAddressSpace(), CostKind, LI); 5310 } 5311 auto *LI = cast<LoadInst>(E->getMainOp()); 5312 auto *LoadTy = FixedVectorType::get(LI->getType(), VF); 5313 Align Alignment = LI->getAlign(); 5314 GatherCost += 5315 VectorizedCnt * 5316 TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment, 5317 LI->getPointerAddressSpace(), CostKind, LI); 5318 GatherCost += ScatterVectorizeCnt * 5319 TTI->getGatherScatterOpCost( 5320 Instruction::Load, LoadTy, LI->getPointerOperand(), 5321 /*VariableMask=*/false, Alignment, CostKind, LI); 5322 if (NeedInsertSubvectorAnalysis) { 5323 // Add the cost for the subvectors insert. 5324 for (int I = VF, E = VL.size(); I < E; I += VF) 5325 GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy, 5326 None, I, LoadTy); 5327 } 5328 return ReuseShuffleCost + GatherCost - ScalarsCost; 5329 } 5330 } 5331 return ReuseShuffleCost + getGatherCost(VL); 5332 } 5333 InstructionCost CommonCost = 0; 5334 SmallVector<int> Mask; 5335 if (!E->ReorderIndices.empty()) { 5336 SmallVector<int> NewMask; 5337 if (E->getOpcode() == Instruction::Store) { 5338 // For stores the order is actually a mask. 5339 NewMask.resize(E->ReorderIndices.size()); 5340 copy(E->ReorderIndices, NewMask.begin()); 5341 } else { 5342 inversePermutation(E->ReorderIndices, NewMask); 5343 } 5344 ::addMask(Mask, NewMask); 5345 } 5346 if (NeedToShuffleReuses) 5347 ::addMask(Mask, E->ReuseShuffleIndices); 5348 if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask)) 5349 CommonCost = 5350 TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask); 5351 assert((E->State == TreeEntry::Vectorize || 5352 E->State == TreeEntry::ScatterVectorize) && 5353 "Unhandled state"); 5354 assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL"); 5355 Instruction *VL0 = E->getMainOp(); 5356 unsigned ShuffleOrOp = 5357 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 5358 switch (ShuffleOrOp) { 5359 case Instruction::PHI: 5360 return 0; 5361 5362 case Instruction::ExtractValue: 5363 case Instruction::ExtractElement: { 5364 // The common cost of removal ExtractElement/ExtractValue instructions + 5365 // the cost of shuffles, if required to resuffle the original vector. 5366 if (NeedToShuffleReuses) { 5367 unsigned Idx = 0; 5368 for (unsigned I : E->ReuseShuffleIndices) { 5369 if (ShuffleOrOp == Instruction::ExtractElement) { 5370 auto *EE = cast<ExtractElementInst>(VL[I]); 5371 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 5372 EE->getVectorOperandType(), 5373 *getExtractIndex(EE)); 5374 } else { 5375 CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement, 5376 VecTy, Idx); 5377 ++Idx; 5378 } 5379 } 5380 Idx = EntryVF; 5381 for (Value *V : VL) { 5382 if (ShuffleOrOp == Instruction::ExtractElement) { 5383 auto *EE = cast<ExtractElementInst>(V); 5384 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 5385 EE->getVectorOperandType(), 5386 *getExtractIndex(EE)); 5387 } else { 5388 --Idx; 5389 CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement, 5390 VecTy, Idx); 5391 } 5392 } 5393 } 5394 if (ShuffleOrOp == Instruction::ExtractValue) { 5395 for (unsigned I = 0, E = VL.size(); I < E; ++I) { 5396 auto *EI = cast<Instruction>(VL[I]); 5397 // Take credit for instruction that will become dead. 5398 if (EI->hasOneUse()) { 5399 Instruction *Ext = EI->user_back(); 5400 if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) && 5401 all_of(Ext->users(), 5402 [](User *U) { return isa<GetElementPtrInst>(U); })) { 5403 // Use getExtractWithExtendCost() to calculate the cost of 5404 // extractelement/ext pair. 5405 CommonCost -= TTI->getExtractWithExtendCost( 5406 Ext->getOpcode(), Ext->getType(), VecTy, I); 5407 // Add back the cost of s|zext which is subtracted separately. 5408 CommonCost += TTI->getCastInstrCost( 5409 Ext->getOpcode(), Ext->getType(), EI->getType(), 5410 TTI::getCastContextHint(Ext), CostKind, Ext); 5411 continue; 5412 } 5413 } 5414 CommonCost -= 5415 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I); 5416 } 5417 } else { 5418 AdjustExtractsCost(CommonCost); 5419 } 5420 return CommonCost; 5421 } 5422 case Instruction::InsertElement: { 5423 assert(E->ReuseShuffleIndices.empty() && 5424 "Unique insertelements only are expected."); 5425 auto *SrcVecTy = cast<FixedVectorType>(VL0->getType()); 5426 5427 unsigned const NumElts = SrcVecTy->getNumElements(); 5428 unsigned const NumScalars = VL.size(); 5429 APInt DemandedElts = APInt::getZero(NumElts); 5430 // TODO: Add support for Instruction::InsertValue. 5431 SmallVector<int> Mask; 5432 if (!E->ReorderIndices.empty()) { 5433 inversePermutation(E->ReorderIndices, Mask); 5434 Mask.append(NumElts - NumScalars, UndefMaskElem); 5435 } else { 5436 Mask.assign(NumElts, UndefMaskElem); 5437 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 5438 } 5439 unsigned Offset = *getInsertIndex(VL0); 5440 bool IsIdentity = true; 5441 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 5442 Mask.swap(PrevMask); 5443 for (unsigned I = 0; I < NumScalars; ++I) { 5444 unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]); 5445 DemandedElts.setBit(InsertIdx); 5446 IsIdentity &= InsertIdx - Offset == I; 5447 Mask[InsertIdx - Offset] = I; 5448 } 5449 assert(Offset < NumElts && "Failed to find vector index offset"); 5450 5451 InstructionCost Cost = 0; 5452 Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts, 5453 /*Insert*/ true, /*Extract*/ false); 5454 5455 if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) { 5456 // FIXME: Replace with SK_InsertSubvector once it is properly supported. 5457 unsigned Sz = PowerOf2Ceil(Offset + NumScalars); 5458 Cost += TTI->getShuffleCost( 5459 TargetTransformInfo::SK_PermuteSingleSrc, 5460 FixedVectorType::get(SrcVecTy->getElementType(), Sz)); 5461 } else if (!IsIdentity) { 5462 auto *FirstInsert = 5463 cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 5464 return !is_contained(E->Scalars, 5465 cast<Instruction>(V)->getOperand(0)); 5466 })); 5467 if (isUndefVector(FirstInsert->getOperand(0))) { 5468 Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask); 5469 } else { 5470 SmallVector<int> InsertMask(NumElts); 5471 std::iota(InsertMask.begin(), InsertMask.end(), 0); 5472 for (unsigned I = 0; I < NumElts; I++) { 5473 if (Mask[I] != UndefMaskElem) 5474 InsertMask[Offset + I] = NumElts + I; 5475 } 5476 Cost += 5477 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask); 5478 } 5479 } 5480 5481 return Cost; 5482 } 5483 case Instruction::ZExt: 5484 case Instruction::SExt: 5485 case Instruction::FPToUI: 5486 case Instruction::FPToSI: 5487 case Instruction::FPExt: 5488 case Instruction::PtrToInt: 5489 case Instruction::IntToPtr: 5490 case Instruction::SIToFP: 5491 case Instruction::UIToFP: 5492 case Instruction::Trunc: 5493 case Instruction::FPTrunc: 5494 case Instruction::BitCast: { 5495 Type *SrcTy = VL0->getOperand(0)->getType(); 5496 InstructionCost ScalarEltCost = 5497 TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy, 5498 TTI::getCastContextHint(VL0), CostKind, VL0); 5499 if (NeedToShuffleReuses) { 5500 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5501 } 5502 5503 // Calculate the cost of this instruction. 5504 InstructionCost ScalarCost = VL.size() * ScalarEltCost; 5505 5506 auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size()); 5507 InstructionCost VecCost = 0; 5508 // Check if the values are candidates to demote. 5509 if (!MinBWs.count(VL0) || VecTy != SrcVecTy) { 5510 VecCost = CommonCost + TTI->getCastInstrCost( 5511 E->getOpcode(), VecTy, SrcVecTy, 5512 TTI::getCastContextHint(VL0), CostKind, VL0); 5513 } 5514 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5515 return VecCost - ScalarCost; 5516 } 5517 case Instruction::FCmp: 5518 case Instruction::ICmp: 5519 case Instruction::Select: { 5520 // Calculate the cost of this instruction. 5521 InstructionCost ScalarEltCost = 5522 TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 5523 CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0); 5524 if (NeedToShuffleReuses) { 5525 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5526 } 5527 auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size()); 5528 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5529 5530 // Check if all entries in VL are either compares or selects with compares 5531 // as condition that have the same predicates. 5532 CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE; 5533 bool First = true; 5534 for (auto *V : VL) { 5535 CmpInst::Predicate CurrentPred; 5536 auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value()); 5537 if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) && 5538 !match(V, MatchCmp)) || 5539 (!First && VecPred != CurrentPred)) { 5540 VecPred = CmpInst::BAD_ICMP_PREDICATE; 5541 break; 5542 } 5543 First = false; 5544 VecPred = CurrentPred; 5545 } 5546 5547 InstructionCost VecCost = TTI->getCmpSelInstrCost( 5548 E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0); 5549 // Check if it is possible and profitable to use min/max for selects in 5550 // VL. 5551 // 5552 auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL); 5553 if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) { 5554 IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy, 5555 {VecTy, VecTy}); 5556 InstructionCost IntrinsicCost = 5557 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 5558 // If the selects are the only uses of the compares, they will be dead 5559 // and we can adjust the cost by removing their cost. 5560 if (IntrinsicAndUse.second) 5561 IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, 5562 MaskTy, VecPred, CostKind); 5563 VecCost = std::min(VecCost, IntrinsicCost); 5564 } 5565 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5566 return CommonCost + VecCost - ScalarCost; 5567 } 5568 case Instruction::FNeg: 5569 case Instruction::Add: 5570 case Instruction::FAdd: 5571 case Instruction::Sub: 5572 case Instruction::FSub: 5573 case Instruction::Mul: 5574 case Instruction::FMul: 5575 case Instruction::UDiv: 5576 case Instruction::SDiv: 5577 case Instruction::FDiv: 5578 case Instruction::URem: 5579 case Instruction::SRem: 5580 case Instruction::FRem: 5581 case Instruction::Shl: 5582 case Instruction::LShr: 5583 case Instruction::AShr: 5584 case Instruction::And: 5585 case Instruction::Or: 5586 case Instruction::Xor: { 5587 // Certain instructions can be cheaper to vectorize if they have a 5588 // constant second vector operand. 5589 TargetTransformInfo::OperandValueKind Op1VK = 5590 TargetTransformInfo::OK_AnyValue; 5591 TargetTransformInfo::OperandValueKind Op2VK = 5592 TargetTransformInfo::OK_UniformConstantValue; 5593 TargetTransformInfo::OperandValueProperties Op1VP = 5594 TargetTransformInfo::OP_None; 5595 TargetTransformInfo::OperandValueProperties Op2VP = 5596 TargetTransformInfo::OP_PowerOf2; 5597 5598 // If all operands are exactly the same ConstantInt then set the 5599 // operand kind to OK_UniformConstantValue. 5600 // If instead not all operands are constants, then set the operand kind 5601 // to OK_AnyValue. If all operands are constants but not the same, 5602 // then set the operand kind to OK_NonUniformConstantValue. 5603 ConstantInt *CInt0 = nullptr; 5604 for (unsigned i = 0, e = VL.size(); i < e; ++i) { 5605 const Instruction *I = cast<Instruction>(VL[i]); 5606 unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0; 5607 ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx)); 5608 if (!CInt) { 5609 Op2VK = TargetTransformInfo::OK_AnyValue; 5610 Op2VP = TargetTransformInfo::OP_None; 5611 break; 5612 } 5613 if (Op2VP == TargetTransformInfo::OP_PowerOf2 && 5614 !CInt->getValue().isPowerOf2()) 5615 Op2VP = TargetTransformInfo::OP_None; 5616 if (i == 0) { 5617 CInt0 = CInt; 5618 continue; 5619 } 5620 if (CInt0 != CInt) 5621 Op2VK = TargetTransformInfo::OK_NonUniformConstantValue; 5622 } 5623 5624 SmallVector<const Value *, 4> Operands(VL0->operand_values()); 5625 InstructionCost ScalarEltCost = 5626 TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK, 5627 Op2VK, Op1VP, Op2VP, Operands, VL0); 5628 if (NeedToShuffleReuses) { 5629 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5630 } 5631 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5632 InstructionCost VecCost = 5633 TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK, 5634 Op2VK, Op1VP, Op2VP, Operands, VL0); 5635 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5636 return CommonCost + VecCost - ScalarCost; 5637 } 5638 case Instruction::GetElementPtr: { 5639 TargetTransformInfo::OperandValueKind Op1VK = 5640 TargetTransformInfo::OK_AnyValue; 5641 TargetTransformInfo::OperandValueKind Op2VK = 5642 TargetTransformInfo::OK_UniformConstantValue; 5643 5644 InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost( 5645 Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK); 5646 if (NeedToShuffleReuses) { 5647 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5648 } 5649 InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost; 5650 InstructionCost VecCost = TTI->getArithmeticInstrCost( 5651 Instruction::Add, VecTy, CostKind, Op1VK, Op2VK); 5652 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5653 return CommonCost + VecCost - ScalarCost; 5654 } 5655 case Instruction::Load: { 5656 // Cost of wide load - cost of scalar loads. 5657 Align Alignment = cast<LoadInst>(VL0)->getAlign(); 5658 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 5659 Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0); 5660 if (NeedToShuffleReuses) { 5661 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5662 } 5663 InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost; 5664 InstructionCost VecLdCost; 5665 if (E->State == TreeEntry::Vectorize) { 5666 VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0, 5667 CostKind, VL0); 5668 } else { 5669 assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState"); 5670 Align CommonAlignment = Alignment; 5671 for (Value *V : VL) 5672 CommonAlignment = 5673 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 5674 VecLdCost = TTI->getGatherScatterOpCost( 5675 Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(), 5676 /*VariableMask=*/false, CommonAlignment, CostKind, VL0); 5677 } 5678 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost)); 5679 return CommonCost + VecLdCost - ScalarLdCost; 5680 } 5681 case Instruction::Store: { 5682 // We know that we can merge the stores. Calculate the cost. 5683 bool IsReorder = !E->ReorderIndices.empty(); 5684 auto *SI = 5685 cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0); 5686 Align Alignment = SI->getAlign(); 5687 InstructionCost ScalarEltCost = TTI->getMemoryOpCost( 5688 Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0); 5689 InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost; 5690 InstructionCost VecStCost = TTI->getMemoryOpCost( 5691 Instruction::Store, VecTy, Alignment, 0, CostKind, VL0); 5692 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost)); 5693 return CommonCost + VecStCost - ScalarStCost; 5694 } 5695 case Instruction::Call: { 5696 CallInst *CI = cast<CallInst>(VL0); 5697 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 5698 5699 // Calculate the cost of the scalar and vector calls. 5700 IntrinsicCostAttributes CostAttrs(ID, *CI, 1); 5701 InstructionCost ScalarEltCost = 5702 TTI->getIntrinsicInstrCost(CostAttrs, CostKind); 5703 if (NeedToShuffleReuses) { 5704 CommonCost -= (EntryVF - VL.size()) * ScalarEltCost; 5705 } 5706 InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost; 5707 5708 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 5709 InstructionCost VecCallCost = 5710 std::min(VecCallCosts.first, VecCallCosts.second); 5711 5712 LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost 5713 << " (" << VecCallCost << "-" << ScalarCallCost << ")" 5714 << " for " << *CI << "\n"); 5715 5716 return CommonCost + VecCallCost - ScalarCallCost; 5717 } 5718 case Instruction::ShuffleVector: { 5719 assert(E->isAltShuffle() && 5720 ((Instruction::isBinaryOp(E->getOpcode()) && 5721 Instruction::isBinaryOp(E->getAltOpcode())) || 5722 (Instruction::isCast(E->getOpcode()) && 5723 Instruction::isCast(E->getAltOpcode())) || 5724 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 5725 "Invalid Shuffle Vector Operand"); 5726 InstructionCost ScalarCost = 0; 5727 if (NeedToShuffleReuses) { 5728 for (unsigned Idx : E->ReuseShuffleIndices) { 5729 Instruction *I = cast<Instruction>(VL[Idx]); 5730 CommonCost -= TTI->getInstructionCost(I, CostKind); 5731 } 5732 for (Value *V : VL) { 5733 Instruction *I = cast<Instruction>(V); 5734 CommonCost += TTI->getInstructionCost(I, CostKind); 5735 } 5736 } 5737 for (Value *V : VL) { 5738 Instruction *I = cast<Instruction>(V); 5739 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 5740 ScalarCost += TTI->getInstructionCost(I, CostKind); 5741 } 5742 // VecCost is equal to sum of the cost of creating 2 vectors 5743 // and the cost of creating shuffle. 5744 InstructionCost VecCost = 0; 5745 // Try to find the previous shuffle node with the same operands and same 5746 // main/alternate ops. 5747 auto &&TryFindNodeWithEqualOperands = [this, E]() { 5748 for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) { 5749 if (TE.get() == E) 5750 break; 5751 if (TE->isAltShuffle() && 5752 ((TE->getOpcode() == E->getOpcode() && 5753 TE->getAltOpcode() == E->getAltOpcode()) || 5754 (TE->getOpcode() == E->getAltOpcode() && 5755 TE->getAltOpcode() == E->getOpcode())) && 5756 TE->hasEqualOperands(*E)) 5757 return true; 5758 } 5759 return false; 5760 }; 5761 if (TryFindNodeWithEqualOperands()) { 5762 LLVM_DEBUG({ 5763 dbgs() << "SLP: diamond match for alternate node found.\n"; 5764 E->dump(); 5765 }); 5766 // No need to add new vector costs here since we're going to reuse 5767 // same main/alternate vector ops, just do different shuffling. 5768 } else if (Instruction::isBinaryOp(E->getOpcode())) { 5769 VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind); 5770 VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy, 5771 CostKind); 5772 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 5773 VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, 5774 Builder.getInt1Ty(), 5775 CI0->getPredicate(), CostKind, VL0); 5776 VecCost += TTI->getCmpSelInstrCost( 5777 E->getOpcode(), ScalarTy, Builder.getInt1Ty(), 5778 cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind, 5779 E->getAltOp()); 5780 } else { 5781 Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType(); 5782 Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType(); 5783 auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size()); 5784 auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size()); 5785 VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty, 5786 TTI::CastContextHint::None, CostKind); 5787 VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty, 5788 TTI::CastContextHint::None, CostKind); 5789 } 5790 5791 SmallVector<int> Mask; 5792 buildShuffleEntryMask( 5793 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 5794 [E](Instruction *I) { 5795 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 5796 return isAlternateInstruction(I, E->getMainOp(), E->getAltOp()); 5797 }, 5798 Mask); 5799 CommonCost = 5800 TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask); 5801 LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost)); 5802 return CommonCost + VecCost - ScalarCost; 5803 } 5804 default: 5805 llvm_unreachable("Unknown instruction"); 5806 } 5807 } 5808 5809 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const { 5810 LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height " 5811 << VectorizableTree.size() << " is fully vectorizable .\n"); 5812 5813 auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) { 5814 SmallVector<int> Mask; 5815 return TE->State == TreeEntry::NeedToGather && 5816 !any_of(TE->Scalars, 5817 [this](Value *V) { return EphValues.contains(V); }) && 5818 (allConstant(TE->Scalars) || isSplat(TE->Scalars) || 5819 TE->Scalars.size() < Limit || 5820 ((TE->getOpcode() == Instruction::ExtractElement || 5821 all_of(TE->Scalars, 5822 [](Value *V) { 5823 return isa<ExtractElementInst, UndefValue>(V); 5824 })) && 5825 isFixedVectorShuffle(TE->Scalars, Mask)) || 5826 (TE->State == TreeEntry::NeedToGather && 5827 TE->getOpcode() == Instruction::Load && !TE->isAltShuffle())); 5828 }; 5829 5830 // We only handle trees of heights 1 and 2. 5831 if (VectorizableTree.size() == 1 && 5832 (VectorizableTree[0]->State == TreeEntry::Vectorize || 5833 (ForReduction && 5834 AreVectorizableGathers(VectorizableTree[0].get(), 5835 VectorizableTree[0]->Scalars.size()) && 5836 VectorizableTree[0]->getVectorFactor() > 2))) 5837 return true; 5838 5839 if (VectorizableTree.size() != 2) 5840 return false; 5841 5842 // Handle splat and all-constants stores. Also try to vectorize tiny trees 5843 // with the second gather nodes if they have less scalar operands rather than 5844 // the initial tree element (may be profitable to shuffle the second gather) 5845 // or they are extractelements, which form shuffle. 5846 SmallVector<int> Mask; 5847 if (VectorizableTree[0]->State == TreeEntry::Vectorize && 5848 AreVectorizableGathers(VectorizableTree[1].get(), 5849 VectorizableTree[0]->Scalars.size())) 5850 return true; 5851 5852 // Gathering cost would be too much for tiny trees. 5853 if (VectorizableTree[0]->State == TreeEntry::NeedToGather || 5854 (VectorizableTree[1]->State == TreeEntry::NeedToGather && 5855 VectorizableTree[0]->State != TreeEntry::ScatterVectorize)) 5856 return false; 5857 5858 return true; 5859 } 5860 5861 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts, 5862 TargetTransformInfo *TTI, 5863 bool MustMatchOrInst) { 5864 // Look past the root to find a source value. Arbitrarily follow the 5865 // path through operand 0 of any 'or'. Also, peek through optional 5866 // shift-left-by-multiple-of-8-bits. 5867 Value *ZextLoad = Root; 5868 const APInt *ShAmtC; 5869 bool FoundOr = false; 5870 while (!isa<ConstantExpr>(ZextLoad) && 5871 (match(ZextLoad, m_Or(m_Value(), m_Value())) || 5872 (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) && 5873 ShAmtC->urem(8) == 0))) { 5874 auto *BinOp = cast<BinaryOperator>(ZextLoad); 5875 ZextLoad = BinOp->getOperand(0); 5876 if (BinOp->getOpcode() == Instruction::Or) 5877 FoundOr = true; 5878 } 5879 // Check if the input is an extended load of the required or/shift expression. 5880 Value *Load; 5881 if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root || 5882 !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load)) 5883 return false; 5884 5885 // Require that the total load bit width is a legal integer type. 5886 // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target. 5887 // But <16 x i8> --> i128 is not, so the backend probably can't reduce it. 5888 Type *SrcTy = Load->getType(); 5889 unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts; 5890 if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth))) 5891 return false; 5892 5893 // Everything matched - assume that we can fold the whole sequence using 5894 // load combining. 5895 LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at " 5896 << *(cast<Instruction>(Root)) << "\n"); 5897 5898 return true; 5899 } 5900 5901 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const { 5902 if (RdxKind != RecurKind::Or) 5903 return false; 5904 5905 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 5906 Value *FirstReduced = VectorizableTree[0]->Scalars[0]; 5907 return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI, 5908 /* MatchOr */ false); 5909 } 5910 5911 bool BoUpSLP::isLoadCombineCandidate() const { 5912 // Peek through a final sequence of stores and check if all operations are 5913 // likely to be load-combined. 5914 unsigned NumElts = VectorizableTree[0]->Scalars.size(); 5915 for (Value *Scalar : VectorizableTree[0]->Scalars) { 5916 Value *X; 5917 if (!match(Scalar, m_Store(m_Value(X), m_Value())) || 5918 !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true)) 5919 return false; 5920 } 5921 return true; 5922 } 5923 5924 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const { 5925 // No need to vectorize inserts of gathered values. 5926 if (VectorizableTree.size() == 2 && 5927 isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) && 5928 VectorizableTree[1]->State == TreeEntry::NeedToGather) 5929 return true; 5930 5931 // We can vectorize the tree if its size is greater than or equal to the 5932 // minimum size specified by the MinTreeSize command line option. 5933 if (VectorizableTree.size() >= MinTreeSize) 5934 return false; 5935 5936 // If we have a tiny tree (a tree whose size is less than MinTreeSize), we 5937 // can vectorize it if we can prove it fully vectorizable. 5938 if (isFullyVectorizableTinyTree(ForReduction)) 5939 return false; 5940 5941 assert(VectorizableTree.empty() 5942 ? ExternalUses.empty() 5943 : true && "We shouldn't have any external users"); 5944 5945 // Otherwise, we can't vectorize the tree. It is both tiny and not fully 5946 // vectorizable. 5947 return true; 5948 } 5949 5950 InstructionCost BoUpSLP::getSpillCost() const { 5951 // Walk from the bottom of the tree to the top, tracking which values are 5952 // live. When we see a call instruction that is not part of our tree, 5953 // query TTI to see if there is a cost to keeping values live over it 5954 // (for example, if spills and fills are required). 5955 unsigned BundleWidth = VectorizableTree.front()->Scalars.size(); 5956 InstructionCost Cost = 0; 5957 5958 SmallPtrSet<Instruction*, 4> LiveValues; 5959 Instruction *PrevInst = nullptr; 5960 5961 // The entries in VectorizableTree are not necessarily ordered by their 5962 // position in basic blocks. Collect them and order them by dominance so later 5963 // instructions are guaranteed to be visited first. For instructions in 5964 // different basic blocks, we only scan to the beginning of the block, so 5965 // their order does not matter, as long as all instructions in a basic block 5966 // are grouped together. Using dominance ensures a deterministic order. 5967 SmallVector<Instruction *, 16> OrderedScalars; 5968 for (const auto &TEPtr : VectorizableTree) { 5969 Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]); 5970 if (!Inst) 5971 continue; 5972 OrderedScalars.push_back(Inst); 5973 } 5974 llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) { 5975 auto *NodeA = DT->getNode(A->getParent()); 5976 auto *NodeB = DT->getNode(B->getParent()); 5977 assert(NodeA && "Should only process reachable instructions"); 5978 assert(NodeB && "Should only process reachable instructions"); 5979 assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) && 5980 "Different nodes should have different DFS numbers"); 5981 if (NodeA != NodeB) 5982 return NodeA->getDFSNumIn() < NodeB->getDFSNumIn(); 5983 return B->comesBefore(A); 5984 }); 5985 5986 for (Instruction *Inst : OrderedScalars) { 5987 if (!PrevInst) { 5988 PrevInst = Inst; 5989 continue; 5990 } 5991 5992 // Update LiveValues. 5993 LiveValues.erase(PrevInst); 5994 for (auto &J : PrevInst->operands()) { 5995 if (isa<Instruction>(&*J) && getTreeEntry(&*J)) 5996 LiveValues.insert(cast<Instruction>(&*J)); 5997 } 5998 5999 LLVM_DEBUG({ 6000 dbgs() << "SLP: #LV: " << LiveValues.size(); 6001 for (auto *X : LiveValues) 6002 dbgs() << " " << X->getName(); 6003 dbgs() << ", Looking at "; 6004 Inst->dump(); 6005 }); 6006 6007 // Now find the sequence of instructions between PrevInst and Inst. 6008 unsigned NumCalls = 0; 6009 BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(), 6010 PrevInstIt = 6011 PrevInst->getIterator().getReverse(); 6012 while (InstIt != PrevInstIt) { 6013 if (PrevInstIt == PrevInst->getParent()->rend()) { 6014 PrevInstIt = Inst->getParent()->rbegin(); 6015 continue; 6016 } 6017 6018 // Debug information does not impact spill cost. 6019 if ((isa<CallInst>(&*PrevInstIt) && 6020 !isa<DbgInfoIntrinsic>(&*PrevInstIt)) && 6021 &*PrevInstIt != PrevInst) 6022 NumCalls++; 6023 6024 ++PrevInstIt; 6025 } 6026 6027 if (NumCalls) { 6028 SmallVector<Type*, 4> V; 6029 for (auto *II : LiveValues) { 6030 auto *ScalarTy = II->getType(); 6031 if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy)) 6032 ScalarTy = VectorTy->getElementType(); 6033 V.push_back(FixedVectorType::get(ScalarTy, BundleWidth)); 6034 } 6035 Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V); 6036 } 6037 6038 PrevInst = Inst; 6039 } 6040 6041 return Cost; 6042 } 6043 6044 /// Check if two insertelement instructions are from the same buildvector. 6045 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU, 6046 InsertElementInst *V) { 6047 // Instructions must be from the same basic blocks. 6048 if (VU->getParent() != V->getParent()) 6049 return false; 6050 // Checks if 2 insertelements are from the same buildvector. 6051 if (VU->getType() != V->getType()) 6052 return false; 6053 // Multiple used inserts are separate nodes. 6054 if (!VU->hasOneUse() && !V->hasOneUse()) 6055 return false; 6056 auto *IE1 = VU; 6057 auto *IE2 = V; 6058 // Go through the vector operand of insertelement instructions trying to find 6059 // either VU as the original vector for IE2 or V as the original vector for 6060 // IE1. 6061 do { 6062 if (IE2 == VU || IE1 == V) 6063 return true; 6064 if (IE1) { 6065 if (IE1 != VU && !IE1->hasOneUse()) 6066 IE1 = nullptr; 6067 else 6068 IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0)); 6069 } 6070 if (IE2) { 6071 if (IE2 != V && !IE2->hasOneUse()) 6072 IE2 = nullptr; 6073 else 6074 IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0)); 6075 } 6076 } while (IE1 || IE2); 6077 return false; 6078 } 6079 6080 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) { 6081 InstructionCost Cost = 0; 6082 LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size " 6083 << VectorizableTree.size() << ".\n"); 6084 6085 unsigned BundleWidth = VectorizableTree[0]->Scalars.size(); 6086 6087 for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) { 6088 TreeEntry &TE = *VectorizableTree[I]; 6089 6090 InstructionCost C = getEntryCost(&TE, VectorizedVals); 6091 Cost += C; 6092 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6093 << " for bundle that starts with " << *TE.Scalars[0] 6094 << ".\n" 6095 << "SLP: Current total cost = " << Cost << "\n"); 6096 } 6097 6098 SmallPtrSet<Value *, 16> ExtractCostCalculated; 6099 InstructionCost ExtractCost = 0; 6100 SmallVector<unsigned> VF; 6101 SmallVector<SmallVector<int>> ShuffleMask; 6102 SmallVector<Value *> FirstUsers; 6103 SmallVector<APInt> DemandedElts; 6104 for (ExternalUser &EU : ExternalUses) { 6105 // We only add extract cost once for the same scalar. 6106 if (!isa_and_nonnull<InsertElementInst>(EU.User) && 6107 !ExtractCostCalculated.insert(EU.Scalar).second) 6108 continue; 6109 6110 // Uses by ephemeral values are free (because the ephemeral value will be 6111 // removed prior to code generation, and so the extraction will be 6112 // removed as well). 6113 if (EphValues.count(EU.User)) 6114 continue; 6115 6116 // No extract cost for vector "scalar" 6117 if (isa<FixedVectorType>(EU.Scalar->getType())) 6118 continue; 6119 6120 // Already counted the cost for external uses when tried to adjust the cost 6121 // for extractelements, no need to add it again. 6122 if (isa<ExtractElementInst>(EU.Scalar)) 6123 continue; 6124 6125 // If found user is an insertelement, do not calculate extract cost but try 6126 // to detect it as a final shuffled/identity match. 6127 if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) { 6128 if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) { 6129 Optional<unsigned> InsertIdx = getInsertIndex(VU); 6130 if (InsertIdx) { 6131 auto *It = find_if(FirstUsers, [VU](Value *V) { 6132 return areTwoInsertFromSameBuildVector(VU, 6133 cast<InsertElementInst>(V)); 6134 }); 6135 int VecId = -1; 6136 if (It == FirstUsers.end()) { 6137 VF.push_back(FTy->getNumElements()); 6138 ShuffleMask.emplace_back(VF.back(), UndefMaskElem); 6139 // Find the insertvector, vectorized in tree, if any. 6140 Value *Base = VU; 6141 while (isa<InsertElementInst>(Base)) { 6142 // Build the mask for the vectorized insertelement instructions. 6143 if (const TreeEntry *E = getTreeEntry(Base)) { 6144 VU = cast<InsertElementInst>(Base); 6145 do { 6146 int Idx = E->findLaneForValue(Base); 6147 ShuffleMask.back()[Idx] = Idx; 6148 Base = cast<InsertElementInst>(Base)->getOperand(0); 6149 } while (E == getTreeEntry(Base)); 6150 break; 6151 } 6152 Base = cast<InsertElementInst>(Base)->getOperand(0); 6153 } 6154 FirstUsers.push_back(VU); 6155 DemandedElts.push_back(APInt::getZero(VF.back())); 6156 VecId = FirstUsers.size() - 1; 6157 } else { 6158 VecId = std::distance(FirstUsers.begin(), It); 6159 } 6160 ShuffleMask[VecId][*InsertIdx] = EU.Lane; 6161 DemandedElts[VecId].setBit(*InsertIdx); 6162 continue; 6163 } 6164 } 6165 } 6166 6167 // If we plan to rewrite the tree in a smaller type, we will need to sign 6168 // extend the extracted value back to the original type. Here, we account 6169 // for the extract and the added cost of the sign extend if needed. 6170 auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth); 6171 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 6172 if (MinBWs.count(ScalarRoot)) { 6173 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 6174 auto Extend = 6175 MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt; 6176 VecTy = FixedVectorType::get(MinTy, BundleWidth); 6177 ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(), 6178 VecTy, EU.Lane); 6179 } else { 6180 ExtractCost += 6181 TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane); 6182 } 6183 } 6184 6185 InstructionCost SpillCost = getSpillCost(); 6186 Cost += SpillCost + ExtractCost; 6187 if (FirstUsers.size() == 1) { 6188 int Limit = ShuffleMask.front().size() * 2; 6189 if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) && 6190 !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) { 6191 InstructionCost C = TTI->getShuffleCost( 6192 TTI::SK_PermuteSingleSrc, 6193 cast<FixedVectorType>(FirstUsers.front()->getType()), 6194 ShuffleMask.front()); 6195 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6196 << " for final shuffle of insertelement external users " 6197 << *VectorizableTree.front()->Scalars.front() << ".\n" 6198 << "SLP: Current total cost = " << Cost << "\n"); 6199 Cost += C; 6200 } 6201 InstructionCost InsertCost = TTI->getScalarizationOverhead( 6202 cast<FixedVectorType>(FirstUsers.front()->getType()), 6203 DemandedElts.front(), /*Insert*/ true, /*Extract*/ false); 6204 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 6205 << " for insertelements gather.\n" 6206 << "SLP: Current total cost = " << Cost << "\n"); 6207 Cost -= InsertCost; 6208 } else if (FirstUsers.size() >= 2) { 6209 unsigned MaxVF = *std::max_element(VF.begin(), VF.end()); 6210 // Combined masks of the first 2 vectors. 6211 SmallVector<int> CombinedMask(MaxVF, UndefMaskElem); 6212 copy(ShuffleMask.front(), CombinedMask.begin()); 6213 APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF); 6214 auto *VecTy = FixedVectorType::get( 6215 cast<VectorType>(FirstUsers.front()->getType())->getElementType(), 6216 MaxVF); 6217 for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) { 6218 if (ShuffleMask[1][I] != UndefMaskElem) { 6219 CombinedMask[I] = ShuffleMask[1][I] + MaxVF; 6220 CombinedDemandedElts.setBit(I); 6221 } 6222 } 6223 InstructionCost C = 6224 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask); 6225 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6226 << " for final shuffle of vector node and external " 6227 "insertelement users " 6228 << *VectorizableTree.front()->Scalars.front() << ".\n" 6229 << "SLP: Current total cost = " << Cost << "\n"); 6230 Cost += C; 6231 InstructionCost InsertCost = TTI->getScalarizationOverhead( 6232 VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false); 6233 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 6234 << " for insertelements gather.\n" 6235 << "SLP: Current total cost = " << Cost << "\n"); 6236 Cost -= InsertCost; 6237 for (int I = 2, E = FirstUsers.size(); I < E; ++I) { 6238 // Other elements - permutation of 2 vectors (the initial one and the 6239 // next Ith incoming vector). 6240 unsigned VF = ShuffleMask[I].size(); 6241 for (unsigned Idx = 0; Idx < VF; ++Idx) { 6242 int Mask = ShuffleMask[I][Idx]; 6243 if (Mask != UndefMaskElem) 6244 CombinedMask[Idx] = MaxVF + Mask; 6245 else if (CombinedMask[Idx] != UndefMaskElem) 6246 CombinedMask[Idx] = Idx; 6247 } 6248 for (unsigned Idx = VF; Idx < MaxVF; ++Idx) 6249 if (CombinedMask[Idx] != UndefMaskElem) 6250 CombinedMask[Idx] = Idx; 6251 InstructionCost C = 6252 TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask); 6253 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C 6254 << " for final shuffle of vector node and external " 6255 "insertelement users " 6256 << *VectorizableTree.front()->Scalars.front() << ".\n" 6257 << "SLP: Current total cost = " << Cost << "\n"); 6258 Cost += C; 6259 InstructionCost InsertCost = TTI->getScalarizationOverhead( 6260 cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I], 6261 /*Insert*/ true, /*Extract*/ false); 6262 LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost 6263 << " for insertelements gather.\n" 6264 << "SLP: Current total cost = " << Cost << "\n"); 6265 Cost -= InsertCost; 6266 } 6267 } 6268 6269 #ifndef NDEBUG 6270 SmallString<256> Str; 6271 { 6272 raw_svector_ostream OS(Str); 6273 OS << "SLP: Spill Cost = " << SpillCost << ".\n" 6274 << "SLP: Extract Cost = " << ExtractCost << ".\n" 6275 << "SLP: Total Cost = " << Cost << ".\n"; 6276 } 6277 LLVM_DEBUG(dbgs() << Str); 6278 if (ViewSLPTree) 6279 ViewGraph(this, "SLP" + F->getName(), false, Str); 6280 #endif 6281 6282 return Cost; 6283 } 6284 6285 Optional<TargetTransformInfo::ShuffleKind> 6286 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask, 6287 SmallVectorImpl<const TreeEntry *> &Entries) { 6288 // TODO: currently checking only for Scalars in the tree entry, need to count 6289 // reused elements too for better cost estimation. 6290 Mask.assign(TE->Scalars.size(), UndefMaskElem); 6291 Entries.clear(); 6292 // Build a lists of values to tree entries. 6293 DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs; 6294 for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) { 6295 if (EntryPtr.get() == TE) 6296 break; 6297 if (EntryPtr->State != TreeEntry::NeedToGather) 6298 continue; 6299 for (Value *V : EntryPtr->Scalars) 6300 ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get()); 6301 } 6302 // Find all tree entries used by the gathered values. If no common entries 6303 // found - not a shuffle. 6304 // Here we build a set of tree nodes for each gathered value and trying to 6305 // find the intersection between these sets. If we have at least one common 6306 // tree node for each gathered value - we have just a permutation of the 6307 // single vector. If we have 2 different sets, we're in situation where we 6308 // have a permutation of 2 input vectors. 6309 SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs; 6310 DenseMap<Value *, int> UsedValuesEntry; 6311 for (Value *V : TE->Scalars) { 6312 if (isa<UndefValue>(V)) 6313 continue; 6314 // Build a list of tree entries where V is used. 6315 SmallPtrSet<const TreeEntry *, 4> VToTEs; 6316 auto It = ValueToTEs.find(V); 6317 if (It != ValueToTEs.end()) 6318 VToTEs = It->second; 6319 if (const TreeEntry *VTE = getTreeEntry(V)) 6320 VToTEs.insert(VTE); 6321 if (VToTEs.empty()) 6322 return None; 6323 if (UsedTEs.empty()) { 6324 // The first iteration, just insert the list of nodes to vector. 6325 UsedTEs.push_back(VToTEs); 6326 } else { 6327 // Need to check if there are any previously used tree nodes which use V. 6328 // If there are no such nodes, consider that we have another one input 6329 // vector. 6330 SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs); 6331 unsigned Idx = 0; 6332 for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) { 6333 // Do we have a non-empty intersection of previously listed tree entries 6334 // and tree entries using current V? 6335 set_intersect(VToTEs, Set); 6336 if (!VToTEs.empty()) { 6337 // Yes, write the new subset and continue analysis for the next 6338 // scalar. 6339 Set.swap(VToTEs); 6340 break; 6341 } 6342 VToTEs = SavedVToTEs; 6343 ++Idx; 6344 } 6345 // No non-empty intersection found - need to add a second set of possible 6346 // source vectors. 6347 if (Idx == UsedTEs.size()) { 6348 // If the number of input vectors is greater than 2 - not a permutation, 6349 // fallback to the regular gather. 6350 if (UsedTEs.size() == 2) 6351 return None; 6352 UsedTEs.push_back(SavedVToTEs); 6353 Idx = UsedTEs.size() - 1; 6354 } 6355 UsedValuesEntry.try_emplace(V, Idx); 6356 } 6357 } 6358 6359 unsigned VF = 0; 6360 if (UsedTEs.size() == 1) { 6361 // Try to find the perfect match in another gather node at first. 6362 auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) { 6363 return EntryPtr->isSame(TE->Scalars); 6364 }); 6365 if (It != UsedTEs.front().end()) { 6366 Entries.push_back(*It); 6367 std::iota(Mask.begin(), Mask.end(), 0); 6368 return TargetTransformInfo::SK_PermuteSingleSrc; 6369 } 6370 // No perfect match, just shuffle, so choose the first tree node. 6371 Entries.push_back(*UsedTEs.front().begin()); 6372 } else { 6373 // Try to find nodes with the same vector factor. 6374 assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries."); 6375 DenseMap<int, const TreeEntry *> VFToTE; 6376 for (const TreeEntry *TE : UsedTEs.front()) 6377 VFToTE.try_emplace(TE->getVectorFactor(), TE); 6378 for (const TreeEntry *TE : UsedTEs.back()) { 6379 auto It = VFToTE.find(TE->getVectorFactor()); 6380 if (It != VFToTE.end()) { 6381 VF = It->first; 6382 Entries.push_back(It->second); 6383 Entries.push_back(TE); 6384 break; 6385 } 6386 } 6387 // No 2 source vectors with the same vector factor - give up and do regular 6388 // gather. 6389 if (Entries.empty()) 6390 return None; 6391 } 6392 6393 // Build a shuffle mask for better cost estimation and vector emission. 6394 for (int I = 0, E = TE->Scalars.size(); I < E; ++I) { 6395 Value *V = TE->Scalars[I]; 6396 if (isa<UndefValue>(V)) 6397 continue; 6398 unsigned Idx = UsedValuesEntry.lookup(V); 6399 const TreeEntry *VTE = Entries[Idx]; 6400 int FoundLane = VTE->findLaneForValue(V); 6401 Mask[I] = Idx * VF + FoundLane; 6402 // Extra check required by isSingleSourceMaskImpl function (called by 6403 // ShuffleVectorInst::isSingleSourceMask). 6404 if (Mask[I] >= 2 * E) 6405 return None; 6406 } 6407 switch (Entries.size()) { 6408 case 1: 6409 return TargetTransformInfo::SK_PermuteSingleSrc; 6410 case 2: 6411 return TargetTransformInfo::SK_PermuteTwoSrc; 6412 default: 6413 break; 6414 } 6415 return None; 6416 } 6417 6418 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty, 6419 const APInt &ShuffledIndices, 6420 bool NeedToShuffle) const { 6421 InstructionCost Cost = 6422 TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true, 6423 /*Extract*/ false); 6424 if (NeedToShuffle) 6425 Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty); 6426 return Cost; 6427 } 6428 6429 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const { 6430 // Find the type of the operands in VL. 6431 Type *ScalarTy = VL[0]->getType(); 6432 if (StoreInst *SI = dyn_cast<StoreInst>(VL[0])) 6433 ScalarTy = SI->getValueOperand()->getType(); 6434 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size()); 6435 bool DuplicateNonConst = false; 6436 // Find the cost of inserting/extracting values from the vector. 6437 // Check if the same elements are inserted several times and count them as 6438 // shuffle candidates. 6439 APInt ShuffledElements = APInt::getZero(VL.size()); 6440 DenseSet<Value *> UniqueElements; 6441 // Iterate in reverse order to consider insert elements with the high cost. 6442 for (unsigned I = VL.size(); I > 0; --I) { 6443 unsigned Idx = I - 1; 6444 // No need to shuffle duplicates for constants. 6445 if (isConstant(VL[Idx])) { 6446 ShuffledElements.setBit(Idx); 6447 continue; 6448 } 6449 if (!UniqueElements.insert(VL[Idx]).second) { 6450 DuplicateNonConst = true; 6451 ShuffledElements.setBit(Idx); 6452 } 6453 } 6454 return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst); 6455 } 6456 6457 // Perform operand reordering on the instructions in VL and return the reordered 6458 // operands in Left and Right. 6459 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL, 6460 SmallVectorImpl<Value *> &Left, 6461 SmallVectorImpl<Value *> &Right, 6462 const DataLayout &DL, 6463 ScalarEvolution &SE, 6464 const BoUpSLP &R) { 6465 if (VL.empty()) 6466 return; 6467 VLOperands Ops(VL, DL, SE, R); 6468 // Reorder the operands in place. 6469 Ops.reorder(); 6470 Left = Ops.getVL(0); 6471 Right = Ops.getVL(1); 6472 } 6473 6474 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) { 6475 // Get the basic block this bundle is in. All instructions in the bundle 6476 // should be in this block. 6477 auto *Front = E->getMainOp(); 6478 auto *BB = Front->getParent(); 6479 assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool { 6480 auto *I = cast<Instruction>(V); 6481 return !E->isOpcodeOrAlt(I) || I->getParent() == BB; 6482 })); 6483 6484 auto &&FindLastInst = [E, Front]() { 6485 Instruction *LastInst = Front; 6486 for (Value *V : E->Scalars) { 6487 auto *I = dyn_cast<Instruction>(V); 6488 if (!I) 6489 continue; 6490 if (LastInst->comesBefore(I)) 6491 LastInst = I; 6492 } 6493 return LastInst; 6494 }; 6495 6496 auto &&FindFirstInst = [E, Front]() { 6497 Instruction *FirstInst = Front; 6498 for (Value *V : E->Scalars) { 6499 auto *I = dyn_cast<Instruction>(V); 6500 if (!I) 6501 continue; 6502 if (I->comesBefore(FirstInst)) 6503 FirstInst = I; 6504 } 6505 return FirstInst; 6506 }; 6507 6508 // Set the insert point to the beginning of the basic block if the entry 6509 // should not be scheduled. 6510 if (E->State != TreeEntry::NeedToGather && 6511 doesNotNeedToSchedule(E->Scalars)) { 6512 BasicBlock::iterator InsertPt; 6513 if (all_of(E->Scalars, isUsedOutsideBlock)) 6514 InsertPt = FindLastInst()->getIterator(); 6515 else 6516 InsertPt = FindFirstInst()->getIterator(); 6517 Builder.SetInsertPoint(BB, InsertPt); 6518 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 6519 return; 6520 } 6521 6522 // The last instruction in the bundle in program order. 6523 Instruction *LastInst = nullptr; 6524 6525 // Find the last instruction. The common case should be that BB has been 6526 // scheduled, and the last instruction is VL.back(). So we start with 6527 // VL.back() and iterate over schedule data until we reach the end of the 6528 // bundle. The end of the bundle is marked by null ScheduleData. 6529 if (BlocksSchedules.count(BB)) { 6530 Value *V = E->isOneOf(E->Scalars.back()); 6531 if (doesNotNeedToBeScheduled(V)) 6532 V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled); 6533 auto *Bundle = BlocksSchedules[BB]->getScheduleData(V); 6534 if (Bundle && Bundle->isPartOfBundle()) 6535 for (; Bundle; Bundle = Bundle->NextInBundle) 6536 if (Bundle->OpValue == Bundle->Inst) 6537 LastInst = Bundle->Inst; 6538 } 6539 6540 // LastInst can still be null at this point if there's either not an entry 6541 // for BB in BlocksSchedules or there's no ScheduleData available for 6542 // VL.back(). This can be the case if buildTree_rec aborts for various 6543 // reasons (e.g., the maximum recursion depth is reached, the maximum region 6544 // size is reached, etc.). ScheduleData is initialized in the scheduling 6545 // "dry-run". 6546 // 6547 // If this happens, we can still find the last instruction by brute force. We 6548 // iterate forwards from Front (inclusive) until we either see all 6549 // instructions in the bundle or reach the end of the block. If Front is the 6550 // last instruction in program order, LastInst will be set to Front, and we 6551 // will visit all the remaining instructions in the block. 6552 // 6553 // One of the reasons we exit early from buildTree_rec is to place an upper 6554 // bound on compile-time. Thus, taking an additional compile-time hit here is 6555 // not ideal. However, this should be exceedingly rare since it requires that 6556 // we both exit early from buildTree_rec and that the bundle be out-of-order 6557 // (causing us to iterate all the way to the end of the block). 6558 if (!LastInst) 6559 LastInst = FindLastInst(); 6560 assert(LastInst && "Failed to find last instruction in bundle"); 6561 6562 // Set the insertion point after the last instruction in the bundle. Set the 6563 // debug location to Front. 6564 Builder.SetInsertPoint(BB, ++LastInst->getIterator()); 6565 Builder.SetCurrentDebugLocation(Front->getDebugLoc()); 6566 } 6567 6568 Value *BoUpSLP::gather(ArrayRef<Value *> VL) { 6569 // List of instructions/lanes from current block and/or the blocks which are 6570 // part of the current loop. These instructions will be inserted at the end to 6571 // make it possible to optimize loops and hoist invariant instructions out of 6572 // the loops body with better chances for success. 6573 SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts; 6574 SmallSet<int, 4> PostponedIndices; 6575 Loop *L = LI->getLoopFor(Builder.GetInsertBlock()); 6576 auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) { 6577 SmallPtrSet<BasicBlock *, 4> Visited; 6578 while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second) 6579 InsertBB = InsertBB->getSinglePredecessor(); 6580 return InsertBB && InsertBB == InstBB; 6581 }; 6582 for (int I = 0, E = VL.size(); I < E; ++I) { 6583 if (auto *Inst = dyn_cast<Instruction>(VL[I])) 6584 if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) || 6585 getTreeEntry(Inst) || (L && (L->contains(Inst)))) && 6586 PostponedIndices.insert(I).second) 6587 PostponedInsts.emplace_back(Inst, I); 6588 } 6589 6590 auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) { 6591 Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos)); 6592 auto *InsElt = dyn_cast<InsertElementInst>(Vec); 6593 if (!InsElt) 6594 return Vec; 6595 GatherShuffleSeq.insert(InsElt); 6596 CSEBlocks.insert(InsElt->getParent()); 6597 // Add to our 'need-to-extract' list. 6598 if (TreeEntry *Entry = getTreeEntry(V)) { 6599 // Find which lane we need to extract. 6600 unsigned FoundLane = Entry->findLaneForValue(V); 6601 ExternalUses.emplace_back(V, InsElt, FoundLane); 6602 } 6603 return Vec; 6604 }; 6605 Value *Val0 = 6606 isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0]; 6607 FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size()); 6608 Value *Vec = PoisonValue::get(VecTy); 6609 SmallVector<int> NonConsts; 6610 // Insert constant values at first. 6611 for (int I = 0, E = VL.size(); I < E; ++I) { 6612 if (PostponedIndices.contains(I)) 6613 continue; 6614 if (!isConstant(VL[I])) { 6615 NonConsts.push_back(I); 6616 continue; 6617 } 6618 Vec = CreateInsertElement(Vec, VL[I], I); 6619 } 6620 // Insert non-constant values. 6621 for (int I : NonConsts) 6622 Vec = CreateInsertElement(Vec, VL[I], I); 6623 // Append instructions, which are/may be part of the loop, in the end to make 6624 // it possible to hoist non-loop-based instructions. 6625 for (const std::pair<Value *, unsigned> &Pair : PostponedInsts) 6626 Vec = CreateInsertElement(Vec, Pair.first, Pair.second); 6627 6628 return Vec; 6629 } 6630 6631 namespace { 6632 /// Merges shuffle masks and emits final shuffle instruction, if required. 6633 class ShuffleInstructionBuilder { 6634 IRBuilderBase &Builder; 6635 const unsigned VF = 0; 6636 bool IsFinalized = false; 6637 SmallVector<int, 4> Mask; 6638 /// Holds all of the instructions that we gathered. 6639 SetVector<Instruction *> &GatherShuffleSeq; 6640 /// A list of blocks that we are going to CSE. 6641 SetVector<BasicBlock *> &CSEBlocks; 6642 6643 public: 6644 ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF, 6645 SetVector<Instruction *> &GatherShuffleSeq, 6646 SetVector<BasicBlock *> &CSEBlocks) 6647 : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq), 6648 CSEBlocks(CSEBlocks) {} 6649 6650 /// Adds a mask, inverting it before applying. 6651 void addInversedMask(ArrayRef<unsigned> SubMask) { 6652 if (SubMask.empty()) 6653 return; 6654 SmallVector<int, 4> NewMask; 6655 inversePermutation(SubMask, NewMask); 6656 addMask(NewMask); 6657 } 6658 6659 /// Functions adds masks, merging them into single one. 6660 void addMask(ArrayRef<unsigned> SubMask) { 6661 SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end()); 6662 addMask(NewMask); 6663 } 6664 6665 void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); } 6666 6667 Value *finalize(Value *V) { 6668 IsFinalized = true; 6669 unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements(); 6670 if (VF == ValueVF && Mask.empty()) 6671 return V; 6672 SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem); 6673 std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0); 6674 addMask(NormalizedMask); 6675 6676 if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask)) 6677 return V; 6678 Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle"); 6679 if (auto *I = dyn_cast<Instruction>(Vec)) { 6680 GatherShuffleSeq.insert(I); 6681 CSEBlocks.insert(I->getParent()); 6682 } 6683 return Vec; 6684 } 6685 6686 ~ShuffleInstructionBuilder() { 6687 assert((IsFinalized || Mask.empty()) && 6688 "Shuffle construction must be finalized."); 6689 } 6690 }; 6691 } // namespace 6692 6693 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) { 6694 const unsigned VF = VL.size(); 6695 InstructionsState S = getSameOpcode(VL); 6696 if (S.getOpcode()) { 6697 if (TreeEntry *E = getTreeEntry(S.OpValue)) 6698 if (E->isSame(VL)) { 6699 Value *V = vectorizeTree(E); 6700 if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) { 6701 if (!E->ReuseShuffleIndices.empty()) { 6702 // Reshuffle to get only unique values. 6703 // If some of the scalars are duplicated in the vectorization tree 6704 // entry, we do not vectorize them but instead generate a mask for 6705 // the reuses. But if there are several users of the same entry, 6706 // they may have different vectorization factors. This is especially 6707 // important for PHI nodes. In this case, we need to adapt the 6708 // resulting instruction for the user vectorization factor and have 6709 // to reshuffle it again to take only unique elements of the vector. 6710 // Without this code the function incorrectly returns reduced vector 6711 // instruction with the same elements, not with the unique ones. 6712 6713 // block: 6714 // %phi = phi <2 x > { .., %entry} {%shuffle, %block} 6715 // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0> 6716 // ... (use %2) 6717 // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0} 6718 // br %block 6719 SmallVector<int> UniqueIdxs(VF, UndefMaskElem); 6720 SmallSet<int, 4> UsedIdxs; 6721 int Pos = 0; 6722 int Sz = VL.size(); 6723 for (int Idx : E->ReuseShuffleIndices) { 6724 if (Idx != Sz && Idx != UndefMaskElem && 6725 UsedIdxs.insert(Idx).second) 6726 UniqueIdxs[Idx] = Pos; 6727 ++Pos; 6728 } 6729 assert(VF >= UsedIdxs.size() && "Expected vectorization factor " 6730 "less than original vector size."); 6731 UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem); 6732 V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle"); 6733 } else { 6734 assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() && 6735 "Expected vectorization factor less " 6736 "than original vector size."); 6737 SmallVector<int> UniformMask(VF, 0); 6738 std::iota(UniformMask.begin(), UniformMask.end(), 0); 6739 V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle"); 6740 } 6741 if (auto *I = dyn_cast<Instruction>(V)) { 6742 GatherShuffleSeq.insert(I); 6743 CSEBlocks.insert(I->getParent()); 6744 } 6745 } 6746 return V; 6747 } 6748 } 6749 6750 // Can't vectorize this, so simply build a new vector with each lane 6751 // corresponding to the requested value. 6752 return createBuildVector(VL); 6753 } 6754 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) { 6755 unsigned VF = VL.size(); 6756 // Exploit possible reuse of values across lanes. 6757 SmallVector<int> ReuseShuffleIndicies; 6758 SmallVector<Value *> UniqueValues; 6759 if (VL.size() > 2) { 6760 DenseMap<Value *, unsigned> UniquePositions; 6761 unsigned NumValues = 6762 std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) { 6763 return !isa<UndefValue>(V); 6764 }).base()); 6765 VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues)); 6766 int UniqueVals = 0; 6767 for (Value *V : VL.drop_back(VL.size() - VF)) { 6768 if (isa<UndefValue>(V)) { 6769 ReuseShuffleIndicies.emplace_back(UndefMaskElem); 6770 continue; 6771 } 6772 if (isConstant(V)) { 6773 ReuseShuffleIndicies.emplace_back(UniqueValues.size()); 6774 UniqueValues.emplace_back(V); 6775 continue; 6776 } 6777 auto Res = UniquePositions.try_emplace(V, UniqueValues.size()); 6778 ReuseShuffleIndicies.emplace_back(Res.first->second); 6779 if (Res.second) { 6780 UniqueValues.emplace_back(V); 6781 ++UniqueVals; 6782 } 6783 } 6784 if (UniqueVals == 1 && UniqueValues.size() == 1) { 6785 // Emit pure splat vector. 6786 ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(), 6787 UndefMaskElem); 6788 } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) { 6789 ReuseShuffleIndicies.clear(); 6790 UniqueValues.clear(); 6791 UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues)); 6792 } 6793 UniqueValues.append(VF - UniqueValues.size(), 6794 PoisonValue::get(VL[0]->getType())); 6795 VL = UniqueValues; 6796 } 6797 6798 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 6799 CSEBlocks); 6800 Value *Vec = gather(VL); 6801 if (!ReuseShuffleIndicies.empty()) { 6802 ShuffleBuilder.addMask(ReuseShuffleIndicies); 6803 Vec = ShuffleBuilder.finalize(Vec); 6804 } 6805 return Vec; 6806 } 6807 6808 Value *BoUpSLP::vectorizeTree(TreeEntry *E) { 6809 IRBuilder<>::InsertPointGuard Guard(Builder); 6810 6811 if (E->VectorizedValue) { 6812 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n"); 6813 return E->VectorizedValue; 6814 } 6815 6816 bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty(); 6817 unsigned VF = E->getVectorFactor(); 6818 ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq, 6819 CSEBlocks); 6820 if (E->State == TreeEntry::NeedToGather) { 6821 if (E->getMainOp()) 6822 setInsertPointAfterBundle(E); 6823 Value *Vec; 6824 SmallVector<int> Mask; 6825 SmallVector<const TreeEntry *> Entries; 6826 Optional<TargetTransformInfo::ShuffleKind> Shuffle = 6827 isGatherShuffledEntry(E, Mask, Entries); 6828 if (Shuffle.hasValue()) { 6829 assert((Entries.size() == 1 || Entries.size() == 2) && 6830 "Expected shuffle of 1 or 2 entries."); 6831 Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue, 6832 Entries.back()->VectorizedValue, Mask); 6833 if (auto *I = dyn_cast<Instruction>(Vec)) { 6834 GatherShuffleSeq.insert(I); 6835 CSEBlocks.insert(I->getParent()); 6836 } 6837 } else { 6838 Vec = gather(E->Scalars); 6839 } 6840 if (NeedToShuffleReuses) { 6841 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6842 Vec = ShuffleBuilder.finalize(Vec); 6843 } 6844 E->VectorizedValue = Vec; 6845 return Vec; 6846 } 6847 6848 assert((E->State == TreeEntry::Vectorize || 6849 E->State == TreeEntry::ScatterVectorize) && 6850 "Unhandled state"); 6851 unsigned ShuffleOrOp = 6852 E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode(); 6853 Instruction *VL0 = E->getMainOp(); 6854 Type *ScalarTy = VL0->getType(); 6855 if (auto *Store = dyn_cast<StoreInst>(VL0)) 6856 ScalarTy = Store->getValueOperand()->getType(); 6857 else if (auto *IE = dyn_cast<InsertElementInst>(VL0)) 6858 ScalarTy = IE->getOperand(1)->getType(); 6859 auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size()); 6860 switch (ShuffleOrOp) { 6861 case Instruction::PHI: { 6862 assert( 6863 (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) && 6864 "PHI reordering is free."); 6865 auto *PH = cast<PHINode>(VL0); 6866 Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI()); 6867 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 6868 PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues()); 6869 Value *V = NewPhi; 6870 6871 // Adjust insertion point once all PHI's have been generated. 6872 Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt()); 6873 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 6874 6875 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6876 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6877 V = ShuffleBuilder.finalize(V); 6878 6879 E->VectorizedValue = V; 6880 6881 // PHINodes may have multiple entries from the same block. We want to 6882 // visit every block once. 6883 SmallPtrSet<BasicBlock*, 4> VisitedBBs; 6884 6885 for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) { 6886 ValueList Operands; 6887 BasicBlock *IBB = PH->getIncomingBlock(i); 6888 6889 if (!VisitedBBs.insert(IBB).second) { 6890 NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB); 6891 continue; 6892 } 6893 6894 Builder.SetInsertPoint(IBB->getTerminator()); 6895 Builder.SetCurrentDebugLocation(PH->getDebugLoc()); 6896 Value *Vec = vectorizeTree(E->getOperand(i)); 6897 NewPhi->addIncoming(Vec, IBB); 6898 } 6899 6900 assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() && 6901 "Invalid number of incoming values"); 6902 return V; 6903 } 6904 6905 case Instruction::ExtractElement: { 6906 Value *V = E->getSingleOperand(0); 6907 Builder.SetInsertPoint(VL0); 6908 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6909 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6910 V = ShuffleBuilder.finalize(V); 6911 E->VectorizedValue = V; 6912 return V; 6913 } 6914 case Instruction::ExtractValue: { 6915 auto *LI = cast<LoadInst>(E->getSingleOperand(0)); 6916 Builder.SetInsertPoint(LI); 6917 auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace()); 6918 Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy); 6919 LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign()); 6920 Value *NewV = propagateMetadata(V, E->Scalars); 6921 ShuffleBuilder.addInversedMask(E->ReorderIndices); 6922 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 6923 NewV = ShuffleBuilder.finalize(NewV); 6924 E->VectorizedValue = NewV; 6925 return NewV; 6926 } 6927 case Instruction::InsertElement: { 6928 assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique"); 6929 Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back())); 6930 Value *V = vectorizeTree(E->getOperand(1)); 6931 6932 // Create InsertVector shuffle if necessary 6933 auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) { 6934 return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0)); 6935 })); 6936 const unsigned NumElts = 6937 cast<FixedVectorType>(FirstInsert->getType())->getNumElements(); 6938 const unsigned NumScalars = E->Scalars.size(); 6939 6940 unsigned Offset = *getInsertIndex(VL0); 6941 assert(Offset < NumElts && "Failed to find vector index offset"); 6942 6943 // Create shuffle to resize vector 6944 SmallVector<int> Mask; 6945 if (!E->ReorderIndices.empty()) { 6946 inversePermutation(E->ReorderIndices, Mask); 6947 Mask.append(NumElts - NumScalars, UndefMaskElem); 6948 } else { 6949 Mask.assign(NumElts, UndefMaskElem); 6950 std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0); 6951 } 6952 // Create InsertVector shuffle if necessary 6953 bool IsIdentity = true; 6954 SmallVector<int> PrevMask(NumElts, UndefMaskElem); 6955 Mask.swap(PrevMask); 6956 for (unsigned I = 0; I < NumScalars; ++I) { 6957 Value *Scalar = E->Scalars[PrevMask[I]]; 6958 unsigned InsertIdx = *getInsertIndex(Scalar); 6959 IsIdentity &= InsertIdx - Offset == I; 6960 Mask[InsertIdx - Offset] = I; 6961 } 6962 if (!IsIdentity || NumElts != NumScalars) { 6963 V = Builder.CreateShuffleVector(V, Mask); 6964 if (auto *I = dyn_cast<Instruction>(V)) { 6965 GatherShuffleSeq.insert(I); 6966 CSEBlocks.insert(I->getParent()); 6967 } 6968 } 6969 6970 if ((!IsIdentity || Offset != 0 || 6971 !isUndefVector(FirstInsert->getOperand(0))) && 6972 NumElts != NumScalars) { 6973 SmallVector<int> InsertMask(NumElts); 6974 std::iota(InsertMask.begin(), InsertMask.end(), 0); 6975 for (unsigned I = 0; I < NumElts; I++) { 6976 if (Mask[I] != UndefMaskElem) 6977 InsertMask[Offset + I] = NumElts + I; 6978 } 6979 6980 V = Builder.CreateShuffleVector( 6981 FirstInsert->getOperand(0), V, InsertMask, 6982 cast<Instruction>(E->Scalars.back())->getName()); 6983 if (auto *I = dyn_cast<Instruction>(V)) { 6984 GatherShuffleSeq.insert(I); 6985 CSEBlocks.insert(I->getParent()); 6986 } 6987 } 6988 6989 ++NumVectorInstructions; 6990 E->VectorizedValue = V; 6991 return V; 6992 } 6993 case Instruction::ZExt: 6994 case Instruction::SExt: 6995 case Instruction::FPToUI: 6996 case Instruction::FPToSI: 6997 case Instruction::FPExt: 6998 case Instruction::PtrToInt: 6999 case Instruction::IntToPtr: 7000 case Instruction::SIToFP: 7001 case Instruction::UIToFP: 7002 case Instruction::Trunc: 7003 case Instruction::FPTrunc: 7004 case Instruction::BitCast: { 7005 setInsertPointAfterBundle(E); 7006 7007 Value *InVec = vectorizeTree(E->getOperand(0)); 7008 7009 if (E->VectorizedValue) { 7010 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7011 return E->VectorizedValue; 7012 } 7013 7014 auto *CI = cast<CastInst>(VL0); 7015 Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy); 7016 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7017 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7018 V = ShuffleBuilder.finalize(V); 7019 7020 E->VectorizedValue = V; 7021 ++NumVectorInstructions; 7022 return V; 7023 } 7024 case Instruction::FCmp: 7025 case Instruction::ICmp: { 7026 setInsertPointAfterBundle(E); 7027 7028 Value *L = vectorizeTree(E->getOperand(0)); 7029 Value *R = vectorizeTree(E->getOperand(1)); 7030 7031 if (E->VectorizedValue) { 7032 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7033 return E->VectorizedValue; 7034 } 7035 7036 CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate(); 7037 Value *V = Builder.CreateCmp(P0, L, R); 7038 propagateIRFlags(V, E->Scalars, VL0); 7039 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7040 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7041 V = ShuffleBuilder.finalize(V); 7042 7043 E->VectorizedValue = V; 7044 ++NumVectorInstructions; 7045 return V; 7046 } 7047 case Instruction::Select: { 7048 setInsertPointAfterBundle(E); 7049 7050 Value *Cond = vectorizeTree(E->getOperand(0)); 7051 Value *True = vectorizeTree(E->getOperand(1)); 7052 Value *False = vectorizeTree(E->getOperand(2)); 7053 7054 if (E->VectorizedValue) { 7055 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7056 return E->VectorizedValue; 7057 } 7058 7059 Value *V = Builder.CreateSelect(Cond, True, False); 7060 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7061 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7062 V = ShuffleBuilder.finalize(V); 7063 7064 E->VectorizedValue = V; 7065 ++NumVectorInstructions; 7066 return V; 7067 } 7068 case Instruction::FNeg: { 7069 setInsertPointAfterBundle(E); 7070 7071 Value *Op = vectorizeTree(E->getOperand(0)); 7072 7073 if (E->VectorizedValue) { 7074 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7075 return E->VectorizedValue; 7076 } 7077 7078 Value *V = Builder.CreateUnOp( 7079 static_cast<Instruction::UnaryOps>(E->getOpcode()), Op); 7080 propagateIRFlags(V, E->Scalars, VL0); 7081 if (auto *I = dyn_cast<Instruction>(V)) 7082 V = propagateMetadata(I, E->Scalars); 7083 7084 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7085 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7086 V = ShuffleBuilder.finalize(V); 7087 7088 E->VectorizedValue = V; 7089 ++NumVectorInstructions; 7090 7091 return V; 7092 } 7093 case Instruction::Add: 7094 case Instruction::FAdd: 7095 case Instruction::Sub: 7096 case Instruction::FSub: 7097 case Instruction::Mul: 7098 case Instruction::FMul: 7099 case Instruction::UDiv: 7100 case Instruction::SDiv: 7101 case Instruction::FDiv: 7102 case Instruction::URem: 7103 case Instruction::SRem: 7104 case Instruction::FRem: 7105 case Instruction::Shl: 7106 case Instruction::LShr: 7107 case Instruction::AShr: 7108 case Instruction::And: 7109 case Instruction::Or: 7110 case Instruction::Xor: { 7111 setInsertPointAfterBundle(E); 7112 7113 Value *LHS = vectorizeTree(E->getOperand(0)); 7114 Value *RHS = vectorizeTree(E->getOperand(1)); 7115 7116 if (E->VectorizedValue) { 7117 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7118 return E->VectorizedValue; 7119 } 7120 7121 Value *V = Builder.CreateBinOp( 7122 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, 7123 RHS); 7124 propagateIRFlags(V, E->Scalars, VL0); 7125 if (auto *I = dyn_cast<Instruction>(V)) 7126 V = propagateMetadata(I, E->Scalars); 7127 7128 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7129 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7130 V = ShuffleBuilder.finalize(V); 7131 7132 E->VectorizedValue = V; 7133 ++NumVectorInstructions; 7134 7135 return V; 7136 } 7137 case Instruction::Load: { 7138 // Loads are inserted at the head of the tree because we don't want to 7139 // sink them all the way down past store instructions. 7140 setInsertPointAfterBundle(E); 7141 7142 LoadInst *LI = cast<LoadInst>(VL0); 7143 Instruction *NewLI; 7144 unsigned AS = LI->getPointerAddressSpace(); 7145 Value *PO = LI->getPointerOperand(); 7146 if (E->State == TreeEntry::Vectorize) { 7147 Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS)); 7148 NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign()); 7149 7150 // The pointer operand uses an in-tree scalar so we add the new BitCast 7151 // or LoadInst to ExternalUses list to make sure that an extract will 7152 // be generated in the future. 7153 if (TreeEntry *Entry = getTreeEntry(PO)) { 7154 // Find which lane we need to extract. 7155 unsigned FoundLane = Entry->findLaneForValue(PO); 7156 ExternalUses.emplace_back( 7157 PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane); 7158 } 7159 } else { 7160 assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state"); 7161 Value *VecPtr = vectorizeTree(E->getOperand(0)); 7162 // Use the minimum alignment of the gathered loads. 7163 Align CommonAlignment = LI->getAlign(); 7164 for (Value *V : E->Scalars) 7165 CommonAlignment = 7166 commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign()); 7167 NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment); 7168 } 7169 Value *V = propagateMetadata(NewLI, E->Scalars); 7170 7171 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7172 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7173 V = ShuffleBuilder.finalize(V); 7174 E->VectorizedValue = V; 7175 ++NumVectorInstructions; 7176 return V; 7177 } 7178 case Instruction::Store: { 7179 auto *SI = cast<StoreInst>(VL0); 7180 unsigned AS = SI->getPointerAddressSpace(); 7181 7182 setInsertPointAfterBundle(E); 7183 7184 Value *VecValue = vectorizeTree(E->getOperand(0)); 7185 ShuffleBuilder.addMask(E->ReorderIndices); 7186 VecValue = ShuffleBuilder.finalize(VecValue); 7187 7188 Value *ScalarPtr = SI->getPointerOperand(); 7189 Value *VecPtr = Builder.CreateBitCast( 7190 ScalarPtr, VecValue->getType()->getPointerTo(AS)); 7191 StoreInst *ST = 7192 Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign()); 7193 7194 // The pointer operand uses an in-tree scalar, so add the new BitCast or 7195 // StoreInst to ExternalUses to make sure that an extract will be 7196 // generated in the future. 7197 if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) { 7198 // Find which lane we need to extract. 7199 unsigned FoundLane = Entry->findLaneForValue(ScalarPtr); 7200 ExternalUses.push_back(ExternalUser( 7201 ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST, 7202 FoundLane)); 7203 } 7204 7205 Value *V = propagateMetadata(ST, E->Scalars); 7206 7207 E->VectorizedValue = V; 7208 ++NumVectorInstructions; 7209 return V; 7210 } 7211 case Instruction::GetElementPtr: { 7212 auto *GEP0 = cast<GetElementPtrInst>(VL0); 7213 setInsertPointAfterBundle(E); 7214 7215 Value *Op0 = vectorizeTree(E->getOperand(0)); 7216 7217 SmallVector<Value *> OpVecs; 7218 for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) { 7219 Value *OpVec = vectorizeTree(E->getOperand(J)); 7220 OpVecs.push_back(OpVec); 7221 } 7222 7223 Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs); 7224 if (Instruction *I = dyn_cast<Instruction>(V)) 7225 V = propagateMetadata(I, E->Scalars); 7226 7227 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7228 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7229 V = ShuffleBuilder.finalize(V); 7230 7231 E->VectorizedValue = V; 7232 ++NumVectorInstructions; 7233 7234 return V; 7235 } 7236 case Instruction::Call: { 7237 CallInst *CI = cast<CallInst>(VL0); 7238 setInsertPointAfterBundle(E); 7239 7240 Intrinsic::ID IID = Intrinsic::not_intrinsic; 7241 if (Function *FI = CI->getCalledFunction()) 7242 IID = FI->getIntrinsicID(); 7243 7244 Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI); 7245 7246 auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI); 7247 bool UseIntrinsic = ID != Intrinsic::not_intrinsic && 7248 VecCallCosts.first <= VecCallCosts.second; 7249 7250 Value *ScalarArg = nullptr; 7251 std::vector<Value *> OpVecs; 7252 SmallVector<Type *, 2> TysForDecl = 7253 {FixedVectorType::get(CI->getType(), E->Scalars.size())}; 7254 for (int j = 0, e = CI->arg_size(); j < e; ++j) { 7255 ValueList OpVL; 7256 // Some intrinsics have scalar arguments. This argument should not be 7257 // vectorized. 7258 if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) { 7259 CallInst *CEI = cast<CallInst>(VL0); 7260 ScalarArg = CEI->getArgOperand(j); 7261 OpVecs.push_back(CEI->getArgOperand(j)); 7262 if (hasVectorInstrinsicOverloadedScalarOpd(IID, j)) 7263 TysForDecl.push_back(ScalarArg->getType()); 7264 continue; 7265 } 7266 7267 Value *OpVec = vectorizeTree(E->getOperand(j)); 7268 LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n"); 7269 OpVecs.push_back(OpVec); 7270 } 7271 7272 Function *CF; 7273 if (!UseIntrinsic) { 7274 VFShape Shape = 7275 VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>( 7276 VecTy->getNumElements())), 7277 false /*HasGlobalPred*/); 7278 CF = VFDatabase(*CI).getVectorizedFunction(Shape); 7279 } else { 7280 CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl); 7281 } 7282 7283 SmallVector<OperandBundleDef, 1> OpBundles; 7284 CI->getOperandBundlesAsDefs(OpBundles); 7285 Value *V = Builder.CreateCall(CF, OpVecs, OpBundles); 7286 7287 // The scalar argument uses an in-tree scalar so we add the new vectorized 7288 // call to ExternalUses list to make sure that an extract will be 7289 // generated in the future. 7290 if (ScalarArg) { 7291 if (TreeEntry *Entry = getTreeEntry(ScalarArg)) { 7292 // Find which lane we need to extract. 7293 unsigned FoundLane = Entry->findLaneForValue(ScalarArg); 7294 ExternalUses.push_back( 7295 ExternalUser(ScalarArg, cast<User>(V), FoundLane)); 7296 } 7297 } 7298 7299 propagateIRFlags(V, E->Scalars, VL0); 7300 ShuffleBuilder.addInversedMask(E->ReorderIndices); 7301 ShuffleBuilder.addMask(E->ReuseShuffleIndices); 7302 V = ShuffleBuilder.finalize(V); 7303 7304 E->VectorizedValue = V; 7305 ++NumVectorInstructions; 7306 return V; 7307 } 7308 case Instruction::ShuffleVector: { 7309 assert(E->isAltShuffle() && 7310 ((Instruction::isBinaryOp(E->getOpcode()) && 7311 Instruction::isBinaryOp(E->getAltOpcode())) || 7312 (Instruction::isCast(E->getOpcode()) && 7313 Instruction::isCast(E->getAltOpcode())) || 7314 (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) && 7315 "Invalid Shuffle Vector Operand"); 7316 7317 Value *LHS = nullptr, *RHS = nullptr; 7318 if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) { 7319 setInsertPointAfterBundle(E); 7320 LHS = vectorizeTree(E->getOperand(0)); 7321 RHS = vectorizeTree(E->getOperand(1)); 7322 } else { 7323 setInsertPointAfterBundle(E); 7324 LHS = vectorizeTree(E->getOperand(0)); 7325 } 7326 7327 if (E->VectorizedValue) { 7328 LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n"); 7329 return E->VectorizedValue; 7330 } 7331 7332 Value *V0, *V1; 7333 if (Instruction::isBinaryOp(E->getOpcode())) { 7334 V0 = Builder.CreateBinOp( 7335 static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS); 7336 V1 = Builder.CreateBinOp( 7337 static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS); 7338 } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) { 7339 V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS); 7340 auto *AltCI = cast<CmpInst>(E->getAltOp()); 7341 CmpInst::Predicate AltPred = AltCI->getPredicate(); 7342 V1 = Builder.CreateCmp(AltPred, LHS, RHS); 7343 } else { 7344 V0 = Builder.CreateCast( 7345 static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy); 7346 V1 = Builder.CreateCast( 7347 static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy); 7348 } 7349 // Add V0 and V1 to later analysis to try to find and remove matching 7350 // instruction, if any. 7351 for (Value *V : {V0, V1}) { 7352 if (auto *I = dyn_cast<Instruction>(V)) { 7353 GatherShuffleSeq.insert(I); 7354 CSEBlocks.insert(I->getParent()); 7355 } 7356 } 7357 7358 // Create shuffle to take alternate operations from the vector. 7359 // Also, gather up main and alt scalar ops to propagate IR flags to 7360 // each vector operation. 7361 ValueList OpScalars, AltScalars; 7362 SmallVector<int> Mask; 7363 buildShuffleEntryMask( 7364 E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices, 7365 [E](Instruction *I) { 7366 assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode"); 7367 return isAlternateInstruction(I, E->getMainOp(), E->getAltOp()); 7368 }, 7369 Mask, &OpScalars, &AltScalars); 7370 7371 propagateIRFlags(V0, OpScalars); 7372 propagateIRFlags(V1, AltScalars); 7373 7374 Value *V = Builder.CreateShuffleVector(V0, V1, Mask); 7375 if (auto *I = dyn_cast<Instruction>(V)) { 7376 V = propagateMetadata(I, E->Scalars); 7377 GatherShuffleSeq.insert(I); 7378 CSEBlocks.insert(I->getParent()); 7379 } 7380 V = ShuffleBuilder.finalize(V); 7381 7382 E->VectorizedValue = V; 7383 ++NumVectorInstructions; 7384 7385 return V; 7386 } 7387 default: 7388 llvm_unreachable("unknown inst"); 7389 } 7390 return nullptr; 7391 } 7392 7393 Value *BoUpSLP::vectorizeTree() { 7394 ExtraValueToDebugLocsMap ExternallyUsedValues; 7395 return vectorizeTree(ExternallyUsedValues); 7396 } 7397 7398 Value * 7399 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) { 7400 // All blocks must be scheduled before any instructions are inserted. 7401 for (auto &BSIter : BlocksSchedules) { 7402 scheduleBlock(BSIter.second.get()); 7403 } 7404 7405 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7406 auto *VectorRoot = vectorizeTree(VectorizableTree[0].get()); 7407 7408 // If the vectorized tree can be rewritten in a smaller type, we truncate the 7409 // vectorized root. InstCombine will then rewrite the entire expression. We 7410 // sign extend the extracted values below. 7411 auto *ScalarRoot = VectorizableTree[0]->Scalars[0]; 7412 if (MinBWs.count(ScalarRoot)) { 7413 if (auto *I = dyn_cast<Instruction>(VectorRoot)) { 7414 // If current instr is a phi and not the last phi, insert it after the 7415 // last phi node. 7416 if (isa<PHINode>(I)) 7417 Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt()); 7418 else 7419 Builder.SetInsertPoint(&*++BasicBlock::iterator(I)); 7420 } 7421 auto BundleWidth = VectorizableTree[0]->Scalars.size(); 7422 auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first); 7423 auto *VecTy = FixedVectorType::get(MinTy, BundleWidth); 7424 auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy); 7425 VectorizableTree[0]->VectorizedValue = Trunc; 7426 } 7427 7428 LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() 7429 << " values .\n"); 7430 7431 // Extract all of the elements with the external uses. 7432 for (const auto &ExternalUse : ExternalUses) { 7433 Value *Scalar = ExternalUse.Scalar; 7434 llvm::User *User = ExternalUse.User; 7435 7436 // Skip users that we already RAUW. This happens when one instruction 7437 // has multiple uses of the same value. 7438 if (User && !is_contained(Scalar->users(), User)) 7439 continue; 7440 TreeEntry *E = getTreeEntry(Scalar); 7441 assert(E && "Invalid scalar"); 7442 assert(E->State != TreeEntry::NeedToGather && 7443 "Extracting from a gather list"); 7444 7445 Value *Vec = E->VectorizedValue; 7446 assert(Vec && "Can't find vectorizable value"); 7447 7448 Value *Lane = Builder.getInt32(ExternalUse.Lane); 7449 auto ExtractAndExtendIfNeeded = [&](Value *Vec) { 7450 if (Scalar->getType() != Vec->getType()) { 7451 Value *Ex; 7452 // "Reuse" the existing extract to improve final codegen. 7453 if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) { 7454 Ex = Builder.CreateExtractElement(ES->getOperand(0), 7455 ES->getOperand(1)); 7456 } else { 7457 Ex = Builder.CreateExtractElement(Vec, Lane); 7458 } 7459 // If necessary, sign-extend or zero-extend ScalarRoot 7460 // to the larger type. 7461 if (!MinBWs.count(ScalarRoot)) 7462 return Ex; 7463 if (MinBWs[ScalarRoot].second) 7464 return Builder.CreateSExt(Ex, Scalar->getType()); 7465 return Builder.CreateZExt(Ex, Scalar->getType()); 7466 } 7467 assert(isa<FixedVectorType>(Scalar->getType()) && 7468 isa<InsertElementInst>(Scalar) && 7469 "In-tree scalar of vector type is not insertelement?"); 7470 return Vec; 7471 }; 7472 // If User == nullptr, the Scalar is used as extra arg. Generate 7473 // ExtractElement instruction and update the record for this scalar in 7474 // ExternallyUsedValues. 7475 if (!User) { 7476 assert(ExternallyUsedValues.count(Scalar) && 7477 "Scalar with nullptr as an external user must be registered in " 7478 "ExternallyUsedValues map"); 7479 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 7480 Builder.SetInsertPoint(VecI->getParent(), 7481 std::next(VecI->getIterator())); 7482 } else { 7483 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7484 } 7485 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7486 CSEBlocks.insert(cast<Instruction>(Scalar)->getParent()); 7487 auto &NewInstLocs = ExternallyUsedValues[NewInst]; 7488 auto It = ExternallyUsedValues.find(Scalar); 7489 assert(It != ExternallyUsedValues.end() && 7490 "Externally used scalar is not found in ExternallyUsedValues"); 7491 NewInstLocs.append(It->second); 7492 ExternallyUsedValues.erase(Scalar); 7493 // Required to update internally referenced instructions. 7494 Scalar->replaceAllUsesWith(NewInst); 7495 continue; 7496 } 7497 7498 // Generate extracts for out-of-tree users. 7499 // Find the insertion point for the extractelement lane. 7500 if (auto *VecI = dyn_cast<Instruction>(Vec)) { 7501 if (PHINode *PH = dyn_cast<PHINode>(User)) { 7502 for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) { 7503 if (PH->getIncomingValue(i) == Scalar) { 7504 Instruction *IncomingTerminator = 7505 PH->getIncomingBlock(i)->getTerminator(); 7506 if (isa<CatchSwitchInst>(IncomingTerminator)) { 7507 Builder.SetInsertPoint(VecI->getParent(), 7508 std::next(VecI->getIterator())); 7509 } else { 7510 Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator()); 7511 } 7512 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7513 CSEBlocks.insert(PH->getIncomingBlock(i)); 7514 PH->setOperand(i, NewInst); 7515 } 7516 } 7517 } else { 7518 Builder.SetInsertPoint(cast<Instruction>(User)); 7519 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7520 CSEBlocks.insert(cast<Instruction>(User)->getParent()); 7521 User->replaceUsesOfWith(Scalar, NewInst); 7522 } 7523 } else { 7524 Builder.SetInsertPoint(&F->getEntryBlock().front()); 7525 Value *NewInst = ExtractAndExtendIfNeeded(Vec); 7526 CSEBlocks.insert(&F->getEntryBlock()); 7527 User->replaceUsesOfWith(Scalar, NewInst); 7528 } 7529 7530 LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n"); 7531 } 7532 7533 // For each vectorized value: 7534 for (auto &TEPtr : VectorizableTree) { 7535 TreeEntry *Entry = TEPtr.get(); 7536 7537 // No need to handle users of gathered values. 7538 if (Entry->State == TreeEntry::NeedToGather) 7539 continue; 7540 7541 assert(Entry->VectorizedValue && "Can't find vectorizable value"); 7542 7543 // For each lane: 7544 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) { 7545 Value *Scalar = Entry->Scalars[Lane]; 7546 7547 #ifndef NDEBUG 7548 Type *Ty = Scalar->getType(); 7549 if (!Ty->isVoidTy()) { 7550 for (User *U : Scalar->users()) { 7551 LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n"); 7552 7553 // It is legal to delete users in the ignorelist. 7554 assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) || 7555 (isa_and_nonnull<Instruction>(U) && 7556 isDeleted(cast<Instruction>(U)))) && 7557 "Deleting out-of-tree value"); 7558 } 7559 } 7560 #endif 7561 LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n"); 7562 eraseInstruction(cast<Instruction>(Scalar)); 7563 } 7564 } 7565 7566 Builder.ClearInsertionPoint(); 7567 InstrElementSize.clear(); 7568 7569 return VectorizableTree[0]->VectorizedValue; 7570 } 7571 7572 void BoUpSLP::optimizeGatherSequence() { 7573 LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size() 7574 << " gather sequences instructions.\n"); 7575 // LICM InsertElementInst sequences. 7576 for (Instruction *I : GatherShuffleSeq) { 7577 if (isDeleted(I)) 7578 continue; 7579 7580 // Check if this block is inside a loop. 7581 Loop *L = LI->getLoopFor(I->getParent()); 7582 if (!L) 7583 continue; 7584 7585 // Check if it has a preheader. 7586 BasicBlock *PreHeader = L->getLoopPreheader(); 7587 if (!PreHeader) 7588 continue; 7589 7590 // If the vector or the element that we insert into it are 7591 // instructions that are defined in this basic block then we can't 7592 // hoist this instruction. 7593 if (any_of(I->operands(), [L](Value *V) { 7594 auto *OpI = dyn_cast<Instruction>(V); 7595 return OpI && L->contains(OpI); 7596 })) 7597 continue; 7598 7599 // We can hoist this instruction. Move it to the pre-header. 7600 I->moveBefore(PreHeader->getTerminator()); 7601 } 7602 7603 // Make a list of all reachable blocks in our CSE queue. 7604 SmallVector<const DomTreeNode *, 8> CSEWorkList; 7605 CSEWorkList.reserve(CSEBlocks.size()); 7606 for (BasicBlock *BB : CSEBlocks) 7607 if (DomTreeNode *N = DT->getNode(BB)) { 7608 assert(DT->isReachableFromEntry(N)); 7609 CSEWorkList.push_back(N); 7610 } 7611 7612 // Sort blocks by domination. This ensures we visit a block after all blocks 7613 // dominating it are visited. 7614 llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) { 7615 assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) && 7616 "Different nodes should have different DFS numbers"); 7617 return A->getDFSNumIn() < B->getDFSNumIn(); 7618 }); 7619 7620 // Less defined shuffles can be replaced by the more defined copies. 7621 // Between two shuffles one is less defined if it has the same vector operands 7622 // and its mask indeces are the same as in the first one or undefs. E.g. 7623 // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0, 7624 // poison, <0, 0, 0, 0>. 7625 auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2, 7626 SmallVectorImpl<int> &NewMask) { 7627 if (I1->getType() != I2->getType()) 7628 return false; 7629 auto *SI1 = dyn_cast<ShuffleVectorInst>(I1); 7630 auto *SI2 = dyn_cast<ShuffleVectorInst>(I2); 7631 if (!SI1 || !SI2) 7632 return I1->isIdenticalTo(I2); 7633 if (SI1->isIdenticalTo(SI2)) 7634 return true; 7635 for (int I = 0, E = SI1->getNumOperands(); I < E; ++I) 7636 if (SI1->getOperand(I) != SI2->getOperand(I)) 7637 return false; 7638 // Check if the second instruction is more defined than the first one. 7639 NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end()); 7640 ArrayRef<int> SM1 = SI1->getShuffleMask(); 7641 // Count trailing undefs in the mask to check the final number of used 7642 // registers. 7643 unsigned LastUndefsCnt = 0; 7644 for (int I = 0, E = NewMask.size(); I < E; ++I) { 7645 if (SM1[I] == UndefMaskElem) 7646 ++LastUndefsCnt; 7647 else 7648 LastUndefsCnt = 0; 7649 if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem && 7650 NewMask[I] != SM1[I]) 7651 return false; 7652 if (NewMask[I] == UndefMaskElem) 7653 NewMask[I] = SM1[I]; 7654 } 7655 // Check if the last undefs actually change the final number of used vector 7656 // registers. 7657 return SM1.size() - LastUndefsCnt > 1 && 7658 TTI->getNumberOfParts(SI1->getType()) == 7659 TTI->getNumberOfParts( 7660 FixedVectorType::get(SI1->getType()->getElementType(), 7661 SM1.size() - LastUndefsCnt)); 7662 }; 7663 // Perform O(N^2) search over the gather/shuffle sequences and merge identical 7664 // instructions. TODO: We can further optimize this scan if we split the 7665 // instructions into different buckets based on the insert lane. 7666 SmallVector<Instruction *, 16> Visited; 7667 for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) { 7668 assert(*I && 7669 (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) && 7670 "Worklist not sorted properly!"); 7671 BasicBlock *BB = (*I)->getBlock(); 7672 // For all instructions in blocks containing gather sequences: 7673 for (Instruction &In : llvm::make_early_inc_range(*BB)) { 7674 if (isDeleted(&In)) 7675 continue; 7676 if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) && 7677 !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In)) 7678 continue; 7679 7680 // Check if we can replace this instruction with any of the 7681 // visited instructions. 7682 bool Replaced = false; 7683 for (Instruction *&V : Visited) { 7684 SmallVector<int> NewMask; 7685 if (IsIdenticalOrLessDefined(&In, V, NewMask) && 7686 DT->dominates(V->getParent(), In.getParent())) { 7687 In.replaceAllUsesWith(V); 7688 eraseInstruction(&In); 7689 if (auto *SI = dyn_cast<ShuffleVectorInst>(V)) 7690 if (!NewMask.empty()) 7691 SI->setShuffleMask(NewMask); 7692 Replaced = true; 7693 break; 7694 } 7695 if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) && 7696 GatherShuffleSeq.contains(V) && 7697 IsIdenticalOrLessDefined(V, &In, NewMask) && 7698 DT->dominates(In.getParent(), V->getParent())) { 7699 In.moveAfter(V); 7700 V->replaceAllUsesWith(&In); 7701 eraseInstruction(V); 7702 if (auto *SI = dyn_cast<ShuffleVectorInst>(&In)) 7703 if (!NewMask.empty()) 7704 SI->setShuffleMask(NewMask); 7705 V = &In; 7706 Replaced = true; 7707 break; 7708 } 7709 } 7710 if (!Replaced) { 7711 assert(!is_contained(Visited, &In)); 7712 Visited.push_back(&In); 7713 } 7714 } 7715 } 7716 CSEBlocks.clear(); 7717 GatherShuffleSeq.clear(); 7718 } 7719 7720 BoUpSLP::ScheduleData * 7721 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) { 7722 ScheduleData *Bundle = nullptr; 7723 ScheduleData *PrevInBundle = nullptr; 7724 for (Value *V : VL) { 7725 if (doesNotNeedToBeScheduled(V)) 7726 continue; 7727 ScheduleData *BundleMember = getScheduleData(V); 7728 assert(BundleMember && 7729 "no ScheduleData for bundle member " 7730 "(maybe not in same basic block)"); 7731 assert(BundleMember->isSchedulingEntity() && 7732 "bundle member already part of other bundle"); 7733 if (PrevInBundle) { 7734 PrevInBundle->NextInBundle = BundleMember; 7735 } else { 7736 Bundle = BundleMember; 7737 } 7738 7739 // Group the instructions to a bundle. 7740 BundleMember->FirstInBundle = Bundle; 7741 PrevInBundle = BundleMember; 7742 } 7743 assert(Bundle && "Failed to find schedule bundle"); 7744 return Bundle; 7745 } 7746 7747 // Groups the instructions to a bundle (which is then a single scheduling entity) 7748 // and schedules instructions until the bundle gets ready. 7749 Optional<BoUpSLP::ScheduleData *> 7750 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP, 7751 const InstructionsState &S) { 7752 // No need to schedule PHIs, insertelement, extractelement and extractvalue 7753 // instructions. 7754 if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) || 7755 doesNotNeedToSchedule(VL)) 7756 return nullptr; 7757 7758 // Initialize the instruction bundle. 7759 Instruction *OldScheduleEnd = ScheduleEnd; 7760 LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n"); 7761 7762 auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule, 7763 ScheduleData *Bundle) { 7764 // The scheduling region got new instructions at the lower end (or it is a 7765 // new region for the first bundle). This makes it necessary to 7766 // recalculate all dependencies. 7767 // It is seldom that this needs to be done a second time after adding the 7768 // initial bundle to the region. 7769 if (ScheduleEnd != OldScheduleEnd) { 7770 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) 7771 doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); }); 7772 ReSchedule = true; 7773 } 7774 if (Bundle) { 7775 LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle 7776 << " in block " << BB->getName() << "\n"); 7777 calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP); 7778 } 7779 7780 if (ReSchedule) { 7781 resetSchedule(); 7782 initialFillReadyList(ReadyInsts); 7783 } 7784 7785 // Now try to schedule the new bundle or (if no bundle) just calculate 7786 // dependencies. As soon as the bundle is "ready" it means that there are no 7787 // cyclic dependencies and we can schedule it. Note that's important that we 7788 // don't "schedule" the bundle yet (see cancelScheduling). 7789 while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) && 7790 !ReadyInsts.empty()) { 7791 ScheduleData *Picked = ReadyInsts.pop_back_val(); 7792 assert(Picked->isSchedulingEntity() && Picked->isReady() && 7793 "must be ready to schedule"); 7794 schedule(Picked, ReadyInsts); 7795 } 7796 }; 7797 7798 // Make sure that the scheduling region contains all 7799 // instructions of the bundle. 7800 for (Value *V : VL) { 7801 if (doesNotNeedToBeScheduled(V)) 7802 continue; 7803 if (!extendSchedulingRegion(V, S)) { 7804 // If the scheduling region got new instructions at the lower end (or it 7805 // is a new region for the first bundle). This makes it necessary to 7806 // recalculate all dependencies. 7807 // Otherwise the compiler may crash trying to incorrectly calculate 7808 // dependencies and emit instruction in the wrong order at the actual 7809 // scheduling. 7810 TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr); 7811 return None; 7812 } 7813 } 7814 7815 bool ReSchedule = false; 7816 for (Value *V : VL) { 7817 if (doesNotNeedToBeScheduled(V)) 7818 continue; 7819 ScheduleData *BundleMember = getScheduleData(V); 7820 assert(BundleMember && 7821 "no ScheduleData for bundle member (maybe not in same basic block)"); 7822 7823 // Make sure we don't leave the pieces of the bundle in the ready list when 7824 // whole bundle might not be ready. 7825 ReadyInsts.remove(BundleMember); 7826 7827 if (!BundleMember->IsScheduled) 7828 continue; 7829 // A bundle member was scheduled as single instruction before and now 7830 // needs to be scheduled as part of the bundle. We just get rid of the 7831 // existing schedule. 7832 LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember 7833 << " was already scheduled\n"); 7834 ReSchedule = true; 7835 } 7836 7837 auto *Bundle = buildBundle(VL); 7838 TryScheduleBundleImpl(ReSchedule, Bundle); 7839 if (!Bundle->isReady()) { 7840 cancelScheduling(VL, S.OpValue); 7841 return None; 7842 } 7843 return Bundle; 7844 } 7845 7846 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL, 7847 Value *OpValue) { 7848 if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) || 7849 doesNotNeedToSchedule(VL)) 7850 return; 7851 7852 if (doesNotNeedToBeScheduled(OpValue)) 7853 OpValue = *find_if_not(VL, doesNotNeedToBeScheduled); 7854 ScheduleData *Bundle = getScheduleData(OpValue); 7855 LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n"); 7856 assert(!Bundle->IsScheduled && 7857 "Can't cancel bundle which is already scheduled"); 7858 assert(Bundle->isSchedulingEntity() && 7859 (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) && 7860 "tried to unbundle something which is not a bundle"); 7861 7862 // Remove the bundle from the ready list. 7863 if (Bundle->isReady()) 7864 ReadyInsts.remove(Bundle); 7865 7866 // Un-bundle: make single instructions out of the bundle. 7867 ScheduleData *BundleMember = Bundle; 7868 while (BundleMember) { 7869 assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links"); 7870 BundleMember->FirstInBundle = BundleMember; 7871 ScheduleData *Next = BundleMember->NextInBundle; 7872 BundleMember->NextInBundle = nullptr; 7873 BundleMember->TE = nullptr; 7874 if (BundleMember->unscheduledDepsInBundle() == 0) { 7875 ReadyInsts.insert(BundleMember); 7876 } 7877 BundleMember = Next; 7878 } 7879 } 7880 7881 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() { 7882 // Allocate a new ScheduleData for the instruction. 7883 if (ChunkPos >= ChunkSize) { 7884 ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize)); 7885 ChunkPos = 0; 7886 } 7887 return &(ScheduleDataChunks.back()[ChunkPos++]); 7888 } 7889 7890 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V, 7891 const InstructionsState &S) { 7892 if (getScheduleData(V, isOneOf(S, V))) 7893 return true; 7894 Instruction *I = dyn_cast<Instruction>(V); 7895 assert(I && "bundle member must be an instruction"); 7896 assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) && 7897 !doesNotNeedToBeScheduled(I) && 7898 "phi nodes/insertelements/extractelements/extractvalues don't need to " 7899 "be scheduled"); 7900 auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool { 7901 ScheduleData *ISD = getScheduleData(I); 7902 if (!ISD) 7903 return false; 7904 assert(isInSchedulingRegion(ISD) && 7905 "ScheduleData not in scheduling region"); 7906 ScheduleData *SD = allocateScheduleDataChunks(); 7907 SD->Inst = I; 7908 SD->init(SchedulingRegionID, S.OpValue); 7909 ExtraScheduleDataMap[I][S.OpValue] = SD; 7910 return true; 7911 }; 7912 if (CheckScheduleForI(I)) 7913 return true; 7914 if (!ScheduleStart) { 7915 // It's the first instruction in the new region. 7916 initScheduleData(I, I->getNextNode(), nullptr, nullptr); 7917 ScheduleStart = I; 7918 ScheduleEnd = I->getNextNode(); 7919 if (isOneOf(S, I) != I) 7920 CheckScheduleForI(I); 7921 assert(ScheduleEnd && "tried to vectorize a terminator?"); 7922 LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n"); 7923 return true; 7924 } 7925 // Search up and down at the same time, because we don't know if the new 7926 // instruction is above or below the existing scheduling region. 7927 BasicBlock::reverse_iterator UpIter = 7928 ++ScheduleStart->getIterator().getReverse(); 7929 BasicBlock::reverse_iterator UpperEnd = BB->rend(); 7930 BasicBlock::iterator DownIter = ScheduleEnd->getIterator(); 7931 BasicBlock::iterator LowerEnd = BB->end(); 7932 while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I && 7933 &*DownIter != I) { 7934 if (++ScheduleRegionSize > ScheduleRegionSizeLimit) { 7935 LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n"); 7936 return false; 7937 } 7938 7939 ++UpIter; 7940 ++DownIter; 7941 } 7942 if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) { 7943 assert(I->getParent() == ScheduleStart->getParent() && 7944 "Instruction is in wrong basic block."); 7945 initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion); 7946 ScheduleStart = I; 7947 if (isOneOf(S, I) != I) 7948 CheckScheduleForI(I); 7949 LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I 7950 << "\n"); 7951 return true; 7952 } 7953 assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) && 7954 "Expected to reach top of the basic block or instruction down the " 7955 "lower end."); 7956 assert(I->getParent() == ScheduleEnd->getParent() && 7957 "Instruction is in wrong basic block."); 7958 initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion, 7959 nullptr); 7960 ScheduleEnd = I->getNextNode(); 7961 if (isOneOf(S, I) != I) 7962 CheckScheduleForI(I); 7963 assert(ScheduleEnd && "tried to vectorize a terminator?"); 7964 LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n"); 7965 return true; 7966 } 7967 7968 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI, 7969 Instruction *ToI, 7970 ScheduleData *PrevLoadStore, 7971 ScheduleData *NextLoadStore) { 7972 ScheduleData *CurrentLoadStore = PrevLoadStore; 7973 for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) { 7974 // No need to allocate data for non-schedulable instructions. 7975 if (doesNotNeedToBeScheduled(I)) 7976 continue; 7977 ScheduleData *SD = ScheduleDataMap.lookup(I); 7978 if (!SD) { 7979 SD = allocateScheduleDataChunks(); 7980 ScheduleDataMap[I] = SD; 7981 SD->Inst = I; 7982 } 7983 assert(!isInSchedulingRegion(SD) && 7984 "new ScheduleData already in scheduling region"); 7985 SD->init(SchedulingRegionID, I); 7986 7987 if (I->mayReadOrWriteMemory() && 7988 (!isa<IntrinsicInst>(I) || 7989 (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect && 7990 cast<IntrinsicInst>(I)->getIntrinsicID() != 7991 Intrinsic::pseudoprobe))) { 7992 // Update the linked list of memory accessing instructions. 7993 if (CurrentLoadStore) { 7994 CurrentLoadStore->NextLoadStore = SD; 7995 } else { 7996 FirstLoadStoreInRegion = SD; 7997 } 7998 CurrentLoadStore = SD; 7999 } 8000 } 8001 if (NextLoadStore) { 8002 if (CurrentLoadStore) 8003 CurrentLoadStore->NextLoadStore = NextLoadStore; 8004 } else { 8005 LastLoadStoreInRegion = CurrentLoadStore; 8006 } 8007 } 8008 8009 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD, 8010 bool InsertInReadyList, 8011 BoUpSLP *SLP) { 8012 assert(SD->isSchedulingEntity()); 8013 8014 SmallVector<ScheduleData *, 10> WorkList; 8015 WorkList.push_back(SD); 8016 8017 while (!WorkList.empty()) { 8018 ScheduleData *SD = WorkList.pop_back_val(); 8019 for (ScheduleData *BundleMember = SD; BundleMember; 8020 BundleMember = BundleMember->NextInBundle) { 8021 assert(isInSchedulingRegion(BundleMember)); 8022 if (BundleMember->hasValidDependencies()) 8023 continue; 8024 8025 LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember 8026 << "\n"); 8027 BundleMember->Dependencies = 0; 8028 BundleMember->resetUnscheduledDeps(); 8029 8030 // Handle def-use chain dependencies. 8031 if (BundleMember->OpValue != BundleMember->Inst) { 8032 if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) { 8033 BundleMember->Dependencies++; 8034 ScheduleData *DestBundle = UseSD->FirstInBundle; 8035 if (!DestBundle->IsScheduled) 8036 BundleMember->incrementUnscheduledDeps(1); 8037 if (!DestBundle->hasValidDependencies()) 8038 WorkList.push_back(DestBundle); 8039 } 8040 } else { 8041 for (User *U : BundleMember->Inst->users()) { 8042 if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) { 8043 BundleMember->Dependencies++; 8044 ScheduleData *DestBundle = UseSD->FirstInBundle; 8045 if (!DestBundle->IsScheduled) 8046 BundleMember->incrementUnscheduledDeps(1); 8047 if (!DestBundle->hasValidDependencies()) 8048 WorkList.push_back(DestBundle); 8049 } 8050 } 8051 } 8052 8053 // Any instruction which isn't safe to speculate at the begining of the 8054 // block is control dependend on any early exit or non-willreturn call 8055 // which proceeds it. 8056 if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) { 8057 for (Instruction *I = BundleMember->Inst->getNextNode(); 8058 I != ScheduleEnd; I = I->getNextNode()) { 8059 if (isSafeToSpeculativelyExecute(I, &*BB->begin())) 8060 continue; 8061 8062 // Add the dependency 8063 auto *DepDest = getScheduleData(I); 8064 assert(DepDest && "must be in schedule window"); 8065 DepDest->ControlDependencies.push_back(BundleMember); 8066 BundleMember->Dependencies++; 8067 ScheduleData *DestBundle = DepDest->FirstInBundle; 8068 if (!DestBundle->IsScheduled) 8069 BundleMember->incrementUnscheduledDeps(1); 8070 if (!DestBundle->hasValidDependencies()) 8071 WorkList.push_back(DestBundle); 8072 8073 if (!isGuaranteedToTransferExecutionToSuccessor(I)) 8074 // Everything past here must be control dependent on I. 8075 break; 8076 } 8077 } 8078 8079 // If we have an inalloc alloca instruction, it needs to be scheduled 8080 // after any preceeding stacksave. 8081 if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>())) { 8082 for (Instruction *I = BundleMember->Inst->getNextNode(); 8083 I != ScheduleEnd; I = I->getNextNode()) { 8084 if (match(I, m_Intrinsic<Intrinsic::stacksave>())) 8085 // Any allocas past here must be control dependent on I, and I 8086 // must be memory dependend on BundleMember->Inst. 8087 break; 8088 8089 if (!isa<AllocaInst>(I)) 8090 continue; 8091 8092 // Add the dependency 8093 auto *DepDest = getScheduleData(I); 8094 assert(DepDest && "must be in schedule window"); 8095 DepDest->ControlDependencies.push_back(BundleMember); 8096 BundleMember->Dependencies++; 8097 ScheduleData *DestBundle = DepDest->FirstInBundle; 8098 if (!DestBundle->IsScheduled) 8099 BundleMember->incrementUnscheduledDeps(1); 8100 if (!DestBundle->hasValidDependencies()) 8101 WorkList.push_back(DestBundle); 8102 } 8103 } 8104 8105 8106 // Handle the memory dependencies (if any). 8107 ScheduleData *DepDest = BundleMember->NextLoadStore; 8108 if (!DepDest) 8109 continue; 8110 Instruction *SrcInst = BundleMember->Inst; 8111 assert(SrcInst->mayReadOrWriteMemory() && 8112 "NextLoadStore list for non memory effecting bundle?"); 8113 MemoryLocation SrcLoc = getLocation(SrcInst); 8114 bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory(); 8115 unsigned numAliased = 0; 8116 unsigned DistToSrc = 1; 8117 8118 for ( ; DepDest; DepDest = DepDest->NextLoadStore) { 8119 assert(isInSchedulingRegion(DepDest)); 8120 8121 // We have two limits to reduce the complexity: 8122 // 1) AliasedCheckLimit: It's a small limit to reduce calls to 8123 // SLP->isAliased (which is the expensive part in this loop). 8124 // 2) MaxMemDepDistance: It's for very large blocks and it aborts 8125 // the whole loop (even if the loop is fast, it's quadratic). 8126 // It's important for the loop break condition (see below) to 8127 // check this limit even between two read-only instructions. 8128 if (DistToSrc >= MaxMemDepDistance || 8129 ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) && 8130 (numAliased >= AliasedCheckLimit || 8131 SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) { 8132 8133 // We increment the counter only if the locations are aliased 8134 // (instead of counting all alias checks). This gives a better 8135 // balance between reduced runtime and accurate dependencies. 8136 numAliased++; 8137 8138 DepDest->MemoryDependencies.push_back(BundleMember); 8139 BundleMember->Dependencies++; 8140 ScheduleData *DestBundle = DepDest->FirstInBundle; 8141 if (!DestBundle->IsScheduled) { 8142 BundleMember->incrementUnscheduledDeps(1); 8143 } 8144 if (!DestBundle->hasValidDependencies()) { 8145 WorkList.push_back(DestBundle); 8146 } 8147 } 8148 8149 // Example, explaining the loop break condition: Let's assume our 8150 // starting instruction is i0 and MaxMemDepDistance = 3. 8151 // 8152 // +--------v--v--v 8153 // i0,i1,i2,i3,i4,i5,i6,i7,i8 8154 // +--------^--^--^ 8155 // 8156 // MaxMemDepDistance let us stop alias-checking at i3 and we add 8157 // dependencies from i0 to i3,i4,.. (even if they are not aliased). 8158 // Previously we already added dependencies from i3 to i6,i7,i8 8159 // (because of MaxMemDepDistance). As we added a dependency from 8160 // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8 8161 // and we can abort this loop at i6. 8162 if (DistToSrc >= 2 * MaxMemDepDistance) 8163 break; 8164 DistToSrc++; 8165 } 8166 } 8167 if (InsertInReadyList && SD->isReady()) { 8168 ReadyInsts.insert(SD); 8169 LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst 8170 << "\n"); 8171 } 8172 } 8173 } 8174 8175 void BoUpSLP::BlockScheduling::resetSchedule() { 8176 assert(ScheduleStart && 8177 "tried to reset schedule on block which has not been scheduled"); 8178 for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) { 8179 doForAllOpcodes(I, [&](ScheduleData *SD) { 8180 assert(isInSchedulingRegion(SD) && 8181 "ScheduleData not in scheduling region"); 8182 SD->IsScheduled = false; 8183 SD->resetUnscheduledDeps(); 8184 }); 8185 } 8186 ReadyInsts.clear(); 8187 } 8188 8189 void BoUpSLP::scheduleBlock(BlockScheduling *BS) { 8190 if (!BS->ScheduleStart) 8191 return; 8192 8193 LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n"); 8194 8195 BS->resetSchedule(); 8196 8197 // For the real scheduling we use a more sophisticated ready-list: it is 8198 // sorted by the original instruction location. This lets the final schedule 8199 // be as close as possible to the original instruction order. 8200 // WARNING: If changing this order causes a correctness issue, that means 8201 // there is some missing dependence edge in the schedule data graph. 8202 struct ScheduleDataCompare { 8203 bool operator()(ScheduleData *SD1, ScheduleData *SD2) const { 8204 return SD2->SchedulingPriority < SD1->SchedulingPriority; 8205 } 8206 }; 8207 std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts; 8208 8209 // Ensure that all dependency data is updated and fill the ready-list with 8210 // initial instructions. 8211 int Idx = 0; 8212 int NumToSchedule = 0; 8213 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; 8214 I = I->getNextNode()) { 8215 BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) { 8216 TreeEntry *SDTE = getTreeEntry(SD->Inst); 8217 (void)SDTE; 8218 assert((isVectorLikeInstWithConstOps(SD->Inst) || 8219 SD->isPartOfBundle() == 8220 (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) && 8221 "scheduler and vectorizer bundle mismatch"); 8222 SD->FirstInBundle->SchedulingPriority = Idx++; 8223 if (SD->isSchedulingEntity()) { 8224 BS->calculateDependencies(SD, false, this); 8225 NumToSchedule++; 8226 } 8227 }); 8228 } 8229 BS->initialFillReadyList(ReadyInsts); 8230 8231 Instruction *LastScheduledInst = BS->ScheduleEnd; 8232 8233 // Do the "real" scheduling. 8234 while (!ReadyInsts.empty()) { 8235 ScheduleData *picked = *ReadyInsts.begin(); 8236 ReadyInsts.erase(ReadyInsts.begin()); 8237 8238 // Move the scheduled instruction(s) to their dedicated places, if not 8239 // there yet. 8240 for (ScheduleData *BundleMember = picked; BundleMember; 8241 BundleMember = BundleMember->NextInBundle) { 8242 Instruction *pickedInst = BundleMember->Inst; 8243 if (pickedInst->getNextNode() != LastScheduledInst) 8244 pickedInst->moveBefore(LastScheduledInst); 8245 LastScheduledInst = pickedInst; 8246 } 8247 8248 BS->schedule(picked, ReadyInsts); 8249 NumToSchedule--; 8250 } 8251 assert(NumToSchedule == 0 && "could not schedule all instructions"); 8252 8253 // Check that we didn't break any of our invariants. 8254 #ifdef EXPENSIVE_CHECKS 8255 BS->verify(); 8256 #endif 8257 8258 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS) 8259 // Check that all schedulable entities got scheduled 8260 for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) { 8261 BS->doForAllOpcodes(I, [&](ScheduleData *SD) { 8262 if (SD->isSchedulingEntity() && SD->hasValidDependencies()) { 8263 assert(SD->IsScheduled && "must be scheduled at this point"); 8264 } 8265 }); 8266 } 8267 #endif 8268 8269 // Avoid duplicate scheduling of the block. 8270 BS->ScheduleStart = nullptr; 8271 } 8272 8273 unsigned BoUpSLP::getVectorElementSize(Value *V) { 8274 // If V is a store, just return the width of the stored value (or value 8275 // truncated just before storing) without traversing the expression tree. 8276 // This is the common case. 8277 if (auto *Store = dyn_cast<StoreInst>(V)) { 8278 if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand())) 8279 return DL->getTypeSizeInBits(Trunc->getSrcTy()); 8280 return DL->getTypeSizeInBits(Store->getValueOperand()->getType()); 8281 } 8282 8283 if (auto *IEI = dyn_cast<InsertElementInst>(V)) 8284 return getVectorElementSize(IEI->getOperand(1)); 8285 8286 auto E = InstrElementSize.find(V); 8287 if (E != InstrElementSize.end()) 8288 return E->second; 8289 8290 // If V is not a store, we can traverse the expression tree to find loads 8291 // that feed it. The type of the loaded value may indicate a more suitable 8292 // width than V's type. We want to base the vector element size on the width 8293 // of memory operations where possible. 8294 SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist; 8295 SmallPtrSet<Instruction *, 16> Visited; 8296 if (auto *I = dyn_cast<Instruction>(V)) { 8297 Worklist.emplace_back(I, I->getParent()); 8298 Visited.insert(I); 8299 } 8300 8301 // Traverse the expression tree in bottom-up order looking for loads. If we 8302 // encounter an instruction we don't yet handle, we give up. 8303 auto Width = 0u; 8304 while (!Worklist.empty()) { 8305 Instruction *I; 8306 BasicBlock *Parent; 8307 std::tie(I, Parent) = Worklist.pop_back_val(); 8308 8309 // We should only be looking at scalar instructions here. If the current 8310 // instruction has a vector type, skip. 8311 auto *Ty = I->getType(); 8312 if (isa<VectorType>(Ty)) 8313 continue; 8314 8315 // If the current instruction is a load, update MaxWidth to reflect the 8316 // width of the loaded value. 8317 if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) || 8318 isa<ExtractValueInst>(I)) 8319 Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty)); 8320 8321 // Otherwise, we need to visit the operands of the instruction. We only 8322 // handle the interesting cases from buildTree here. If an operand is an 8323 // instruction we haven't yet visited and from the same basic block as the 8324 // user or the use is a PHI node, we add it to the worklist. 8325 else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) || 8326 isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) || 8327 isa<UnaryOperator>(I)) { 8328 for (Use &U : I->operands()) 8329 if (auto *J = dyn_cast<Instruction>(U.get())) 8330 if (Visited.insert(J).second && 8331 (isa<PHINode>(I) || J->getParent() == Parent)) 8332 Worklist.emplace_back(J, J->getParent()); 8333 } else { 8334 break; 8335 } 8336 } 8337 8338 // If we didn't encounter a memory access in the expression tree, or if we 8339 // gave up for some reason, just return the width of V. Otherwise, return the 8340 // maximum width we found. 8341 if (!Width) { 8342 if (auto *CI = dyn_cast<CmpInst>(V)) 8343 V = CI->getOperand(0); 8344 Width = DL->getTypeSizeInBits(V->getType()); 8345 } 8346 8347 for (Instruction *I : Visited) 8348 InstrElementSize[I] = Width; 8349 8350 return Width; 8351 } 8352 8353 // Determine if a value V in a vectorizable expression Expr can be demoted to a 8354 // smaller type with a truncation. We collect the values that will be demoted 8355 // in ToDemote and additional roots that require investigating in Roots. 8356 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr, 8357 SmallVectorImpl<Value *> &ToDemote, 8358 SmallVectorImpl<Value *> &Roots) { 8359 // We can always demote constants. 8360 if (isa<Constant>(V)) { 8361 ToDemote.push_back(V); 8362 return true; 8363 } 8364 8365 // If the value is not an instruction in the expression with only one use, it 8366 // cannot be demoted. 8367 auto *I = dyn_cast<Instruction>(V); 8368 if (!I || !I->hasOneUse() || !Expr.count(I)) 8369 return false; 8370 8371 switch (I->getOpcode()) { 8372 8373 // We can always demote truncations and extensions. Since truncations can 8374 // seed additional demotion, we save the truncated value. 8375 case Instruction::Trunc: 8376 Roots.push_back(I->getOperand(0)); 8377 break; 8378 case Instruction::ZExt: 8379 case Instruction::SExt: 8380 if (isa<ExtractElementInst>(I->getOperand(0)) || 8381 isa<InsertElementInst>(I->getOperand(0))) 8382 return false; 8383 break; 8384 8385 // We can demote certain binary operations if we can demote both of their 8386 // operands. 8387 case Instruction::Add: 8388 case Instruction::Sub: 8389 case Instruction::Mul: 8390 case Instruction::And: 8391 case Instruction::Or: 8392 case Instruction::Xor: 8393 if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) || 8394 !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots)) 8395 return false; 8396 break; 8397 8398 // We can demote selects if we can demote their true and false values. 8399 case Instruction::Select: { 8400 SelectInst *SI = cast<SelectInst>(I); 8401 if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) || 8402 !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots)) 8403 return false; 8404 break; 8405 } 8406 8407 // We can demote phis if we can demote all their incoming operands. Note that 8408 // we don't need to worry about cycles since we ensure single use above. 8409 case Instruction::PHI: { 8410 PHINode *PN = cast<PHINode>(I); 8411 for (Value *IncValue : PN->incoming_values()) 8412 if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots)) 8413 return false; 8414 break; 8415 } 8416 8417 // Otherwise, conservatively give up. 8418 default: 8419 return false; 8420 } 8421 8422 // Record the value that we can demote. 8423 ToDemote.push_back(V); 8424 return true; 8425 } 8426 8427 void BoUpSLP::computeMinimumValueSizes() { 8428 // If there are no external uses, the expression tree must be rooted by a 8429 // store. We can't demote in-memory values, so there is nothing to do here. 8430 if (ExternalUses.empty()) 8431 return; 8432 8433 // We only attempt to truncate integer expressions. 8434 auto &TreeRoot = VectorizableTree[0]->Scalars; 8435 auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType()); 8436 if (!TreeRootIT) 8437 return; 8438 8439 // If the expression is not rooted by a store, these roots should have 8440 // external uses. We will rely on InstCombine to rewrite the expression in 8441 // the narrower type. However, InstCombine only rewrites single-use values. 8442 // This means that if a tree entry other than a root is used externally, it 8443 // must have multiple uses and InstCombine will not rewrite it. The code 8444 // below ensures that only the roots are used externally. 8445 SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end()); 8446 for (auto &EU : ExternalUses) 8447 if (!Expr.erase(EU.Scalar)) 8448 return; 8449 if (!Expr.empty()) 8450 return; 8451 8452 // Collect the scalar values of the vectorizable expression. We will use this 8453 // context to determine which values can be demoted. If we see a truncation, 8454 // we mark it as seeding another demotion. 8455 for (auto &EntryPtr : VectorizableTree) 8456 Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end()); 8457 8458 // Ensure the roots of the vectorizable tree don't form a cycle. They must 8459 // have a single external user that is not in the vectorizable tree. 8460 for (auto *Root : TreeRoot) 8461 if (!Root->hasOneUse() || Expr.count(*Root->user_begin())) 8462 return; 8463 8464 // Conservatively determine if we can actually truncate the roots of the 8465 // expression. Collect the values that can be demoted in ToDemote and 8466 // additional roots that require investigating in Roots. 8467 SmallVector<Value *, 32> ToDemote; 8468 SmallVector<Value *, 4> Roots; 8469 for (auto *Root : TreeRoot) 8470 if (!collectValuesToDemote(Root, Expr, ToDemote, Roots)) 8471 return; 8472 8473 // The maximum bit width required to represent all the values that can be 8474 // demoted without loss of precision. It would be safe to truncate the roots 8475 // of the expression to this width. 8476 auto MaxBitWidth = 8u; 8477 8478 // We first check if all the bits of the roots are demanded. If they're not, 8479 // we can truncate the roots to this narrower type. 8480 for (auto *Root : TreeRoot) { 8481 auto Mask = DB->getDemandedBits(cast<Instruction>(Root)); 8482 MaxBitWidth = std::max<unsigned>( 8483 Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth); 8484 } 8485 8486 // True if the roots can be zero-extended back to their original type, rather 8487 // than sign-extended. We know that if the leading bits are not demanded, we 8488 // can safely zero-extend. So we initialize IsKnownPositive to True. 8489 bool IsKnownPositive = true; 8490 8491 // If all the bits of the roots are demanded, we can try a little harder to 8492 // compute a narrower type. This can happen, for example, if the roots are 8493 // getelementptr indices. InstCombine promotes these indices to the pointer 8494 // width. Thus, all their bits are technically demanded even though the 8495 // address computation might be vectorized in a smaller type. 8496 // 8497 // We start by looking at each entry that can be demoted. We compute the 8498 // maximum bit width required to store the scalar by using ValueTracking to 8499 // compute the number of high-order bits we can truncate. 8500 if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) && 8501 llvm::all_of(TreeRoot, [](Value *R) { 8502 assert(R->hasOneUse() && "Root should have only one use!"); 8503 return isa<GetElementPtrInst>(R->user_back()); 8504 })) { 8505 MaxBitWidth = 8u; 8506 8507 // Determine if the sign bit of all the roots is known to be zero. If not, 8508 // IsKnownPositive is set to False. 8509 IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) { 8510 KnownBits Known = computeKnownBits(R, *DL); 8511 return Known.isNonNegative(); 8512 }); 8513 8514 // Determine the maximum number of bits required to store the scalar 8515 // values. 8516 for (auto *Scalar : ToDemote) { 8517 auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT); 8518 auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType()); 8519 MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth); 8520 } 8521 8522 // If we can't prove that the sign bit is zero, we must add one to the 8523 // maximum bit width to account for the unknown sign bit. This preserves 8524 // the existing sign bit so we can safely sign-extend the root back to the 8525 // original type. Otherwise, if we know the sign bit is zero, we will 8526 // zero-extend the root instead. 8527 // 8528 // FIXME: This is somewhat suboptimal, as there will be cases where adding 8529 // one to the maximum bit width will yield a larger-than-necessary 8530 // type. In general, we need to add an extra bit only if we can't 8531 // prove that the upper bit of the original type is equal to the 8532 // upper bit of the proposed smaller type. If these two bits are the 8533 // same (either zero or one) we know that sign-extending from the 8534 // smaller type will result in the same value. Here, since we can't 8535 // yet prove this, we are just making the proposed smaller type 8536 // larger to ensure correctness. 8537 if (!IsKnownPositive) 8538 ++MaxBitWidth; 8539 } 8540 8541 // Round MaxBitWidth up to the next power-of-two. 8542 if (!isPowerOf2_64(MaxBitWidth)) 8543 MaxBitWidth = NextPowerOf2(MaxBitWidth); 8544 8545 // If the maximum bit width we compute is less than the with of the roots' 8546 // type, we can proceed with the narrowing. Otherwise, do nothing. 8547 if (MaxBitWidth >= TreeRootIT->getBitWidth()) 8548 return; 8549 8550 // If we can truncate the root, we must collect additional values that might 8551 // be demoted as a result. That is, those seeded by truncations we will 8552 // modify. 8553 while (!Roots.empty()) 8554 collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots); 8555 8556 // Finally, map the values we can demote to the maximum bit with we computed. 8557 for (auto *Scalar : ToDemote) 8558 MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive); 8559 } 8560 8561 namespace { 8562 8563 /// The SLPVectorizer Pass. 8564 struct SLPVectorizer : public FunctionPass { 8565 SLPVectorizerPass Impl; 8566 8567 /// Pass identification, replacement for typeid 8568 static char ID; 8569 8570 explicit SLPVectorizer() : FunctionPass(ID) { 8571 initializeSLPVectorizerPass(*PassRegistry::getPassRegistry()); 8572 } 8573 8574 bool doInitialization(Module &M) override { return false; } 8575 8576 bool runOnFunction(Function &F) override { 8577 if (skipFunction(F)) 8578 return false; 8579 8580 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE(); 8581 auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 8582 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>(); 8583 auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr; 8584 auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults(); 8585 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo(); 8586 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree(); 8587 auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F); 8588 auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits(); 8589 auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE(); 8590 8591 return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 8592 } 8593 8594 void getAnalysisUsage(AnalysisUsage &AU) const override { 8595 FunctionPass::getAnalysisUsage(AU); 8596 AU.addRequired<AssumptionCacheTracker>(); 8597 AU.addRequired<ScalarEvolutionWrapperPass>(); 8598 AU.addRequired<AAResultsWrapperPass>(); 8599 AU.addRequired<TargetTransformInfoWrapperPass>(); 8600 AU.addRequired<LoopInfoWrapperPass>(); 8601 AU.addRequired<DominatorTreeWrapperPass>(); 8602 AU.addRequired<DemandedBitsWrapperPass>(); 8603 AU.addRequired<OptimizationRemarkEmitterWrapperPass>(); 8604 AU.addRequired<InjectTLIMappingsLegacy>(); 8605 AU.addPreserved<LoopInfoWrapperPass>(); 8606 AU.addPreserved<DominatorTreeWrapperPass>(); 8607 AU.addPreserved<AAResultsWrapperPass>(); 8608 AU.addPreserved<GlobalsAAWrapperPass>(); 8609 AU.setPreservesCFG(); 8610 } 8611 }; 8612 8613 } // end anonymous namespace 8614 8615 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) { 8616 auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F); 8617 auto *TTI = &AM.getResult<TargetIRAnalysis>(F); 8618 auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F); 8619 auto *AA = &AM.getResult<AAManager>(F); 8620 auto *LI = &AM.getResult<LoopAnalysis>(F); 8621 auto *DT = &AM.getResult<DominatorTreeAnalysis>(F); 8622 auto *AC = &AM.getResult<AssumptionAnalysis>(F); 8623 auto *DB = &AM.getResult<DemandedBitsAnalysis>(F); 8624 auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F); 8625 8626 bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE); 8627 if (!Changed) 8628 return PreservedAnalyses::all(); 8629 8630 PreservedAnalyses PA; 8631 PA.preserveSet<CFGAnalyses>(); 8632 return PA; 8633 } 8634 8635 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_, 8636 TargetTransformInfo *TTI_, 8637 TargetLibraryInfo *TLI_, AAResults *AA_, 8638 LoopInfo *LI_, DominatorTree *DT_, 8639 AssumptionCache *AC_, DemandedBits *DB_, 8640 OptimizationRemarkEmitter *ORE_) { 8641 if (!RunSLPVectorization) 8642 return false; 8643 SE = SE_; 8644 TTI = TTI_; 8645 TLI = TLI_; 8646 AA = AA_; 8647 LI = LI_; 8648 DT = DT_; 8649 AC = AC_; 8650 DB = DB_; 8651 DL = &F.getParent()->getDataLayout(); 8652 8653 Stores.clear(); 8654 GEPs.clear(); 8655 bool Changed = false; 8656 8657 // If the target claims to have no vector registers don't attempt 8658 // vectorization. 8659 if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) { 8660 LLVM_DEBUG( 8661 dbgs() << "SLP: Didn't find any vector registers for target, abort.\n"); 8662 return false; 8663 } 8664 8665 // Don't vectorize when the attribute NoImplicitFloat is used. 8666 if (F.hasFnAttribute(Attribute::NoImplicitFloat)) 8667 return false; 8668 8669 LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n"); 8670 8671 // Use the bottom up slp vectorizer to construct chains that start with 8672 // store instructions. 8673 BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_); 8674 8675 // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to 8676 // delete instructions. 8677 8678 // Update DFS numbers now so that we can use them for ordering. 8679 DT->updateDFSNumbers(); 8680 8681 // Scan the blocks in the function in post order. 8682 for (auto BB : post_order(&F.getEntryBlock())) { 8683 collectSeedInstructions(BB); 8684 8685 // Vectorize trees that end at stores. 8686 if (!Stores.empty()) { 8687 LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size() 8688 << " underlying objects.\n"); 8689 Changed |= vectorizeStoreChains(R); 8690 } 8691 8692 // Vectorize trees that end at reductions. 8693 Changed |= vectorizeChainsInBlock(BB, R); 8694 8695 // Vectorize the index computations of getelementptr instructions. This 8696 // is primarily intended to catch gather-like idioms ending at 8697 // non-consecutive loads. 8698 if (!GEPs.empty()) { 8699 LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size() 8700 << " underlying objects.\n"); 8701 Changed |= vectorizeGEPIndices(BB, R); 8702 } 8703 } 8704 8705 if (Changed) { 8706 R.optimizeGatherSequence(); 8707 LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n"); 8708 } 8709 return Changed; 8710 } 8711 8712 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R, 8713 unsigned Idx) { 8714 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size() 8715 << "\n"); 8716 const unsigned Sz = R.getVectorElementSize(Chain[0]); 8717 const unsigned MinVF = R.getMinVecRegSize() / Sz; 8718 unsigned VF = Chain.size(); 8719 8720 if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF) 8721 return false; 8722 8723 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx 8724 << "\n"); 8725 8726 R.buildTree(Chain); 8727 if (R.isTreeTinyAndNotFullyVectorizable()) 8728 return false; 8729 if (R.isLoadCombineCandidate()) 8730 return false; 8731 R.reorderTopToBottom(); 8732 R.reorderBottomToTop(); 8733 R.buildExternalUses(); 8734 8735 R.computeMinimumValueSizes(); 8736 8737 InstructionCost Cost = R.getTreeCost(); 8738 8739 LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n"); 8740 if (Cost < -SLPCostThreshold) { 8741 LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n"); 8742 8743 using namespace ore; 8744 8745 R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized", 8746 cast<StoreInst>(Chain[0])) 8747 << "Stores SLP vectorized with cost " << NV("Cost", Cost) 8748 << " and with tree size " 8749 << NV("TreeSize", R.getTreeSize())); 8750 8751 R.vectorizeTree(); 8752 return true; 8753 } 8754 8755 return false; 8756 } 8757 8758 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores, 8759 BoUpSLP &R) { 8760 // We may run into multiple chains that merge into a single chain. We mark the 8761 // stores that we vectorized so that we don't visit the same store twice. 8762 BoUpSLP::ValueSet VectorizedStores; 8763 bool Changed = false; 8764 8765 int E = Stores.size(); 8766 SmallBitVector Tails(E, false); 8767 int MaxIter = MaxStoreLookup.getValue(); 8768 SmallVector<std::pair<int, int>, 16> ConsecutiveChain( 8769 E, std::make_pair(E, INT_MAX)); 8770 SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false)); 8771 int IterCnt; 8772 auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter, 8773 &CheckedPairs, 8774 &ConsecutiveChain](int K, int Idx) { 8775 if (IterCnt >= MaxIter) 8776 return true; 8777 if (CheckedPairs[Idx].test(K)) 8778 return ConsecutiveChain[K].second == 1 && 8779 ConsecutiveChain[K].first == Idx; 8780 ++IterCnt; 8781 CheckedPairs[Idx].set(K); 8782 CheckedPairs[K].set(Idx); 8783 Optional<int> Diff = getPointersDiff( 8784 Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(), 8785 Stores[Idx]->getValueOperand()->getType(), 8786 Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true); 8787 if (!Diff || *Diff == 0) 8788 return false; 8789 int Val = *Diff; 8790 if (Val < 0) { 8791 if (ConsecutiveChain[Idx].second > -Val) { 8792 Tails.set(K); 8793 ConsecutiveChain[Idx] = std::make_pair(K, -Val); 8794 } 8795 return false; 8796 } 8797 if (ConsecutiveChain[K].second <= Val) 8798 return false; 8799 8800 Tails.set(Idx); 8801 ConsecutiveChain[K] = std::make_pair(Idx, Val); 8802 return Val == 1; 8803 }; 8804 // Do a quadratic search on all of the given stores in reverse order and find 8805 // all of the pairs of stores that follow each other. 8806 for (int Idx = E - 1; Idx >= 0; --Idx) { 8807 // If a store has multiple consecutive store candidates, search according 8808 // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ... 8809 // This is because usually pairing with immediate succeeding or preceding 8810 // candidate create the best chance to find slp vectorization opportunity. 8811 const int MaxLookDepth = std::max(E - Idx, Idx + 1); 8812 IterCnt = 0; 8813 for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset) 8814 if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) || 8815 (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx))) 8816 break; 8817 } 8818 8819 // Tracks if we tried to vectorize stores starting from the given tail 8820 // already. 8821 SmallBitVector TriedTails(E, false); 8822 // For stores that start but don't end a link in the chain: 8823 for (int Cnt = E; Cnt > 0; --Cnt) { 8824 int I = Cnt - 1; 8825 if (ConsecutiveChain[I].first == E || Tails.test(I)) 8826 continue; 8827 // We found a store instr that starts a chain. Now follow the chain and try 8828 // to vectorize it. 8829 BoUpSLP::ValueList Operands; 8830 // Collect the chain into a list. 8831 while (I != E && !VectorizedStores.count(Stores[I])) { 8832 Operands.push_back(Stores[I]); 8833 Tails.set(I); 8834 if (ConsecutiveChain[I].second != 1) { 8835 // Mark the new end in the chain and go back, if required. It might be 8836 // required if the original stores come in reversed order, for example. 8837 if (ConsecutiveChain[I].first != E && 8838 Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) && 8839 !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) { 8840 TriedTails.set(I); 8841 Tails.reset(ConsecutiveChain[I].first); 8842 if (Cnt < ConsecutiveChain[I].first + 2) 8843 Cnt = ConsecutiveChain[I].first + 2; 8844 } 8845 break; 8846 } 8847 // Move to the next value in the chain. 8848 I = ConsecutiveChain[I].first; 8849 } 8850 assert(!Operands.empty() && "Expected non-empty list of stores."); 8851 8852 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 8853 unsigned EltSize = R.getVectorElementSize(Operands[0]); 8854 unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize); 8855 8856 unsigned MinVF = R.getMinVF(EltSize); 8857 unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store), 8858 MaxElts); 8859 8860 // FIXME: Is division-by-2 the correct step? Should we assert that the 8861 // register size is a power-of-2? 8862 unsigned StartIdx = 0; 8863 for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) { 8864 for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) { 8865 ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size); 8866 if (!VectorizedStores.count(Slice.front()) && 8867 !VectorizedStores.count(Slice.back()) && 8868 vectorizeStoreChain(Slice, R, Cnt)) { 8869 // Mark the vectorized stores so that we don't vectorize them again. 8870 VectorizedStores.insert(Slice.begin(), Slice.end()); 8871 Changed = true; 8872 // If we vectorized initial block, no need to try to vectorize it 8873 // again. 8874 if (Cnt == StartIdx) 8875 StartIdx += Size; 8876 Cnt += Size; 8877 continue; 8878 } 8879 ++Cnt; 8880 } 8881 // Check if the whole array was vectorized already - exit. 8882 if (StartIdx >= Operands.size()) 8883 break; 8884 } 8885 } 8886 8887 return Changed; 8888 } 8889 8890 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) { 8891 // Initialize the collections. We will make a single pass over the block. 8892 Stores.clear(); 8893 GEPs.clear(); 8894 8895 // Visit the store and getelementptr instructions in BB and organize them in 8896 // Stores and GEPs according to the underlying objects of their pointer 8897 // operands. 8898 for (Instruction &I : *BB) { 8899 // Ignore store instructions that are volatile or have a pointer operand 8900 // that doesn't point to a scalar type. 8901 if (auto *SI = dyn_cast<StoreInst>(&I)) { 8902 if (!SI->isSimple()) 8903 continue; 8904 if (!isValidElementType(SI->getValueOperand()->getType())) 8905 continue; 8906 Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI); 8907 } 8908 8909 // Ignore getelementptr instructions that have more than one index, a 8910 // constant index, or a pointer operand that doesn't point to a scalar 8911 // type. 8912 else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) { 8913 auto Idx = GEP->idx_begin()->get(); 8914 if (GEP->getNumIndices() > 1 || isa<Constant>(Idx)) 8915 continue; 8916 if (!isValidElementType(Idx->getType())) 8917 continue; 8918 if (GEP->getType()->isVectorTy()) 8919 continue; 8920 GEPs[GEP->getPointerOperand()].push_back(GEP); 8921 } 8922 } 8923 } 8924 8925 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) { 8926 if (!A || !B) 8927 return false; 8928 if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B)) 8929 return false; 8930 Value *VL[] = {A, B}; 8931 return tryToVectorizeList(VL, R); 8932 } 8933 8934 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R, 8935 bool LimitForRegisterSize) { 8936 if (VL.size() < 2) 8937 return false; 8938 8939 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " 8940 << VL.size() << ".\n"); 8941 8942 // Check that all of the parts are instructions of the same type, 8943 // we permit an alternate opcode via InstructionsState. 8944 InstructionsState S = getSameOpcode(VL); 8945 if (!S.getOpcode()) 8946 return false; 8947 8948 Instruction *I0 = cast<Instruction>(S.OpValue); 8949 // Make sure invalid types (including vector type) are rejected before 8950 // determining vectorization factor for scalar instructions. 8951 for (Value *V : VL) { 8952 Type *Ty = V->getType(); 8953 if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) { 8954 // NOTE: the following will give user internal llvm type name, which may 8955 // not be useful. 8956 R.getORE()->emit([&]() { 8957 std::string type_str; 8958 llvm::raw_string_ostream rso(type_str); 8959 Ty->print(rso); 8960 return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0) 8961 << "Cannot SLP vectorize list: type " 8962 << rso.str() + " is unsupported by vectorizer"; 8963 }); 8964 return false; 8965 } 8966 } 8967 8968 unsigned Sz = R.getVectorElementSize(I0); 8969 unsigned MinVF = R.getMinVF(Sz); 8970 unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF); 8971 MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF); 8972 if (MaxVF < 2) { 8973 R.getORE()->emit([&]() { 8974 return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0) 8975 << "Cannot SLP vectorize list: vectorization factor " 8976 << "less than 2 is not supported"; 8977 }); 8978 return false; 8979 } 8980 8981 bool Changed = false; 8982 bool CandidateFound = false; 8983 InstructionCost MinCost = SLPCostThreshold.getValue(); 8984 Type *ScalarTy = VL[0]->getType(); 8985 if (auto *IE = dyn_cast<InsertElementInst>(VL[0])) 8986 ScalarTy = IE->getOperand(1)->getType(); 8987 8988 unsigned NextInst = 0, MaxInst = VL.size(); 8989 for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) { 8990 // No actual vectorization should happen, if number of parts is the same as 8991 // provided vectorization factor (i.e. the scalar type is used for vector 8992 // code during codegen). 8993 auto *VecTy = FixedVectorType::get(ScalarTy, VF); 8994 if (TTI->getNumberOfParts(VecTy) == VF) 8995 continue; 8996 for (unsigned I = NextInst; I < MaxInst; ++I) { 8997 unsigned OpsWidth = 0; 8998 8999 if (I + VF > MaxInst) 9000 OpsWidth = MaxInst - I; 9001 else 9002 OpsWidth = VF; 9003 9004 if (!isPowerOf2_32(OpsWidth)) 9005 continue; 9006 9007 if ((LimitForRegisterSize && OpsWidth < MaxVF) || 9008 (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2)) 9009 break; 9010 9011 ArrayRef<Value *> Ops = VL.slice(I, OpsWidth); 9012 // Check that a previous iteration of this loop did not delete the Value. 9013 if (llvm::any_of(Ops, [&R](Value *V) { 9014 auto *I = dyn_cast<Instruction>(V); 9015 return I && R.isDeleted(I); 9016 })) 9017 continue; 9018 9019 LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations " 9020 << "\n"); 9021 9022 R.buildTree(Ops); 9023 if (R.isTreeTinyAndNotFullyVectorizable()) 9024 continue; 9025 R.reorderTopToBottom(); 9026 R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front())); 9027 R.buildExternalUses(); 9028 9029 R.computeMinimumValueSizes(); 9030 InstructionCost Cost = R.getTreeCost(); 9031 CandidateFound = true; 9032 MinCost = std::min(MinCost, Cost); 9033 9034 if (Cost < -SLPCostThreshold) { 9035 LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n"); 9036 R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList", 9037 cast<Instruction>(Ops[0])) 9038 << "SLP vectorized with cost " << ore::NV("Cost", Cost) 9039 << " and with tree size " 9040 << ore::NV("TreeSize", R.getTreeSize())); 9041 9042 R.vectorizeTree(); 9043 // Move to the next bundle. 9044 I += VF - 1; 9045 NextInst = I + 1; 9046 Changed = true; 9047 } 9048 } 9049 } 9050 9051 if (!Changed && CandidateFound) { 9052 R.getORE()->emit([&]() { 9053 return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0) 9054 << "List vectorization was possible but not beneficial with cost " 9055 << ore::NV("Cost", MinCost) << " >= " 9056 << ore::NV("Treshold", -SLPCostThreshold); 9057 }); 9058 } else if (!Changed) { 9059 R.getORE()->emit([&]() { 9060 return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0) 9061 << "Cannot SLP vectorize list: vectorization was impossible" 9062 << " with available vectorization factors"; 9063 }); 9064 } 9065 return Changed; 9066 } 9067 9068 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) { 9069 if (!I) 9070 return false; 9071 9072 if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I)) 9073 return false; 9074 9075 Value *P = I->getParent(); 9076 9077 // Vectorize in current basic block only. 9078 auto *Op0 = dyn_cast<Instruction>(I->getOperand(0)); 9079 auto *Op1 = dyn_cast<Instruction>(I->getOperand(1)); 9080 if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P) 9081 return false; 9082 9083 // Try to vectorize V. 9084 if (tryToVectorizePair(Op0, Op1, R)) 9085 return true; 9086 9087 auto *A = dyn_cast<BinaryOperator>(Op0); 9088 auto *B = dyn_cast<BinaryOperator>(Op1); 9089 // Try to skip B. 9090 if (B && B->hasOneUse()) { 9091 auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0)); 9092 auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1)); 9093 if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R)) 9094 return true; 9095 if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R)) 9096 return true; 9097 } 9098 9099 // Try to skip A. 9100 if (A && A->hasOneUse()) { 9101 auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0)); 9102 auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1)); 9103 if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R)) 9104 return true; 9105 if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R)) 9106 return true; 9107 } 9108 return false; 9109 } 9110 9111 namespace { 9112 9113 /// Model horizontal reductions. 9114 /// 9115 /// A horizontal reduction is a tree of reduction instructions that has values 9116 /// that can be put into a vector as its leaves. For example: 9117 /// 9118 /// mul mul mul mul 9119 /// \ / \ / 9120 /// + + 9121 /// \ / 9122 /// + 9123 /// This tree has "mul" as its leaf values and "+" as its reduction 9124 /// instructions. A reduction can feed into a store or a binary operation 9125 /// feeding a phi. 9126 /// ... 9127 /// \ / 9128 /// + 9129 /// | 9130 /// phi += 9131 /// 9132 /// Or: 9133 /// ... 9134 /// \ / 9135 /// + 9136 /// | 9137 /// *p = 9138 /// 9139 class HorizontalReduction { 9140 using ReductionOpsType = SmallVector<Value *, 16>; 9141 using ReductionOpsListType = SmallVector<ReductionOpsType, 2>; 9142 ReductionOpsListType ReductionOps; 9143 SmallVector<Value *, 32> ReducedVals; 9144 // Use map vector to make stable output. 9145 MapVector<Instruction *, Value *> ExtraArgs; 9146 WeakTrackingVH ReductionRoot; 9147 /// The type of reduction operation. 9148 RecurKind RdxKind; 9149 9150 const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max(); 9151 9152 static bool isCmpSelMinMax(Instruction *I) { 9153 return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) && 9154 RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I)); 9155 } 9156 9157 // And/or are potentially poison-safe logical patterns like: 9158 // select x, y, false 9159 // select x, true, y 9160 static bool isBoolLogicOp(Instruction *I) { 9161 return match(I, m_LogicalAnd(m_Value(), m_Value())) || 9162 match(I, m_LogicalOr(m_Value(), m_Value())); 9163 } 9164 9165 /// Checks if instruction is associative and can be vectorized. 9166 static bool isVectorizable(RecurKind Kind, Instruction *I) { 9167 if (Kind == RecurKind::None) 9168 return false; 9169 9170 // Integer ops that map to select instructions or intrinsics are fine. 9171 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) || 9172 isBoolLogicOp(I)) 9173 return true; 9174 9175 if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) { 9176 // FP min/max are associative except for NaN and -0.0. We do not 9177 // have to rule out -0.0 here because the intrinsic semantics do not 9178 // specify a fixed result for it. 9179 return I->getFastMathFlags().noNaNs(); 9180 } 9181 9182 return I->isAssociative(); 9183 } 9184 9185 static Value *getRdxOperand(Instruction *I, unsigned Index) { 9186 // Poison-safe 'or' takes the form: select X, true, Y 9187 // To make that work with the normal operand processing, we skip the 9188 // true value operand. 9189 // TODO: Change the code and data structures to handle this without a hack. 9190 if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1) 9191 return I->getOperand(2); 9192 return I->getOperand(Index); 9193 } 9194 9195 /// Checks if the ParentStackElem.first should be marked as a reduction 9196 /// operation with an extra argument or as extra argument itself. 9197 void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem, 9198 Value *ExtraArg) { 9199 if (ExtraArgs.count(ParentStackElem.first)) { 9200 ExtraArgs[ParentStackElem.first] = nullptr; 9201 // We ran into something like: 9202 // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg. 9203 // The whole ParentStackElem.first should be considered as an extra value 9204 // in this case. 9205 // Do not perform analysis of remaining operands of ParentStackElem.first 9206 // instruction, this whole instruction is an extra argument. 9207 ParentStackElem.second = INVALID_OPERAND_INDEX; 9208 } else { 9209 // We ran into something like: 9210 // ParentStackElem.first += ... + ExtraArg + ... 9211 ExtraArgs[ParentStackElem.first] = ExtraArg; 9212 } 9213 } 9214 9215 /// Creates reduction operation with the current opcode. 9216 static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS, 9217 Value *RHS, const Twine &Name, bool UseSelect) { 9218 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind); 9219 switch (Kind) { 9220 case RecurKind::Or: 9221 if (UseSelect && 9222 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 9223 return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name); 9224 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 9225 Name); 9226 case RecurKind::And: 9227 if (UseSelect && 9228 LHS->getType() == CmpInst::makeCmpResultType(LHS->getType())) 9229 return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name); 9230 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 9231 Name); 9232 case RecurKind::Add: 9233 case RecurKind::Mul: 9234 case RecurKind::Xor: 9235 case RecurKind::FAdd: 9236 case RecurKind::FMul: 9237 return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS, 9238 Name); 9239 case RecurKind::FMax: 9240 return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS); 9241 case RecurKind::FMin: 9242 return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS); 9243 case RecurKind::SMax: 9244 if (UseSelect) { 9245 Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name); 9246 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 9247 } 9248 return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS); 9249 case RecurKind::SMin: 9250 if (UseSelect) { 9251 Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name); 9252 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 9253 } 9254 return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS); 9255 case RecurKind::UMax: 9256 if (UseSelect) { 9257 Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name); 9258 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 9259 } 9260 return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS); 9261 case RecurKind::UMin: 9262 if (UseSelect) { 9263 Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name); 9264 return Builder.CreateSelect(Cmp, LHS, RHS, Name); 9265 } 9266 return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS); 9267 default: 9268 llvm_unreachable("Unknown reduction operation."); 9269 } 9270 } 9271 9272 /// Creates reduction operation with the current opcode with the IR flags 9273 /// from \p ReductionOps. 9274 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 9275 Value *RHS, const Twine &Name, 9276 const ReductionOpsListType &ReductionOps) { 9277 bool UseSelect = ReductionOps.size() == 2 || 9278 // Logical or/and. 9279 (ReductionOps.size() == 1 && 9280 isa<SelectInst>(ReductionOps.front().front())); 9281 assert((!UseSelect || ReductionOps.size() != 2 || 9282 isa<SelectInst>(ReductionOps[1][0])) && 9283 "Expected cmp + select pairs for reduction"); 9284 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect); 9285 if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 9286 if (auto *Sel = dyn_cast<SelectInst>(Op)) { 9287 propagateIRFlags(Sel->getCondition(), ReductionOps[0]); 9288 propagateIRFlags(Op, ReductionOps[1]); 9289 return Op; 9290 } 9291 } 9292 propagateIRFlags(Op, ReductionOps[0]); 9293 return Op; 9294 } 9295 9296 /// Creates reduction operation with the current opcode with the IR flags 9297 /// from \p I. 9298 static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS, 9299 Value *RHS, const Twine &Name, Instruction *I) { 9300 auto *SelI = dyn_cast<SelectInst>(I); 9301 Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr); 9302 if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) { 9303 if (auto *Sel = dyn_cast<SelectInst>(Op)) 9304 propagateIRFlags(Sel->getCondition(), SelI->getCondition()); 9305 } 9306 propagateIRFlags(Op, I); 9307 return Op; 9308 } 9309 9310 static RecurKind getRdxKind(Instruction *I) { 9311 assert(I && "Expected instruction for reduction matching"); 9312 if (match(I, m_Add(m_Value(), m_Value()))) 9313 return RecurKind::Add; 9314 if (match(I, m_Mul(m_Value(), m_Value()))) 9315 return RecurKind::Mul; 9316 if (match(I, m_And(m_Value(), m_Value())) || 9317 match(I, m_LogicalAnd(m_Value(), m_Value()))) 9318 return RecurKind::And; 9319 if (match(I, m_Or(m_Value(), m_Value())) || 9320 match(I, m_LogicalOr(m_Value(), m_Value()))) 9321 return RecurKind::Or; 9322 if (match(I, m_Xor(m_Value(), m_Value()))) 9323 return RecurKind::Xor; 9324 if (match(I, m_FAdd(m_Value(), m_Value()))) 9325 return RecurKind::FAdd; 9326 if (match(I, m_FMul(m_Value(), m_Value()))) 9327 return RecurKind::FMul; 9328 9329 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value()))) 9330 return RecurKind::FMax; 9331 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value()))) 9332 return RecurKind::FMin; 9333 9334 // This matches either cmp+select or intrinsics. SLP is expected to handle 9335 // either form. 9336 // TODO: If we are canonicalizing to intrinsics, we can remove several 9337 // special-case paths that deal with selects. 9338 if (match(I, m_SMax(m_Value(), m_Value()))) 9339 return RecurKind::SMax; 9340 if (match(I, m_SMin(m_Value(), m_Value()))) 9341 return RecurKind::SMin; 9342 if (match(I, m_UMax(m_Value(), m_Value()))) 9343 return RecurKind::UMax; 9344 if (match(I, m_UMin(m_Value(), m_Value()))) 9345 return RecurKind::UMin; 9346 9347 if (auto *Select = dyn_cast<SelectInst>(I)) { 9348 // Try harder: look for min/max pattern based on instructions producing 9349 // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2). 9350 // During the intermediate stages of SLP, it's very common to have 9351 // pattern like this (since optimizeGatherSequence is run only once 9352 // at the end): 9353 // %1 = extractelement <2 x i32> %a, i32 0 9354 // %2 = extractelement <2 x i32> %a, i32 1 9355 // %cond = icmp sgt i32 %1, %2 9356 // %3 = extractelement <2 x i32> %a, i32 0 9357 // %4 = extractelement <2 x i32> %a, i32 1 9358 // %select = select i1 %cond, i32 %3, i32 %4 9359 CmpInst::Predicate Pred; 9360 Instruction *L1; 9361 Instruction *L2; 9362 9363 Value *LHS = Select->getTrueValue(); 9364 Value *RHS = Select->getFalseValue(); 9365 Value *Cond = Select->getCondition(); 9366 9367 // TODO: Support inverse predicates. 9368 if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) { 9369 if (!isa<ExtractElementInst>(RHS) || 9370 !L2->isIdenticalTo(cast<Instruction>(RHS))) 9371 return RecurKind::None; 9372 } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) { 9373 if (!isa<ExtractElementInst>(LHS) || 9374 !L1->isIdenticalTo(cast<Instruction>(LHS))) 9375 return RecurKind::None; 9376 } else { 9377 if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS)) 9378 return RecurKind::None; 9379 if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) || 9380 !L1->isIdenticalTo(cast<Instruction>(LHS)) || 9381 !L2->isIdenticalTo(cast<Instruction>(RHS))) 9382 return RecurKind::None; 9383 } 9384 9385 switch (Pred) { 9386 default: 9387 return RecurKind::None; 9388 case CmpInst::ICMP_SGT: 9389 case CmpInst::ICMP_SGE: 9390 return RecurKind::SMax; 9391 case CmpInst::ICMP_SLT: 9392 case CmpInst::ICMP_SLE: 9393 return RecurKind::SMin; 9394 case CmpInst::ICMP_UGT: 9395 case CmpInst::ICMP_UGE: 9396 return RecurKind::UMax; 9397 case CmpInst::ICMP_ULT: 9398 case CmpInst::ICMP_ULE: 9399 return RecurKind::UMin; 9400 } 9401 } 9402 return RecurKind::None; 9403 } 9404 9405 /// Get the index of the first operand. 9406 static unsigned getFirstOperandIndex(Instruction *I) { 9407 return isCmpSelMinMax(I) ? 1 : 0; 9408 } 9409 9410 /// Total number of operands in the reduction operation. 9411 static unsigned getNumberOfOperands(Instruction *I) { 9412 return isCmpSelMinMax(I) ? 3 : 2; 9413 } 9414 9415 /// Checks if the instruction is in basic block \p BB. 9416 /// For a cmp+sel min/max reduction check that both ops are in \p BB. 9417 static bool hasSameParent(Instruction *I, BasicBlock *BB) { 9418 if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) { 9419 auto *Sel = cast<SelectInst>(I); 9420 auto *Cmp = dyn_cast<Instruction>(Sel->getCondition()); 9421 return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB; 9422 } 9423 return I->getParent() == BB; 9424 } 9425 9426 /// Expected number of uses for reduction operations/reduced values. 9427 static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) { 9428 if (IsCmpSelMinMax) { 9429 // SelectInst must be used twice while the condition op must have single 9430 // use only. 9431 if (auto *Sel = dyn_cast<SelectInst>(I)) 9432 return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse(); 9433 return I->hasNUses(2); 9434 } 9435 9436 // Arithmetic reduction operation must be used once only. 9437 return I->hasOneUse(); 9438 } 9439 9440 /// Initializes the list of reduction operations. 9441 void initReductionOps(Instruction *I) { 9442 if (isCmpSelMinMax(I)) 9443 ReductionOps.assign(2, ReductionOpsType()); 9444 else 9445 ReductionOps.assign(1, ReductionOpsType()); 9446 } 9447 9448 /// Add all reduction operations for the reduction instruction \p I. 9449 void addReductionOps(Instruction *I) { 9450 if (isCmpSelMinMax(I)) { 9451 ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition()); 9452 ReductionOps[1].emplace_back(I); 9453 } else { 9454 ReductionOps[0].emplace_back(I); 9455 } 9456 } 9457 9458 static Value *getLHS(RecurKind Kind, Instruction *I) { 9459 if (Kind == RecurKind::None) 9460 return nullptr; 9461 return I->getOperand(getFirstOperandIndex(I)); 9462 } 9463 static Value *getRHS(RecurKind Kind, Instruction *I) { 9464 if (Kind == RecurKind::None) 9465 return nullptr; 9466 return I->getOperand(getFirstOperandIndex(I) + 1); 9467 } 9468 9469 public: 9470 HorizontalReduction() = default; 9471 9472 /// Try to find a reduction tree. 9473 bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) { 9474 assert((!Phi || is_contained(Phi->operands(), Inst)) && 9475 "Phi needs to use the binary operator"); 9476 assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) || 9477 isa<IntrinsicInst>(Inst)) && 9478 "Expected binop, select, or intrinsic for reduction matching"); 9479 RdxKind = getRdxKind(Inst); 9480 9481 // We could have a initial reductions that is not an add. 9482 // r *= v1 + v2 + v3 + v4 9483 // In such a case start looking for a tree rooted in the first '+'. 9484 if (Phi) { 9485 if (getLHS(RdxKind, Inst) == Phi) { 9486 Phi = nullptr; 9487 Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst)); 9488 if (!Inst) 9489 return false; 9490 RdxKind = getRdxKind(Inst); 9491 } else if (getRHS(RdxKind, Inst) == Phi) { 9492 Phi = nullptr; 9493 Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst)); 9494 if (!Inst) 9495 return false; 9496 RdxKind = getRdxKind(Inst); 9497 } 9498 } 9499 9500 if (!isVectorizable(RdxKind, Inst)) 9501 return false; 9502 9503 // Analyze "regular" integer/FP types for reductions - no target-specific 9504 // types or pointers. 9505 Type *Ty = Inst->getType(); 9506 if (!isValidElementType(Ty) || Ty->isPointerTy()) 9507 return false; 9508 9509 // Though the ultimate reduction may have multiple uses, its condition must 9510 // have only single use. 9511 if (auto *Sel = dyn_cast<SelectInst>(Inst)) 9512 if (!Sel->getCondition()->hasOneUse()) 9513 return false; 9514 9515 ReductionRoot = Inst; 9516 9517 // The opcode for leaf values that we perform a reduction on. 9518 // For example: load(x) + load(y) + load(z) + fptoui(w) 9519 // The leaf opcode for 'w' does not match, so we don't include it as a 9520 // potential candidate for the reduction. 9521 unsigned LeafOpcode = 0; 9522 9523 // Post-order traverse the reduction tree starting at Inst. We only handle 9524 // true trees containing binary operators or selects. 9525 SmallVector<std::pair<Instruction *, unsigned>, 32> Stack; 9526 Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst))); 9527 initReductionOps(Inst); 9528 while (!Stack.empty()) { 9529 Instruction *TreeN = Stack.back().first; 9530 unsigned EdgeToVisit = Stack.back().second++; 9531 const RecurKind TreeRdxKind = getRdxKind(TreeN); 9532 bool IsReducedValue = TreeRdxKind != RdxKind; 9533 9534 // Postorder visit. 9535 if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) { 9536 if (IsReducedValue) 9537 ReducedVals.push_back(TreeN); 9538 else { 9539 auto ExtraArgsIter = ExtraArgs.find(TreeN); 9540 if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) { 9541 // Check if TreeN is an extra argument of its parent operation. 9542 if (Stack.size() <= 1) { 9543 // TreeN can't be an extra argument as it is a root reduction 9544 // operation. 9545 return false; 9546 } 9547 // Yes, TreeN is an extra argument, do not add it to a list of 9548 // reduction operations. 9549 // Stack[Stack.size() - 2] always points to the parent operation. 9550 markExtraArg(Stack[Stack.size() - 2], TreeN); 9551 ExtraArgs.erase(TreeN); 9552 } else 9553 addReductionOps(TreeN); 9554 } 9555 // Retract. 9556 Stack.pop_back(); 9557 continue; 9558 } 9559 9560 // Visit operands. 9561 Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit); 9562 auto *EdgeInst = dyn_cast<Instruction>(EdgeVal); 9563 if (!EdgeInst) { 9564 // Edge value is not a reduction instruction or a leaf instruction. 9565 // (It may be a constant, function argument, or something else.) 9566 markExtraArg(Stack.back(), EdgeVal); 9567 continue; 9568 } 9569 RecurKind EdgeRdxKind = getRdxKind(EdgeInst); 9570 // Continue analysis if the next operand is a reduction operation or 9571 // (possibly) a leaf value. If the leaf value opcode is not set, 9572 // the first met operation != reduction operation is considered as the 9573 // leaf opcode. 9574 // Only handle trees in the current basic block. 9575 // Each tree node needs to have minimal number of users except for the 9576 // ultimate reduction. 9577 const bool IsRdxInst = EdgeRdxKind == RdxKind; 9578 if (EdgeInst != Phi && EdgeInst != Inst && 9579 hasSameParent(EdgeInst, Inst->getParent()) && 9580 hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) && 9581 (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) { 9582 if (IsRdxInst) { 9583 // We need to be able to reassociate the reduction operations. 9584 if (!isVectorizable(EdgeRdxKind, EdgeInst)) { 9585 // I is an extra argument for TreeN (its parent operation). 9586 markExtraArg(Stack.back(), EdgeInst); 9587 continue; 9588 } 9589 } else if (!LeafOpcode) { 9590 LeafOpcode = EdgeInst->getOpcode(); 9591 } 9592 Stack.push_back( 9593 std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst))); 9594 continue; 9595 } 9596 // I is an extra argument for TreeN (its parent operation). 9597 markExtraArg(Stack.back(), EdgeInst); 9598 } 9599 return true; 9600 } 9601 9602 /// Attempt to vectorize the tree found by matchAssociativeReduction. 9603 Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) { 9604 // If there are a sufficient number of reduction values, reduce 9605 // to a nearby power-of-2. We can safely generate oversized 9606 // vectors and rely on the backend to split them to legal sizes. 9607 unsigned NumReducedVals = ReducedVals.size(); 9608 if (NumReducedVals < 4) 9609 return nullptr; 9610 9611 // Intersect the fast-math-flags from all reduction operations. 9612 FastMathFlags RdxFMF; 9613 RdxFMF.set(); 9614 for (ReductionOpsType &RdxOp : ReductionOps) { 9615 for (Value *RdxVal : RdxOp) { 9616 if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal)) 9617 RdxFMF &= FPMO->getFastMathFlags(); 9618 } 9619 } 9620 9621 IRBuilder<> Builder(cast<Instruction>(ReductionRoot)); 9622 Builder.setFastMathFlags(RdxFMF); 9623 9624 BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues; 9625 // The same extra argument may be used several times, so log each attempt 9626 // to use it. 9627 for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) { 9628 assert(Pair.first && "DebugLoc must be set."); 9629 ExternallyUsedValues[Pair.second].push_back(Pair.first); 9630 } 9631 9632 // The compare instruction of a min/max is the insertion point for new 9633 // instructions and may be replaced with a new compare instruction. 9634 auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) { 9635 assert(isa<SelectInst>(RdxRootInst) && 9636 "Expected min/max reduction to have select root instruction"); 9637 Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition(); 9638 assert(isa<Instruction>(ScalarCond) && 9639 "Expected min/max reduction to have compare condition"); 9640 return cast<Instruction>(ScalarCond); 9641 }; 9642 9643 // The reduction root is used as the insertion point for new instructions, 9644 // so set it as externally used to prevent it from being deleted. 9645 ExternallyUsedValues[ReductionRoot]; 9646 SmallVector<Value *, 16> IgnoreList; 9647 for (ReductionOpsType &RdxOp : ReductionOps) 9648 IgnoreList.append(RdxOp.begin(), RdxOp.end()); 9649 9650 unsigned ReduxWidth = PowerOf2Floor(NumReducedVals); 9651 if (NumReducedVals > ReduxWidth) { 9652 // In the loop below, we are building a tree based on a window of 9653 // 'ReduxWidth' values. 9654 // If the operands of those values have common traits (compare predicate, 9655 // constant operand, etc), then we want to group those together to 9656 // minimize the cost of the reduction. 9657 9658 // TODO: This should be extended to count common operands for 9659 // compares and binops. 9660 9661 // Step 1: Count the number of times each compare predicate occurs. 9662 SmallDenseMap<unsigned, unsigned> PredCountMap; 9663 for (Value *RdxVal : ReducedVals) { 9664 CmpInst::Predicate Pred; 9665 if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value()))) 9666 ++PredCountMap[Pred]; 9667 } 9668 // Step 2: Sort the values so the most common predicates come first. 9669 stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) { 9670 CmpInst::Predicate PredA, PredB; 9671 if (match(A, m_Cmp(PredA, m_Value(), m_Value())) && 9672 match(B, m_Cmp(PredB, m_Value(), m_Value()))) { 9673 return PredCountMap[PredA] > PredCountMap[PredB]; 9674 } 9675 return false; 9676 }); 9677 } 9678 9679 Value *VectorizedTree = nullptr; 9680 unsigned i = 0; 9681 while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) { 9682 ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth); 9683 V.buildTree(VL, IgnoreList); 9684 if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) 9685 break; 9686 if (V.isLoadCombineReductionCandidate(RdxKind)) 9687 break; 9688 V.reorderTopToBottom(); 9689 V.reorderBottomToTop(/*IgnoreReorder=*/true); 9690 V.buildExternalUses(ExternallyUsedValues); 9691 9692 // For a poison-safe boolean logic reduction, do not replace select 9693 // instructions with logic ops. All reduced values will be frozen (see 9694 // below) to prevent leaking poison. 9695 if (isa<SelectInst>(ReductionRoot) && 9696 isBoolLogicOp(cast<Instruction>(ReductionRoot)) && 9697 NumReducedVals != ReduxWidth) 9698 break; 9699 9700 V.computeMinimumValueSizes(); 9701 9702 // Estimate cost. 9703 InstructionCost TreeCost = 9704 V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth)); 9705 InstructionCost ReductionCost = 9706 getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF); 9707 InstructionCost Cost = TreeCost + ReductionCost; 9708 if (!Cost.isValid()) { 9709 LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n"); 9710 return nullptr; 9711 } 9712 if (Cost >= -SLPCostThreshold) { 9713 V.getORE()->emit([&]() { 9714 return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial", 9715 cast<Instruction>(VL[0])) 9716 << "Vectorizing horizontal reduction is possible" 9717 << "but not beneficial with cost " << ore::NV("Cost", Cost) 9718 << " and threshold " 9719 << ore::NV("Threshold", -SLPCostThreshold); 9720 }); 9721 break; 9722 } 9723 9724 LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" 9725 << Cost << ". (HorRdx)\n"); 9726 V.getORE()->emit([&]() { 9727 return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction", 9728 cast<Instruction>(VL[0])) 9729 << "Vectorized horizontal reduction with cost " 9730 << ore::NV("Cost", Cost) << " and with tree size " 9731 << ore::NV("TreeSize", V.getTreeSize()); 9732 }); 9733 9734 // Vectorize a tree. 9735 DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc(); 9736 Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues); 9737 9738 // Emit a reduction. If the root is a select (min/max idiom), the insert 9739 // point is the compare condition of that select. 9740 Instruction *RdxRootInst = cast<Instruction>(ReductionRoot); 9741 if (isCmpSelMinMax(RdxRootInst)) 9742 Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst)); 9743 else 9744 Builder.SetInsertPoint(RdxRootInst); 9745 9746 // To prevent poison from leaking across what used to be sequential, safe, 9747 // scalar boolean logic operations, the reduction operand must be frozen. 9748 if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst)) 9749 VectorizedRoot = Builder.CreateFreeze(VectorizedRoot); 9750 9751 Value *ReducedSubTree = 9752 emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI); 9753 9754 if (!VectorizedTree) { 9755 // Initialize the final value in the reduction. 9756 VectorizedTree = ReducedSubTree; 9757 } else { 9758 // Update the final value in the reduction. 9759 Builder.SetCurrentDebugLocation(Loc); 9760 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 9761 ReducedSubTree, "op.rdx", ReductionOps); 9762 } 9763 i += ReduxWidth; 9764 ReduxWidth = PowerOf2Floor(NumReducedVals - i); 9765 } 9766 9767 if (VectorizedTree) { 9768 // Finish the reduction. 9769 for (; i < NumReducedVals; ++i) { 9770 auto *I = cast<Instruction>(ReducedVals[i]); 9771 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 9772 VectorizedTree = 9773 createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps); 9774 } 9775 for (auto &Pair : ExternallyUsedValues) { 9776 // Add each externally used value to the final reduction. 9777 for (auto *I : Pair.second) { 9778 Builder.SetCurrentDebugLocation(I->getDebugLoc()); 9779 VectorizedTree = createOp(Builder, RdxKind, VectorizedTree, 9780 Pair.first, "op.extra", I); 9781 } 9782 } 9783 9784 ReductionRoot->replaceAllUsesWith(VectorizedTree); 9785 9786 // Mark all scalar reduction ops for deletion, they are replaced by the 9787 // vector reductions. 9788 V.eraseInstructions(IgnoreList); 9789 } 9790 return VectorizedTree; 9791 } 9792 9793 unsigned numReductionValues() const { return ReducedVals.size(); } 9794 9795 private: 9796 /// Calculate the cost of a reduction. 9797 InstructionCost getReductionCost(TargetTransformInfo *TTI, 9798 Value *FirstReducedVal, unsigned ReduxWidth, 9799 FastMathFlags FMF) { 9800 TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput; 9801 Type *ScalarTy = FirstReducedVal->getType(); 9802 FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth); 9803 InstructionCost VectorCost, ScalarCost; 9804 switch (RdxKind) { 9805 case RecurKind::Add: 9806 case RecurKind::Mul: 9807 case RecurKind::Or: 9808 case RecurKind::And: 9809 case RecurKind::Xor: 9810 case RecurKind::FAdd: 9811 case RecurKind::FMul: { 9812 unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind); 9813 VectorCost = 9814 TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind); 9815 ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind); 9816 break; 9817 } 9818 case RecurKind::FMax: 9819 case RecurKind::FMin: { 9820 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 9821 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 9822 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, 9823 /*IsUnsigned=*/false, CostKind); 9824 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 9825 ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy, 9826 SclCondTy, RdxPred, CostKind) + 9827 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 9828 SclCondTy, RdxPred, CostKind); 9829 break; 9830 } 9831 case RecurKind::SMax: 9832 case RecurKind::SMin: 9833 case RecurKind::UMax: 9834 case RecurKind::UMin: { 9835 auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy); 9836 auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy)); 9837 bool IsUnsigned = 9838 RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin; 9839 VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned, 9840 CostKind); 9841 CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind); 9842 ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy, 9843 SclCondTy, RdxPred, CostKind) + 9844 TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy, 9845 SclCondTy, RdxPred, CostKind); 9846 break; 9847 } 9848 default: 9849 llvm_unreachable("Expected arithmetic or min/max reduction operation"); 9850 } 9851 9852 // Scalar cost is repeated for N-1 elements. 9853 ScalarCost *= (ReduxWidth - 1); 9854 LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost 9855 << " for reduction that starts with " << *FirstReducedVal 9856 << " (It is a splitting reduction)\n"); 9857 return VectorCost - ScalarCost; 9858 } 9859 9860 /// Emit a horizontal reduction of the vectorized value. 9861 Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder, 9862 unsigned ReduxWidth, const TargetTransformInfo *TTI) { 9863 assert(VectorizedValue && "Need to have a vectorized tree node"); 9864 assert(isPowerOf2_32(ReduxWidth) && 9865 "We only handle power-of-two reductions for now"); 9866 assert(RdxKind != RecurKind::FMulAdd && 9867 "A call to the llvm.fmuladd intrinsic is not handled yet"); 9868 9869 ++NumVectorInstructions; 9870 return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind); 9871 } 9872 }; 9873 9874 } // end anonymous namespace 9875 9876 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) { 9877 if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) 9878 return cast<FixedVectorType>(IE->getType())->getNumElements(); 9879 9880 unsigned AggregateSize = 1; 9881 auto *IV = cast<InsertValueInst>(InsertInst); 9882 Type *CurrentType = IV->getType(); 9883 do { 9884 if (auto *ST = dyn_cast<StructType>(CurrentType)) { 9885 for (auto *Elt : ST->elements()) 9886 if (Elt != ST->getElementType(0)) // check homogeneity 9887 return None; 9888 AggregateSize *= ST->getNumElements(); 9889 CurrentType = ST->getElementType(0); 9890 } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) { 9891 AggregateSize *= AT->getNumElements(); 9892 CurrentType = AT->getElementType(); 9893 } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) { 9894 AggregateSize *= VT->getNumElements(); 9895 return AggregateSize; 9896 } else if (CurrentType->isSingleValueType()) { 9897 return AggregateSize; 9898 } else { 9899 return None; 9900 } 9901 } while (true); 9902 } 9903 9904 static void findBuildAggregate_rec(Instruction *LastInsertInst, 9905 TargetTransformInfo *TTI, 9906 SmallVectorImpl<Value *> &BuildVectorOpds, 9907 SmallVectorImpl<Value *> &InsertElts, 9908 unsigned OperandOffset) { 9909 do { 9910 Value *InsertedOperand = LastInsertInst->getOperand(1); 9911 Optional<unsigned> OperandIndex = 9912 getInsertIndex(LastInsertInst, OperandOffset); 9913 if (!OperandIndex) 9914 return; 9915 if (isa<InsertElementInst>(InsertedOperand) || 9916 isa<InsertValueInst>(InsertedOperand)) { 9917 findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI, 9918 BuildVectorOpds, InsertElts, *OperandIndex); 9919 9920 } else { 9921 BuildVectorOpds[*OperandIndex] = InsertedOperand; 9922 InsertElts[*OperandIndex] = LastInsertInst; 9923 } 9924 LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0)); 9925 } while (LastInsertInst != nullptr && 9926 (isa<InsertValueInst>(LastInsertInst) || 9927 isa<InsertElementInst>(LastInsertInst)) && 9928 LastInsertInst->hasOneUse()); 9929 } 9930 9931 /// Recognize construction of vectors like 9932 /// %ra = insertelement <4 x float> poison, float %s0, i32 0 9933 /// %rb = insertelement <4 x float> %ra, float %s1, i32 1 9934 /// %rc = insertelement <4 x float> %rb, float %s2, i32 2 9935 /// %rd = insertelement <4 x float> %rc, float %s3, i32 3 9936 /// starting from the last insertelement or insertvalue instruction. 9937 /// 9938 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>}, 9939 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on. 9940 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples. 9941 /// 9942 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type. 9943 /// 9944 /// \return true if it matches. 9945 static bool findBuildAggregate(Instruction *LastInsertInst, 9946 TargetTransformInfo *TTI, 9947 SmallVectorImpl<Value *> &BuildVectorOpds, 9948 SmallVectorImpl<Value *> &InsertElts) { 9949 9950 assert((isa<InsertElementInst>(LastInsertInst) || 9951 isa<InsertValueInst>(LastInsertInst)) && 9952 "Expected insertelement or insertvalue instruction!"); 9953 9954 assert((BuildVectorOpds.empty() && InsertElts.empty()) && 9955 "Expected empty result vectors!"); 9956 9957 Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst); 9958 if (!AggregateSize) 9959 return false; 9960 BuildVectorOpds.resize(*AggregateSize); 9961 InsertElts.resize(*AggregateSize); 9962 9963 findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0); 9964 llvm::erase_value(BuildVectorOpds, nullptr); 9965 llvm::erase_value(InsertElts, nullptr); 9966 if (BuildVectorOpds.size() >= 2) 9967 return true; 9968 9969 return false; 9970 } 9971 9972 /// Try and get a reduction value from a phi node. 9973 /// 9974 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions 9975 /// if they come from either \p ParentBB or a containing loop latch. 9976 /// 9977 /// \returns A candidate reduction value if possible, or \code nullptr \endcode 9978 /// if not possible. 9979 static Value *getReductionValue(const DominatorTree *DT, PHINode *P, 9980 BasicBlock *ParentBB, LoopInfo *LI) { 9981 // There are situations where the reduction value is not dominated by the 9982 // reduction phi. Vectorizing such cases has been reported to cause 9983 // miscompiles. See PR25787. 9984 auto DominatedReduxValue = [&](Value *R) { 9985 return isa<Instruction>(R) && 9986 DT->dominates(P->getParent(), cast<Instruction>(R)->getParent()); 9987 }; 9988 9989 Value *Rdx = nullptr; 9990 9991 // Return the incoming value if it comes from the same BB as the phi node. 9992 if (P->getIncomingBlock(0) == ParentBB) { 9993 Rdx = P->getIncomingValue(0); 9994 } else if (P->getIncomingBlock(1) == ParentBB) { 9995 Rdx = P->getIncomingValue(1); 9996 } 9997 9998 if (Rdx && DominatedReduxValue(Rdx)) 9999 return Rdx; 10000 10001 // Otherwise, check whether we have a loop latch to look at. 10002 Loop *BBL = LI->getLoopFor(ParentBB); 10003 if (!BBL) 10004 return nullptr; 10005 BasicBlock *BBLatch = BBL->getLoopLatch(); 10006 if (!BBLatch) 10007 return nullptr; 10008 10009 // There is a loop latch, return the incoming value if it comes from 10010 // that. This reduction pattern occasionally turns up. 10011 if (P->getIncomingBlock(0) == BBLatch) { 10012 Rdx = P->getIncomingValue(0); 10013 } else if (P->getIncomingBlock(1) == BBLatch) { 10014 Rdx = P->getIncomingValue(1); 10015 } 10016 10017 if (Rdx && DominatedReduxValue(Rdx)) 10018 return Rdx; 10019 10020 return nullptr; 10021 } 10022 10023 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) { 10024 if (match(I, m_BinOp(m_Value(V0), m_Value(V1)))) 10025 return true; 10026 if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1)))) 10027 return true; 10028 if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1)))) 10029 return true; 10030 if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1)))) 10031 return true; 10032 if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1)))) 10033 return true; 10034 if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1)))) 10035 return true; 10036 if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1)))) 10037 return true; 10038 return false; 10039 } 10040 10041 /// Attempt to reduce a horizontal reduction. 10042 /// If it is legal to match a horizontal reduction feeding the phi node \a P 10043 /// with reduction operators \a Root (or one of its operands) in a basic block 10044 /// \a BB, then check if it can be done. If horizontal reduction is not found 10045 /// and root instruction is a binary operation, vectorization of the operands is 10046 /// attempted. 10047 /// \returns true if a horizontal reduction was matched and reduced or operands 10048 /// of one of the binary instruction were vectorized. 10049 /// \returns false if a horizontal reduction was not matched (or not possible) 10050 /// or no vectorization of any binary operation feeding \a Root instruction was 10051 /// performed. 10052 static bool tryToVectorizeHorReductionOrInstOperands( 10053 PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R, 10054 TargetTransformInfo *TTI, 10055 const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) { 10056 if (!ShouldVectorizeHor) 10057 return false; 10058 10059 if (!Root) 10060 return false; 10061 10062 if (Root->getParent() != BB || isa<PHINode>(Root)) 10063 return false; 10064 // Start analysis starting from Root instruction. If horizontal reduction is 10065 // found, try to vectorize it. If it is not a horizontal reduction or 10066 // vectorization is not possible or not effective, and currently analyzed 10067 // instruction is a binary operation, try to vectorize the operands, using 10068 // pre-order DFS traversal order. If the operands were not vectorized, repeat 10069 // the same procedure considering each operand as a possible root of the 10070 // horizontal reduction. 10071 // Interrupt the process if the Root instruction itself was vectorized or all 10072 // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized. 10073 // Skip the analysis of CmpInsts.Compiler implements postanalysis of the 10074 // CmpInsts so we can skip extra attempts in 10075 // tryToVectorizeHorReductionOrInstOperands and save compile time. 10076 std::queue<std::pair<Instruction *, unsigned>> Stack; 10077 Stack.emplace(Root, 0); 10078 SmallPtrSet<Value *, 8> VisitedInstrs; 10079 SmallVector<WeakTrackingVH> PostponedInsts; 10080 bool Res = false; 10081 auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0, 10082 Value *&B1) -> Value * { 10083 bool IsBinop = matchRdxBop(Inst, B0, B1); 10084 bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value())); 10085 if (IsBinop || IsSelect) { 10086 HorizontalReduction HorRdx; 10087 if (HorRdx.matchAssociativeReduction(P, Inst)) 10088 return HorRdx.tryToReduce(R, TTI); 10089 } 10090 return nullptr; 10091 }; 10092 while (!Stack.empty()) { 10093 Instruction *Inst; 10094 unsigned Level; 10095 std::tie(Inst, Level) = Stack.front(); 10096 Stack.pop(); 10097 // Do not try to analyze instruction that has already been vectorized. 10098 // This may happen when we vectorize instruction operands on a previous 10099 // iteration while stack was populated before that happened. 10100 if (R.isDeleted(Inst)) 10101 continue; 10102 Value *B0 = nullptr, *B1 = nullptr; 10103 if (Value *V = TryToReduce(Inst, B0, B1)) { 10104 Res = true; 10105 // Set P to nullptr to avoid re-analysis of phi node in 10106 // matchAssociativeReduction function unless this is the root node. 10107 P = nullptr; 10108 if (auto *I = dyn_cast<Instruction>(V)) { 10109 // Try to find another reduction. 10110 Stack.emplace(I, Level); 10111 continue; 10112 } 10113 } else { 10114 bool IsBinop = B0 && B1; 10115 if (P && IsBinop) { 10116 Inst = dyn_cast<Instruction>(B0); 10117 if (Inst == P) 10118 Inst = dyn_cast<Instruction>(B1); 10119 if (!Inst) { 10120 // Set P to nullptr to avoid re-analysis of phi node in 10121 // matchAssociativeReduction function unless this is the root node. 10122 P = nullptr; 10123 continue; 10124 } 10125 } 10126 // Set P to nullptr to avoid re-analysis of phi node in 10127 // matchAssociativeReduction function unless this is the root node. 10128 P = nullptr; 10129 // Do not try to vectorize CmpInst operands, this is done separately. 10130 // Final attempt for binop args vectorization should happen after the loop 10131 // to try to find reductions. 10132 if (!isa<CmpInst>(Inst)) 10133 PostponedInsts.push_back(Inst); 10134 } 10135 10136 // Try to vectorize operands. 10137 // Continue analysis for the instruction from the same basic block only to 10138 // save compile time. 10139 if (++Level < RecursionMaxDepth) 10140 for (auto *Op : Inst->operand_values()) 10141 if (VisitedInstrs.insert(Op).second) 10142 if (auto *I = dyn_cast<Instruction>(Op)) 10143 // Do not try to vectorize CmpInst operands, this is done 10144 // separately. 10145 if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) && 10146 I->getParent() == BB) 10147 Stack.emplace(I, Level); 10148 } 10149 // Try to vectorized binops where reductions were not found. 10150 for (Value *V : PostponedInsts) 10151 if (auto *Inst = dyn_cast<Instruction>(V)) 10152 if (!R.isDeleted(Inst)) 10153 Res |= Vectorize(Inst, R); 10154 return Res; 10155 } 10156 10157 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V, 10158 BasicBlock *BB, BoUpSLP &R, 10159 TargetTransformInfo *TTI) { 10160 auto *I = dyn_cast_or_null<Instruction>(V); 10161 if (!I) 10162 return false; 10163 10164 if (!isa<BinaryOperator>(I)) 10165 P = nullptr; 10166 // Try to match and vectorize a horizontal reduction. 10167 auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool { 10168 return tryToVectorize(I, R); 10169 }; 10170 return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, 10171 ExtraVectorization); 10172 } 10173 10174 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI, 10175 BasicBlock *BB, BoUpSLP &R) { 10176 const DataLayout &DL = BB->getModule()->getDataLayout(); 10177 if (!R.canMapToVector(IVI->getType(), DL)) 10178 return false; 10179 10180 SmallVector<Value *, 16> BuildVectorOpds; 10181 SmallVector<Value *, 16> BuildVectorInsts; 10182 if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts)) 10183 return false; 10184 10185 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n"); 10186 // Aggregate value is unlikely to be processed in vector register. 10187 return tryToVectorizeList(BuildVectorOpds, R); 10188 } 10189 10190 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI, 10191 BasicBlock *BB, BoUpSLP &R) { 10192 SmallVector<Value *, 16> BuildVectorInsts; 10193 SmallVector<Value *, 16> BuildVectorOpds; 10194 SmallVector<int> Mask; 10195 if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) || 10196 (llvm::all_of( 10197 BuildVectorOpds, 10198 [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) && 10199 isFixedVectorShuffle(BuildVectorOpds, Mask))) 10200 return false; 10201 10202 LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n"); 10203 return tryToVectorizeList(BuildVectorInsts, R); 10204 } 10205 10206 template <typename T> 10207 static bool 10208 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming, 10209 function_ref<unsigned(T *)> Limit, 10210 function_ref<bool(T *, T *)> Comparator, 10211 function_ref<bool(T *, T *)> AreCompatible, 10212 function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper, 10213 bool LimitForRegisterSize) { 10214 bool Changed = false; 10215 // Sort by type, parent, operands. 10216 stable_sort(Incoming, Comparator); 10217 10218 // Try to vectorize elements base on their type. 10219 SmallVector<T *> Candidates; 10220 for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) { 10221 // Look for the next elements with the same type, parent and operand 10222 // kinds. 10223 auto *SameTypeIt = IncIt; 10224 while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt)) 10225 ++SameTypeIt; 10226 10227 // Try to vectorize them. 10228 unsigned NumElts = (SameTypeIt - IncIt); 10229 LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes (" 10230 << NumElts << ")\n"); 10231 // The vectorization is a 3-state attempt: 10232 // 1. Try to vectorize instructions with the same/alternate opcodes with the 10233 // size of maximal register at first. 10234 // 2. Try to vectorize remaining instructions with the same type, if 10235 // possible. This may result in the better vectorization results rather than 10236 // if we try just to vectorize instructions with the same/alternate opcodes. 10237 // 3. Final attempt to try to vectorize all instructions with the 10238 // same/alternate ops only, this may result in some extra final 10239 // vectorization. 10240 if (NumElts > 1 && 10241 TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) { 10242 // Success start over because instructions might have been changed. 10243 Changed = true; 10244 } else if (NumElts < Limit(*IncIt) && 10245 (Candidates.empty() || 10246 Candidates.front()->getType() == (*IncIt)->getType())) { 10247 Candidates.append(IncIt, std::next(IncIt, NumElts)); 10248 } 10249 // Final attempt to vectorize instructions with the same types. 10250 if (Candidates.size() > 1 && 10251 (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) { 10252 if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) { 10253 // Success start over because instructions might have been changed. 10254 Changed = true; 10255 } else if (LimitForRegisterSize) { 10256 // Try to vectorize using small vectors. 10257 for (auto *It = Candidates.begin(), *End = Candidates.end(); 10258 It != End;) { 10259 auto *SameTypeIt = It; 10260 while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It)) 10261 ++SameTypeIt; 10262 unsigned NumElts = (SameTypeIt - It); 10263 if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts), 10264 /*LimitForRegisterSize=*/false)) 10265 Changed = true; 10266 It = SameTypeIt; 10267 } 10268 } 10269 Candidates.clear(); 10270 } 10271 10272 // Start over at the next instruction of a different type (or the end). 10273 IncIt = SameTypeIt; 10274 } 10275 return Changed; 10276 } 10277 10278 /// Compare two cmp instructions. If IsCompatibility is true, function returns 10279 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding 10280 /// operands. If IsCompatibility is false, function implements strict weak 10281 /// ordering relation between two cmp instructions, returning true if the first 10282 /// instruction is "less" than the second, i.e. its predicate is less than the 10283 /// predicate of the second or the operands IDs are less than the operands IDs 10284 /// of the second cmp instruction. 10285 template <bool IsCompatibility> 10286 static bool compareCmp(Value *V, Value *V2, 10287 function_ref<bool(Instruction *)> IsDeleted) { 10288 auto *CI1 = cast<CmpInst>(V); 10289 auto *CI2 = cast<CmpInst>(V2); 10290 if (IsDeleted(CI2) || !isValidElementType(CI2->getType())) 10291 return false; 10292 if (CI1->getOperand(0)->getType()->getTypeID() < 10293 CI2->getOperand(0)->getType()->getTypeID()) 10294 return !IsCompatibility; 10295 if (CI1->getOperand(0)->getType()->getTypeID() > 10296 CI2->getOperand(0)->getType()->getTypeID()) 10297 return false; 10298 CmpInst::Predicate Pred1 = CI1->getPredicate(); 10299 CmpInst::Predicate Pred2 = CI2->getPredicate(); 10300 CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1); 10301 CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2); 10302 CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1); 10303 CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2); 10304 if (BasePred1 < BasePred2) 10305 return !IsCompatibility; 10306 if (BasePred1 > BasePred2) 10307 return false; 10308 // Compare operands. 10309 bool LEPreds = Pred1 <= Pred2; 10310 bool GEPreds = Pred1 >= Pred2; 10311 for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) { 10312 auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1); 10313 auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1); 10314 if (Op1->getValueID() < Op2->getValueID()) 10315 return !IsCompatibility; 10316 if (Op1->getValueID() > Op2->getValueID()) 10317 return false; 10318 if (auto *I1 = dyn_cast<Instruction>(Op1)) 10319 if (auto *I2 = dyn_cast<Instruction>(Op2)) { 10320 if (I1->getParent() != I2->getParent()) 10321 return false; 10322 InstructionsState S = getSameOpcode({I1, I2}); 10323 if (S.getOpcode()) 10324 continue; 10325 return false; 10326 } 10327 } 10328 return IsCompatibility; 10329 } 10330 10331 bool SLPVectorizerPass::vectorizeSimpleInstructions( 10332 SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R, 10333 bool AtTerminator) { 10334 bool OpsChanged = false; 10335 SmallVector<Instruction *, 4> PostponedCmps; 10336 for (auto *I : reverse(Instructions)) { 10337 if (R.isDeleted(I)) 10338 continue; 10339 if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) 10340 OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R); 10341 else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) 10342 OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R); 10343 else if (isa<CmpInst>(I)) 10344 PostponedCmps.push_back(I); 10345 } 10346 if (AtTerminator) { 10347 // Try to find reductions first. 10348 for (Instruction *I : PostponedCmps) { 10349 if (R.isDeleted(I)) 10350 continue; 10351 for (Value *Op : I->operands()) 10352 OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI); 10353 } 10354 // Try to vectorize operands as vector bundles. 10355 for (Instruction *I : PostponedCmps) { 10356 if (R.isDeleted(I)) 10357 continue; 10358 OpsChanged |= tryToVectorize(I, R); 10359 } 10360 // Try to vectorize list of compares. 10361 // Sort by type, compare predicate, etc. 10362 auto &&CompareSorter = [&R](Value *V, Value *V2) { 10363 return compareCmp<false>(V, V2, 10364 [&R](Instruction *I) { return R.isDeleted(I); }); 10365 }; 10366 10367 auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) { 10368 if (V1 == V2) 10369 return true; 10370 return compareCmp<true>(V1, V2, 10371 [&R](Instruction *I) { return R.isDeleted(I); }); 10372 }; 10373 auto Limit = [&R](Value *V) { 10374 unsigned EltSize = R.getVectorElementSize(V); 10375 return std::max(2U, R.getMaxVecRegSize() / EltSize); 10376 }; 10377 10378 SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end()); 10379 OpsChanged |= tryToVectorizeSequence<Value>( 10380 Vals, Limit, CompareSorter, AreCompatibleCompares, 10381 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 10382 // Exclude possible reductions from other blocks. 10383 bool ArePossiblyReducedInOtherBlock = 10384 any_of(Candidates, [](Value *V) { 10385 return any_of(V->users(), [V](User *U) { 10386 return isa<SelectInst>(U) && 10387 cast<SelectInst>(U)->getParent() != 10388 cast<Instruction>(V)->getParent(); 10389 }); 10390 }); 10391 if (ArePossiblyReducedInOtherBlock) 10392 return false; 10393 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 10394 }, 10395 /*LimitForRegisterSize=*/true); 10396 Instructions.clear(); 10397 } else { 10398 // Insert in reverse order since the PostponedCmps vector was filled in 10399 // reverse order. 10400 Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend()); 10401 } 10402 return OpsChanged; 10403 } 10404 10405 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) { 10406 bool Changed = false; 10407 SmallVector<Value *, 4> Incoming; 10408 SmallPtrSet<Value *, 16> VisitedInstrs; 10409 // Maps phi nodes to the non-phi nodes found in the use tree for each phi 10410 // node. Allows better to identify the chains that can be vectorized in the 10411 // better way. 10412 DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes; 10413 auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) { 10414 assert(isValidElementType(V1->getType()) && 10415 isValidElementType(V2->getType()) && 10416 "Expected vectorizable types only."); 10417 // It is fine to compare type IDs here, since we expect only vectorizable 10418 // types, like ints, floats and pointers, we don't care about other type. 10419 if (V1->getType()->getTypeID() < V2->getType()->getTypeID()) 10420 return true; 10421 if (V1->getType()->getTypeID() > V2->getType()->getTypeID()) 10422 return false; 10423 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 10424 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 10425 if (Opcodes1.size() < Opcodes2.size()) 10426 return true; 10427 if (Opcodes1.size() > Opcodes2.size()) 10428 return false; 10429 Optional<bool> ConstOrder; 10430 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 10431 // Undefs are compatible with any other value. 10432 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) { 10433 if (!ConstOrder) 10434 ConstOrder = 10435 !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]); 10436 continue; 10437 } 10438 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 10439 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 10440 DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent()); 10441 DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent()); 10442 if (!NodeI1) 10443 return NodeI2 != nullptr; 10444 if (!NodeI2) 10445 return false; 10446 assert((NodeI1 == NodeI2) == 10447 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 10448 "Different nodes should have different DFS numbers"); 10449 if (NodeI1 != NodeI2) 10450 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 10451 InstructionsState S = getSameOpcode({I1, I2}); 10452 if (S.getOpcode()) 10453 continue; 10454 return I1->getOpcode() < I2->getOpcode(); 10455 } 10456 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) { 10457 if (!ConstOrder) 10458 ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID(); 10459 continue; 10460 } 10461 if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID()) 10462 return true; 10463 if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID()) 10464 return false; 10465 } 10466 return ConstOrder && *ConstOrder; 10467 }; 10468 auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) { 10469 if (V1 == V2) 10470 return true; 10471 if (V1->getType() != V2->getType()) 10472 return false; 10473 ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1]; 10474 ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2]; 10475 if (Opcodes1.size() != Opcodes2.size()) 10476 return false; 10477 for (int I = 0, E = Opcodes1.size(); I < E; ++I) { 10478 // Undefs are compatible with any other value. 10479 if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) 10480 continue; 10481 if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I])) 10482 if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) { 10483 if (I1->getParent() != I2->getParent()) 10484 return false; 10485 InstructionsState S = getSameOpcode({I1, I2}); 10486 if (S.getOpcode()) 10487 continue; 10488 return false; 10489 } 10490 if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) 10491 continue; 10492 if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID()) 10493 return false; 10494 } 10495 return true; 10496 }; 10497 auto Limit = [&R](Value *V) { 10498 unsigned EltSize = R.getVectorElementSize(V); 10499 return std::max(2U, R.getMaxVecRegSize() / EltSize); 10500 }; 10501 10502 bool HaveVectorizedPhiNodes = false; 10503 do { 10504 // Collect the incoming values from the PHIs. 10505 Incoming.clear(); 10506 for (Instruction &I : *BB) { 10507 PHINode *P = dyn_cast<PHINode>(&I); 10508 if (!P) 10509 break; 10510 10511 // No need to analyze deleted, vectorized and non-vectorizable 10512 // instructions. 10513 if (!VisitedInstrs.count(P) && !R.isDeleted(P) && 10514 isValidElementType(P->getType())) 10515 Incoming.push_back(P); 10516 } 10517 10518 // Find the corresponding non-phi nodes for better matching when trying to 10519 // build the tree. 10520 for (Value *V : Incoming) { 10521 SmallVectorImpl<Value *> &Opcodes = 10522 PHIToOpcodes.try_emplace(V).first->getSecond(); 10523 if (!Opcodes.empty()) 10524 continue; 10525 SmallVector<Value *, 4> Nodes(1, V); 10526 SmallPtrSet<Value *, 4> Visited; 10527 while (!Nodes.empty()) { 10528 auto *PHI = cast<PHINode>(Nodes.pop_back_val()); 10529 if (!Visited.insert(PHI).second) 10530 continue; 10531 for (Value *V : PHI->incoming_values()) { 10532 if (auto *PHI1 = dyn_cast<PHINode>((V))) { 10533 Nodes.push_back(PHI1); 10534 continue; 10535 } 10536 Opcodes.emplace_back(V); 10537 } 10538 } 10539 } 10540 10541 HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>( 10542 Incoming, Limit, PHICompare, AreCompatiblePHIs, 10543 [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) { 10544 return tryToVectorizeList(Candidates, R, LimitForRegisterSize); 10545 }, 10546 /*LimitForRegisterSize=*/true); 10547 Changed |= HaveVectorizedPhiNodes; 10548 VisitedInstrs.insert(Incoming.begin(), Incoming.end()); 10549 } while (HaveVectorizedPhiNodes); 10550 10551 VisitedInstrs.clear(); 10552 10553 SmallVector<Instruction *, 8> PostProcessInstructions; 10554 SmallDenseSet<Instruction *, 4> KeyNodes; 10555 for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) { 10556 // Skip instructions with scalable type. The num of elements is unknown at 10557 // compile-time for scalable type. 10558 if (isa<ScalableVectorType>(it->getType())) 10559 continue; 10560 10561 // Skip instructions marked for the deletion. 10562 if (R.isDeleted(&*it)) 10563 continue; 10564 // We may go through BB multiple times so skip the one we have checked. 10565 if (!VisitedInstrs.insert(&*it).second) { 10566 if (it->use_empty() && KeyNodes.contains(&*it) && 10567 vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 10568 it->isTerminator())) { 10569 // We would like to start over since some instructions are deleted 10570 // and the iterator may become invalid value. 10571 Changed = true; 10572 it = BB->begin(); 10573 e = BB->end(); 10574 } 10575 continue; 10576 } 10577 10578 if (isa<DbgInfoIntrinsic>(it)) 10579 continue; 10580 10581 // Try to vectorize reductions that use PHINodes. 10582 if (PHINode *P = dyn_cast<PHINode>(it)) { 10583 // Check that the PHI is a reduction PHI. 10584 if (P->getNumIncomingValues() == 2) { 10585 // Try to match and vectorize a horizontal reduction. 10586 if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R, 10587 TTI)) { 10588 Changed = true; 10589 it = BB->begin(); 10590 e = BB->end(); 10591 continue; 10592 } 10593 } 10594 // Try to vectorize the incoming values of the PHI, to catch reductions 10595 // that feed into PHIs. 10596 for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) { 10597 // Skip if the incoming block is the current BB for now. Also, bypass 10598 // unreachable IR for efficiency and to avoid crashing. 10599 // TODO: Collect the skipped incoming values and try to vectorize them 10600 // after processing BB. 10601 if (BB == P->getIncomingBlock(I) || 10602 !DT->isReachableFromEntry(P->getIncomingBlock(I))) 10603 continue; 10604 10605 Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I), 10606 P->getIncomingBlock(I), R, TTI); 10607 } 10608 continue; 10609 } 10610 10611 // Ran into an instruction without users, like terminator, or function call 10612 // with ignored return value, store. Ignore unused instructions (basing on 10613 // instruction type, except for CallInst and InvokeInst). 10614 if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) || 10615 isa<InvokeInst>(it))) { 10616 KeyNodes.insert(&*it); 10617 bool OpsChanged = false; 10618 if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) { 10619 for (auto *V : it->operand_values()) { 10620 // Try to match and vectorize a horizontal reduction. 10621 OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI); 10622 } 10623 } 10624 // Start vectorization of post-process list of instructions from the 10625 // top-tree instructions to try to vectorize as many instructions as 10626 // possible. 10627 OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R, 10628 it->isTerminator()); 10629 if (OpsChanged) { 10630 // We would like to start over since some instructions are deleted 10631 // and the iterator may become invalid value. 10632 Changed = true; 10633 it = BB->begin(); 10634 e = BB->end(); 10635 continue; 10636 } 10637 } 10638 10639 if (isa<InsertElementInst>(it) || isa<CmpInst>(it) || 10640 isa<InsertValueInst>(it)) 10641 PostProcessInstructions.push_back(&*it); 10642 } 10643 10644 return Changed; 10645 } 10646 10647 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) { 10648 auto Changed = false; 10649 for (auto &Entry : GEPs) { 10650 // If the getelementptr list has fewer than two elements, there's nothing 10651 // to do. 10652 if (Entry.second.size() < 2) 10653 continue; 10654 10655 LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length " 10656 << Entry.second.size() << ".\n"); 10657 10658 // Process the GEP list in chunks suitable for the target's supported 10659 // vector size. If a vector register can't hold 1 element, we are done. We 10660 // are trying to vectorize the index computations, so the maximum number of 10661 // elements is based on the size of the index expression, rather than the 10662 // size of the GEP itself (the target's pointer size). 10663 unsigned MaxVecRegSize = R.getMaxVecRegSize(); 10664 unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin()); 10665 if (MaxVecRegSize < EltSize) 10666 continue; 10667 10668 unsigned MaxElts = MaxVecRegSize / EltSize; 10669 for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) { 10670 auto Len = std::min<unsigned>(BE - BI, MaxElts); 10671 ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len); 10672 10673 // Initialize a set a candidate getelementptrs. Note that we use a 10674 // SetVector here to preserve program order. If the index computations 10675 // are vectorizable and begin with loads, we want to minimize the chance 10676 // of having to reorder them later. 10677 SetVector<Value *> Candidates(GEPList.begin(), GEPList.end()); 10678 10679 // Some of the candidates may have already been vectorized after we 10680 // initially collected them. If so, they are marked as deleted, so remove 10681 // them from the set of candidates. 10682 Candidates.remove_if( 10683 [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); }); 10684 10685 // Remove from the set of candidates all pairs of getelementptrs with 10686 // constant differences. Such getelementptrs are likely not good 10687 // candidates for vectorization in a bottom-up phase since one can be 10688 // computed from the other. We also ensure all candidate getelementptr 10689 // indices are unique. 10690 for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) { 10691 auto *GEPI = GEPList[I]; 10692 if (!Candidates.count(GEPI)) 10693 continue; 10694 auto *SCEVI = SE->getSCEV(GEPList[I]); 10695 for (int J = I + 1; J < E && Candidates.size() > 1; ++J) { 10696 auto *GEPJ = GEPList[J]; 10697 auto *SCEVJ = SE->getSCEV(GEPList[J]); 10698 if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) { 10699 Candidates.remove(GEPI); 10700 Candidates.remove(GEPJ); 10701 } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) { 10702 Candidates.remove(GEPJ); 10703 } 10704 } 10705 } 10706 10707 // We break out of the above computation as soon as we know there are 10708 // fewer than two candidates remaining. 10709 if (Candidates.size() < 2) 10710 continue; 10711 10712 // Add the single, non-constant index of each candidate to the bundle. We 10713 // ensured the indices met these constraints when we originally collected 10714 // the getelementptrs. 10715 SmallVector<Value *, 16> Bundle(Candidates.size()); 10716 auto BundleIndex = 0u; 10717 for (auto *V : Candidates) { 10718 auto *GEP = cast<GetElementPtrInst>(V); 10719 auto *GEPIdx = GEP->idx_begin()->get(); 10720 assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx)); 10721 Bundle[BundleIndex++] = GEPIdx; 10722 } 10723 10724 // Try and vectorize the indices. We are currently only interested in 10725 // gather-like cases of the form: 10726 // 10727 // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ... 10728 // 10729 // where the loads of "a", the loads of "b", and the subtractions can be 10730 // performed in parallel. It's likely that detecting this pattern in a 10731 // bottom-up phase will be simpler and less costly than building a 10732 // full-blown top-down phase beginning at the consecutive loads. 10733 Changed |= tryToVectorizeList(Bundle, R); 10734 } 10735 } 10736 return Changed; 10737 } 10738 10739 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) { 10740 bool Changed = false; 10741 // Sort by type, base pointers and values operand. Value operands must be 10742 // compatible (have the same opcode, same parent), otherwise it is 10743 // definitely not profitable to try to vectorize them. 10744 auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) { 10745 if (V->getPointerOperandType()->getTypeID() < 10746 V2->getPointerOperandType()->getTypeID()) 10747 return true; 10748 if (V->getPointerOperandType()->getTypeID() > 10749 V2->getPointerOperandType()->getTypeID()) 10750 return false; 10751 // UndefValues are compatible with all other values. 10752 if (isa<UndefValue>(V->getValueOperand()) || 10753 isa<UndefValue>(V2->getValueOperand())) 10754 return false; 10755 if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand())) 10756 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 10757 DomTreeNodeBase<llvm::BasicBlock> *NodeI1 = 10758 DT->getNode(I1->getParent()); 10759 DomTreeNodeBase<llvm::BasicBlock> *NodeI2 = 10760 DT->getNode(I2->getParent()); 10761 assert(NodeI1 && "Should only process reachable instructions"); 10762 assert(NodeI1 && "Should only process reachable instructions"); 10763 assert((NodeI1 == NodeI2) == 10764 (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) && 10765 "Different nodes should have different DFS numbers"); 10766 if (NodeI1 != NodeI2) 10767 return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn(); 10768 InstructionsState S = getSameOpcode({I1, I2}); 10769 if (S.getOpcode()) 10770 return false; 10771 return I1->getOpcode() < I2->getOpcode(); 10772 } 10773 if (isa<Constant>(V->getValueOperand()) && 10774 isa<Constant>(V2->getValueOperand())) 10775 return false; 10776 return V->getValueOperand()->getValueID() < 10777 V2->getValueOperand()->getValueID(); 10778 }; 10779 10780 auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) { 10781 if (V1 == V2) 10782 return true; 10783 if (V1->getPointerOperandType() != V2->getPointerOperandType()) 10784 return false; 10785 // Undefs are compatible with any other value. 10786 if (isa<UndefValue>(V1->getValueOperand()) || 10787 isa<UndefValue>(V2->getValueOperand())) 10788 return true; 10789 if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand())) 10790 if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) { 10791 if (I1->getParent() != I2->getParent()) 10792 return false; 10793 InstructionsState S = getSameOpcode({I1, I2}); 10794 return S.getOpcode() > 0; 10795 } 10796 if (isa<Constant>(V1->getValueOperand()) && 10797 isa<Constant>(V2->getValueOperand())) 10798 return true; 10799 return V1->getValueOperand()->getValueID() == 10800 V2->getValueOperand()->getValueID(); 10801 }; 10802 auto Limit = [&R, this](StoreInst *SI) { 10803 unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType()); 10804 return R.getMinVF(EltSize); 10805 }; 10806 10807 // Attempt to sort and vectorize each of the store-groups. 10808 for (auto &Pair : Stores) { 10809 if (Pair.second.size() < 2) 10810 continue; 10811 10812 LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " 10813 << Pair.second.size() << ".\n"); 10814 10815 if (!isValidElementType(Pair.second.front()->getValueOperand()->getType())) 10816 continue; 10817 10818 Changed |= tryToVectorizeSequence<StoreInst>( 10819 Pair.second, Limit, StoreSorter, AreCompatibleStores, 10820 [this, &R](ArrayRef<StoreInst *> Candidates, bool) { 10821 return vectorizeStores(Candidates, R); 10822 }, 10823 /*LimitForRegisterSize=*/false); 10824 } 10825 return Changed; 10826 } 10827 10828 char SLPVectorizer::ID = 0; 10829 10830 static const char lv_name[] = "SLP Vectorizer"; 10831 10832 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false) 10833 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass) 10834 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 10835 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 10836 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass) 10837 INITIALIZE_PASS_DEPENDENCY(LoopSimplify) 10838 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass) 10839 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass) 10840 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy) 10841 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false) 10842 10843 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); } 10844